<?php

namespace App\Modules\Dashboard\Controllers;

use App\Core\BaseApiController;
use App\Modules\Dashboard\Models\SchoolPresenceSettingsModel;
use App\Modules\Geo\Models\ZoneModel;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * API: Pengaturan Presensi terpusat (zona sekolah + jam masuk/pulang).
 * GET /api/dashboard/presence-settings
 * PUT /api/dashboard/presence-settings
 */
class PresenceSettingsController extends BaseApiController
{
    protected const ZONE_CODE = 'SMA1-SCHOOL';

    /**
     * GET /api/dashboard/presence-settings
     * Returns zone (lat, lng, radius) + jam masuk/pulang.
     */
    public function index(): ResponseInterface
    {
        $zoneModel = new ZoneModel();
        $settingsModel = new SchoolPresenceSettingsModel();

        $zone = $zoneModel->findActiveByZoneCode(self::ZONE_CODE);
        if (!$zone) {
            $zones = $zoneModel->findAllActive();
            $zone = !empty($zones) ? $zones[0] : null;
        }

        $zoneData = null;
        if ($zone) {
            $zoneData = [
                'zone_code'     => $zone->zone_code,
                'zone_name'     => $zone->zone_name,
                'latitude'      => (float) $zone->latitude,
                'longitude'     => (float) $zone->longitude,
                'radius_meters' => (int) $zone->radius_meters,
            ];
        } else {
            $zoneData = [
                'zone_code'     => self::ZONE_CODE,
                'zone_name'     => 'Zona Sekolah',
                'latitude'      => 0.0,
                'longitude'     => 0.0,
                'radius_meters' => 150,
            ];
        }

        $times = $settingsModel->getSettings();

        $data = [
            'zone'  => $zoneData,
            'times' => $times,
        ];

        return $this->successResponse($data, 'Pengaturan presensi');
    }

    /**
     * PUT /api/dashboard/presence-settings
     * Body: { zone: { latitude, longitude, radius_meters }, times: { time_masuk_start, time_masuk_end, time_pulang_start, time_pulang_end } }
     */
    public function update(): ResponseInterface
    {
        $body = $this->request->getJSON(true) ?? [];
        $zoneModel = new ZoneModel();
        $settingsModel = new SchoolPresenceSettingsModel();

        $zone = $zoneModel->findByZoneCode(self::ZONE_CODE);
        $zoneInput = $body['zone'] ?? [];

        if (!empty($zoneInput)) {
            $lat    = isset($zoneInput['latitude']) ? (float) $zoneInput['latitude'] : null;
            $lng    = isset($zoneInput['longitude']) ? (float) $zoneInput['longitude'] : null;
            $radius = isset($zoneInput['radius_meters']) ? (int) $zoneInput['radius_meters'] : null;

            if ($lat !== null && $lng !== null && $radius !== null && $radius > 0) {
                $zonePayload = [
                    'latitude'      => $lat,
                    'longitude'     => $lng,
                    'radius_meters' => $radius,
                    'zone_name'     => $zoneInput['zone_name'] ?? 'Zona Sekolah',
                    'is_active'     => 1,
                ];
                if ($zone) {
                    $zoneModel->update($zone->id, $zonePayload);
                } else {
                    $zonePayload['zone_code'] = self::ZONE_CODE;
                    $zoneModel->insert($zonePayload);
                }
            }
        }

        $timesInput = $body['times'] ?? [];
        if (!empty($timesInput)) {
            $settingsModel->saveSettings([
                'time_masuk_start'  => $timesInput['time_masuk_start'] ?? null,
                'time_masuk_end'    => $timesInput['time_masuk_end'] ?? null,
                'time_pulang_start' => $timesInput['time_pulang_start'] ?? null,
                'time_pulang_end'   => $timesInput['time_pulang_end'] ?? null,
            ]);
        }

        $z = $zoneModel->findActiveByZoneCode(self::ZONE_CODE);
        $data = [
            'zone'  => $z ? [
                'zone_code'     => $z->zone_code,
                'latitude'      => (float) $z->latitude,
                'longitude'     => (float) $z->longitude,
                'radius_meters' => (int) $z->radius_meters,
            ] : null,
            'times' => $settingsModel->getSettings(),
        ];

        return $this->successResponse($data, 'Pengaturan presensi berhasil disimpan');
    }
}
