<?php

namespace App\Modules\Devices\Controllers;

use App\Core\BaseApiController;
use App\Modules\Devices\Models\DeviceModel;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Device Controller
 *
 * Admin-only management for device configuration (geo-fence, etc).
 */
class DeviceController extends BaseApiController
{
    /**
     * PUT /api/devices/{id}
     *
     * Body (JSON):
     * - latitude: float|null
     * - longitude: float|null
     * - radius_meters: int|null
     */
    public function update($id): ResponseInterface
    {
        $id = (int) $id;
        if ($id <= 0) {
            return $this->errorResponse('Invalid device id', null, null, ResponseInterface::HTTP_BAD_REQUEST);
        }

        $payload = $this->request->getJSON(true) ?? [];

        $lat = $payload['latitude'] ?? null;
        $lng = $payload['longitude'] ?? null;
        $radius = $payload['radius_meters'] ?? null;

        // Normalize empty strings to null
        $lat = ($lat === '' || $lat === null) ? null : $lat;
        $lng = ($lng === '' || $lng === null) ? null : $lng;
        $radius = ($radius === '' || $radius === null) ? null : $radius;

        // Basic validation
        if ($lat !== null && !is_numeric($lat)) {
            return $this->errorResponse('Latitude harus berupa angka atau kosong', null, null, ResponseInterface::HTTP_UNPROCESSABLE_ENTITY);
        }
        if ($lng !== null && !is_numeric($lng)) {
            return $this->errorResponse('Longitude harus berupa angka atau kosong', null, null, ResponseInterface::HTTP_UNPROCESSABLE_ENTITY);
        }
        if ($radius !== null && (!is_numeric($radius) || (int) $radius < 0)) {
            return $this->errorResponse('Radius harus berupa angka >= 0 atau kosong', null, null, ResponseInterface::HTTP_UNPROCESSABLE_ENTITY);
        }

        // If one of lat/lng/radius set, require all three
        $hasAny = $lat !== null || $lng !== null || $radius !== null;
        if ($hasAny) {
            if ($lat === null || $lng === null || $radius === null) {
                return $this->errorResponse('Jika mengatur zona, latitude, longitude, dan radius wajib diisi semua', null, null, ResponseInterface::HTTP_UNPROCESSABLE_ENTITY);
            }
        }

        $data = [
            'latitude'      => $lat !== null ? (float) $lat : null,
            'longitude'     => $lng !== null ? (float) $lng : null,
            'radius_meters' => $radius !== null ? (int) $radius : null,
        ];

        $model = new DeviceModel();
        $device = $model->find($id);
        if (!$device) {
            return $this->errorResponse('Device tidak ditemukan', null, null, ResponseInterface::HTTP_NOT_FOUND);
        }

        if (!$model->update($id, $data)) {
            return $this->errorResponse('Gagal menyimpan konfigurasi device', $model->errors(), null, ResponseInterface::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->successResponse(null, 'Konfigurasi geo-fence device berhasil disimpan');
    }
}

