<?php

namespace App\Modules\Attendance\Controllers;

use App\Core\BaseApiController;
use App\Modules\Attendance\Services\AttendanceCheckinService;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Attendance Controller
 * 
 * Handles attendance check-in endpoints.
 */
class AttendanceController extends BaseApiController
{
    protected AttendanceCheckinService $checkinService;

    public function __construct()
    {
        $this->checkinService = new AttendanceCheckinService();
    }

    /**
     * Attendance check-in endpoint
     * 
     * POST /api/attendance/checkin
     * Body: {
     *   "device_code": "",
     *   "api_key": "",
     *   "student_id": 0,
     *   "datetime": "Y-m-d H:i:s",
     *   "lat": 0.0,
     *   "lng": 0.0,
     *   "confidence": 0.0 (optional)
     * }
     * 
     * @return ResponseInterface
     */
    public function checkin(): ResponseInterface
    {
        // Get JSON input
        $input = $this->request->getJSON(true);

        // Validate required fields
        $requiredFields = ['device_code', 'api_key', 'student_id', 'datetime', 'lat', 'lng'];
        foreach ($requiredFields as $field) {
            if (!isset($input[$field])) {
                return $this->errorResponse(
                    "Field '{$field}' is required",
                    null,
                    null,
                    400
                );
            }
        }

        // Process check-in
        try {
            $result = $this->checkinService->checkin($input);

            // Determine message based on status
            $messages = [
                'PRESENT'                  => 'Attendance recorded successfully',
                'LATE'                     => 'Attendance recorded but marked as late',
                'OUTSIDE_ZONE'             => 'Check-in failed: Location outside school zone',
                'NO_SCHEDULE'              => 'Check-in failed: No active schedule found',
                'INVALID_DEVICE'           => 'Check-in failed: Invalid device credentials',
                'ALREADY_CHECKED_IN'       => 'Already checked in for this schedule today',
                'ABSENCE_WINDOW_CLOSED'    => 'Check-in failed: Outside attendance window',
                'SESSION_CLOSED'           => 'Attendance session closed',
            ];

            $message = $messages[$result['status']] ?? 'Attendance check-in processed';

            // Return success response (even for failures, as the record is saved)
            return $this->successResponse(
                $result,
                $message
            );
        } catch (\Exception $e) {
            return $this->errorResponse(
                'An error occurred while processing check-in',
                ['error' => $e->getMessage()],
                null,
                500
            );
        }
    }
}
