<?php
/**
 * Check-in Controller
 * Handles check-in record management
 */

class CheckinController {
    private $db;
    private $checkinModel;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
        $this->checkinModel = new Checkin($this->db);
    }

    /**
     * Get all check-ins
     */
    public function getAll() {
        Auth::requireAuth();

        $filters = [];

        // Parse query parameters
        if (isset($_GET['bus_id'])) {
            $filters['bus_id'] = (int)$_GET['bus_id'];
        }

        if (isset($_GET['agent_id'])) {
            $filters['agent_id'] = (int)$_GET['agent_id'];
        }

        if (isset($_GET['date'])) {
            $filters['date'] = $_GET['date'];
        }

        if (isset($_GET['date_from']) && isset($_GET['date_to'])) {
            $filters['date_from'] = $_GET['date_from'];
            $filters['date_to'] = $_GET['date_to'];
        }

        if (isset($_GET['id_operateur'])) {
            $filters['id_operateur'] = (int)$_GET['id_operateur'];
        }

        if (isset($_GET['id_ligne'])) {
            $filters['id_ligne'] = (int)$_GET['id_ligne'];
        }

        if (isset($_GET['is_valid'])) {
            $filters['is_valid'] = (int)$_GET['is_valid'];
        }

        if (isset($_GET['limit'])) {
            $filters['limit'] = (int)$_GET['limit'];
        }

        $checkins = $this->checkinModel->getAll($filters);

        Auth::sendSuccess($checkins, 'Check-ins retrieved successfully');
    }

    /**
     * Get check-in by ID
     */
    public function getById($id) {
        Auth::requireAuth();

        $checkin = $this->checkinModel->getById($id);

        if ($checkin) {
            Auth::sendSuccess($checkin, 'Check-in retrieved successfully');
        } else {
            Auth::sendError('Check-in not found', 404);
        }
    }

    /**
     * Create new check-in (Admin only - for manual entry)
     */
    public function create() {
        Auth::requireAdmin();

        $data = Auth::getRequestBody();

        // Validate required fields
        $requiredFields = ['bus_id', 'agent_id', 'checkin_date'];
        foreach ($requiredFields as $field) {
            if (!isset($data[$field]) || empty($data[$field])) {
                Auth::sendError("Field '$field' is required", 400);
            }
        }

        // Set default time if not provided - use MySQL time for consistency
        if (!isset($data['checkin_time'])) {
            $database = new Database();
            $conn = $database->getConnection();
            $mysql_time = $database->getCurrentTime($conn);
            $database->closeConnection();
            $data['checkin_time'] = date('H:i:s', strtotime($mysql_time));
        }

        // Prevent duplicate check-ins
        if ($this->checkinModel->hasCheckedInToday($data['bus_id'], $data['checkin_date'])) {
            Auth::sendError('Bus has already been checked in on this date', 409);
        }

        $checkinId = $this->checkinModel->create($data);

        if ($checkinId) {
            $checkin = $this->checkinModel->getById($checkinId);
            Auth::sendSuccess($checkin, 'Check-in created successfully', 201);
        } else {
            Auth::sendError('Failed to create check-in', 500);
        }
    }

    /**
     * Update check-in (Admin only)
     */
    public function update($id) {
        Auth::requireAdmin();

        $data = Auth::getRequestBody();

        if (empty($data)) {
            Auth::sendError('No data provided for update', 400);
        }

        // Check if check-in exists
        $existingCheckin = $this->checkinModel->getById($id);
        if (!$existingCheckin) {
            Auth::sendError('Check-in not found', 404);
        }

        $success = $this->checkinModel->update($id, $data);

        if ($success) {
            $updatedCheckin = $this->checkinModel->getById($id);
            Auth::sendSuccess($updatedCheckin, 'Check-in updated successfully');
        } else {
            Auth::sendError('Failed to update check-in', 500);
        }
    }

    /**
     * Delete check-in (Admin only)
     */
    public function delete($id) {
        Auth::requireAdmin();

        // Check if check-in exists
        $checkin = $this->checkinModel->getById($id);
        if (!$checkin) {
            Auth::sendError('Check-in not found', 404);
        }

        $success = $this->checkinModel->delete($id);

        if ($success) {
            Auth::sendSuccess(null, 'Check-in deleted successfully');
        } else {
            Auth::sendError('Failed to delete check-in', 500);
        }
    }

    /**
     * Get check-ins for current user (agent)
     */
    public function getMyCheckins() {
        $user = Auth::requireAuth();

        $filters = ['agent_id' => $user['id']];

        // Parse additional filters
        if (isset($_GET['date'])) {
            $filters['date'] = $_GET['date'];
        }

        if (isset($_GET['date_from']) && isset($_GET['date_to'])) {
            $filters['date_from'] = $_GET['date_from'];
            $filters['date_to'] = $_GET['date_to'];
        }

        if (isset($_GET['limit'])) {
            $filters['limit'] = (int)$_GET['limit'];
        }

        $checkins = $this->checkinModel->getAll($filters);

        Auth::sendSuccess($checkins, 'Your check-ins retrieved successfully');
    }

    /**
     * Get check-in statistics
     */
    public function getStats() {
        Auth::requireAuth();

        $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
        $dateTo = $_GET['date_to'] ?? date('Y-m-d');

        $stats = $this->checkinModel->getStats($dateFrom, $dateTo);

        Auth::sendSuccess($stats, 'Check-in statistics retrieved successfully');
    }

    /**
     * Get most active agents
     */
    public function getMostActiveAgents() {
        Auth::requireAdmin(); // Only admins can see agent activity

        $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
        $dateTo = $_GET['date_to'] ?? date('Y-m-d');
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;

        $agents = $this->checkinModel->getMostActiveAgents($dateFrom, $dateTo, $limit);

        Auth::sendSuccess($agents, 'Most active agents retrieved successfully');
    }

    /**
     * Get check-ins by hour for today
     */
    public function getCheckinsByHour() {
        Auth::requireAuth();

        $date = $_GET['date'] ?? date('Y-m-d');

        $hourlyStats = $this->checkinModel->getCheckinsByHour($date);

        Auth::sendSuccess($hourlyStats, 'Hourly check-in statistics retrieved successfully');
    }

    /**
     * Invalidate a check-in (mark as invalid)
     */
    public function invalidate($id) {
        Auth::requireAdmin();

        $success = $this->checkinModel->update($id, ['is_valid' => false]);

        if ($success) {
            Auth::sendSuccess(null, 'Check-in invalidated successfully');
        } else {
            Auth::sendError('Failed to invalidate check-in', 500);
        }
    }

    /**
     * Validate a check-in (mark as valid)
     */
    public function validate($id) {
        Auth::requireAdmin();

        $success = $this->checkinModel->update($id, ['is_valid' => true]);

        if ($success) {
            Auth::sendSuccess(null, 'Check-in validated successfully');
        } else {
            Auth::sendError('Failed to validate check-in', 500);
        }
    }
}
?>
