<?php
/**
 * Bus Controller
 * Handles bus management and QR scanning operations
 */

class BusController {
    private $db;
    private $busModel;
    private $checkinModel;

    public function __construct($db) {
        $this->db = $db;
        require_once __DIR__ . '/../models/Bus.php';
        require_once __DIR__ . '/../models/Checkin.php';
        $this->busModel = new Bus($this->db);
        $this->checkinModel = new Checkin($this->db);
    }

    /**
     * Get all buses
     */
    public function getAll() {
        Auth::requireAuth(); // Any authenticated user can view buses

        $filters = [];

        // Parse query parameters
        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['actif'])) {
            $filters['status'] = (int)$_GET['actif'] === 1 ? 'Active' : 'Inactive';
        }

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

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

        $buses = $this->busModel->getAll($filters);

        Auth::sendSuccess($buses, 'Buses retrieved successfully');
    }

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

        $bus = $this->busModel->getById($id);

        if ($bus) {
            Auth::sendSuccess($bus, 'Bus retrieved successfully');
        } else {
            Auth::sendError('Bus not found', 404);
        }
    }

    /**
     * Scan QR code and create check-in
     */
    public function scanQR() {
        $user = Auth::requireAgent(); // Only agents can scan QR codes

        $data = Auth::getRequestBody();

        if (!isset($data['qr_code'])) {
            Auth::sendError('QR code is required', 400);
        }

        $qrCode = trim($data['qr_code']);

        if (empty($qrCode)) {
            Auth::sendError('QR code cannot be empty', 400);
        }

        // Find bus by QR code
        $bus = $this->busModel->getByQRCode($qrCode);

        if (!$bus) {
            Auth::sendError('Invalid QR code or bus not found', 404);
        }

        // Check if bus was checked in within the last 30 minutes
        $checkedInRecently = $this->checkinModel->hasCheckedInRecently($bus['id']);

        if ($checkedInRecently) {
            Auth::sendError('Bus déjà pointé récemment (moins de 30 minutes)', 409);
        }

        // Create check-in record - use MySQL time for consistency
        $query = "SELECT NOW() as mysql_now";
        $stmt = $this->db->prepare($query);
        $stmt->execute();
        $mysql_time = $stmt->fetch(PDO::FETCH_ASSOC)['mysql_now'];

        $checkinData = [
            'bus_id' => $bus['id'],
            'agent_id' => $user['id'],
            'checkin_date' => date('Y-m-d', strtotime($mysql_time)),
            'checkin_time' => date('H:i:s', strtotime($mysql_time)),
            'location' => $data['location'] ?? (isset($data['latitude']) ? "GPS: " . $data['latitude'] . ", " . $data['longitude'] : 'Boumerdes Bus Station'),
            'latitude' => $data['latitude'] ?? null,
            'longitude' => $data['longitude'] ?? null,
            'notes' => $data['notes'] ?? null,
            'is_valid' => true
        ];

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

        if ($checkinId) {
            // Return bus info with check-in details
            $response = [
                'bus' => $bus,
                'checkin' => [
                    'id' => $checkinId,
                    'checkin_time' => $checkinData['checkin_time'],
                    'checkin_date' => $checkinData['checkin_date'],
                    'location' => $checkinData['location'],
                    'agent_name' => $user['full_name']
                ]
            ];

            Auth::sendSuccess($response, 'Check-in successful');
        } else {
            Auth::sendError('Failed to create check-in record', 500);
        }
    }

    /**
     * Create new bus (Admin only)
     */
    public function create() {
        Auth::requireAdmin();

        $data = Auth::getRequestBody();

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

        // Check if matricule already exists
        if ($this->busModel->matriculeExists($data['matricule'])) {
            Auth::sendError('Matricule already exists', 409);
        }

        // Create bus
        $busId = $this->busModel->create($data);

        if ($busId) {
            $bus = $this->busModel->getById($busId);
            Auth::sendSuccess($bus, 'Bus created successfully', 201);
        } else {
            Auth::sendError('Failed to create bus', 500);
        }
    }

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

        $data = Auth::getRequestBody();

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

        // Check if bus exists
        $existingBus = $this->busModel->getById($id);
        if (!$existingBus) {
            Auth::sendError('Bus not found', 404);
        }

        // Check matricule uniqueness if being updated
        if (isset($data['matricule']) && $data['matricule'] !== $existingBus['matricule']) {
            if ($this->busModel->matriculeExists($data['matricule'], $id)) {
                Auth::sendError('Matricule already exists', 409);
            }
        }

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

        if ($success) {
            $updatedBus = $this->busModel->getById($id);
            Auth::sendSuccess($updatedBus, 'Bus updated successfully');
        } else {
            Auth::sendError('Failed to update bus', 500);
        }
    }

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

        // Check if bus exists
        $bus = $this->busModel->getById($id);
        if (!$bus) {
            Auth::sendError('Bus not found', 404);
        }

        // Check if bus has check-ins (we'll allow deletion but log it)
        $checkinsCount = $this->checkinModel->getAll(['bus_id' => $id]);
        $hasCheckins = !empty($checkinsCount);

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

        if ($success) {
            $message = $hasCheckins ?
                'Bus deleted successfully (Note: Bus had existing check-in records)' :
                'Bus deleted successfully';

            Auth::sendSuccess(null, $message);
        } else {
            Auth::sendError('Failed to delete bus', 500);
        }
    }

    /**
     * Get buses checked in today
     */
    public function getCheckedInToday() {
        Auth::requireAuth();

        $date = $_GET['date'] ?? date('Y-m-d');
        $buses = $this->busModel->getCheckedInToday($date);

        Auth::sendSuccess($buses, 'Checked-in buses retrieved successfully');
    }

    /**
     * Get buses absent today
     */
    public function getAbsentToday() {
        Auth::requireAuth();

        $date = $_GET['date'] ?? date('Y-m-d');
        $buses = $this->busModel->getAbsentToday($date);

        Auth::sendSuccess($buses, 'Absent buses retrieved successfully');
    }

    /**
     * Validate QR code (without creating check-in)
     */
    public function validateQR() {
        $user = Auth::requireAgent();

        $data = Auth::getRequestBody();

        if (!isset($data['qr_code'])) {
            Auth::sendError('QR code is required', 400);
        }

        $qrCode = trim($data['qr_code']);

        // Find bus by QR code
        $bus = $this->busModel->getByQRCode($qrCode);

        if (!$bus) {
            Auth::sendError('Invalid QR code or bus not found', 404);
        }

        // Check if bus already checked in today
        $alreadyCheckedIn = $this->checkinModel->hasCheckedInToday($bus['id']);

        $response = [
            'bus' => $bus,
            'can_checkin' => !$alreadyCheckedIn,
            'already_checked_in' => $alreadyCheckedIn
        ];

        if ($alreadyCheckedIn) {
            $response['message'] = 'Bus has already been checked in today';
        } else {
            $response['message'] = 'QR code is valid for check-in';
        }

        Auth::sendSuccess($response, 'QR code validated');
    }
}
?>
