<?php

namespace App\Modules\Devices\Controllers;

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

/**
 * Mobile Support Controller
 *
 * Endpoints for Android app (ping, bootstrap). No authentication required.
 */
class MobileController extends BaseApiController
{
    /**
     * Default check-in late tolerance in minutes (must match AttendanceCheckinService)
     */
    protected int $checkinToleranceMinutes = 10;

    /**
     * GET /api/mobile/ping
     *
     * @return ResponseInterface
     */
    public function ping(): ResponseInterface
    {
        $data = [
            'server_time' => date('Y-m-d H:i:s'),
            'api_version' => '1.0',
        ];
        return $this->successResponse($data, 'Mobile connected');
    }

    /**
     * GET /api/mobile/bootstrap
     *
     * Returns active zones, device validation rules, and checkin tolerance for app startup.
     *
     * @return ResponseInterface
     */
    public function bootstrap(): ResponseInterface
    {
        $zoneModel = new ZoneModel();
        $activeZones = $zoneModel->findAllActive();

        $zonesData = [];
        foreach ($activeZones as $zone) {
            $zonesData[] = [
                'zone_code'     => $zone->zone_code,
                'zone_name'     => $zone->zone_name,
                'latitude'      => (float) $zone->latitude,
                'longitude'     => (float) $zone->longitude,
                'radius_meters' => (int) $zone->radius_meters,
            ];
        }

        $data = [
            'server_timestamp'          => gmdate('Y-m-d\TH:i:s\Z'), // ISO 8601 UTC — for device_time_offset = server_time - device_time
            'server_timezone'           => 'Asia/Jakarta',           // WIB — for display / jadwal sekolah
            'active_zones'              => $zonesData,
            'device_validation_rules'   => [
                'require_device_code' => true,
                'require_api_key'     => true,
            ],
            'checkin_tolerance_minutes' => $this->checkinToleranceMinutes,
        ];

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