<?php
/**
 * Pointages Boumerdes Controller
 * Handles pointages Boumerdes operations
 */

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

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

    /**
     * Get pointages Boumerdes data for dashboard
     */
    public function getDashboardData() {
        Auth::requireAuth();

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

        if ($action == 'details') {
            // Récupérer les détails des buses/taxis disponibles
            $this->getAvailableBuses($type);
        } elseif ($action == 'pointer') {
            // Récupérer les détails des pointer
            $this->getCheckedInBuses($type, $date);
        } elseif ($action == 'absent') {
            // Récupérer le nombre de buses/taxis absents
            $this->getAbsentBuses($type, $date);
        } else {
            // Action par défaut : récupérer les données pour la page principale
            $this->getDefaultData($date);
        }
    }

    /**
     * Get available buses/taxis count
     */
    private function getAvailableBuses($type) {
        $query = "SELECT COUNT(*) as count FROM buses WHERE type = ? AND actif = 1";
        $stmt = $this->db->prepare($query);
        $stmt->execute([$type]);
        $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
        Auth::sendSuccess(['count' => $count], 'Available buses/taxis count retrieved successfully');
    }

    /**
     * Get checked in buses/taxis details
     */
    private function getCheckedInBuses($type, $date) {
        $query = "
            SELECT 
                c.id,
                b.matricule,
                b.type,
                o.name as operateur,
                l.name as ligne,
                c.checkin_date as date,
                c.checkin_time as time,
                a.full_name as agent,
                c.latitude,
                c.longitude
            FROM checkins c
            JOIN buses b ON c.bus_id = b.id
            JOIN agents a ON c.agent_id = a.id
            LEFT JOIN operators o ON b.id_operateur = o.id
            LEFT JOIN lignes l ON b.id_ligne = l.id
            WHERE c.checkin_date = ? AND b.type = ?
            ORDER BY c.checkin_time ASC
        ";
        $stmt = $this->db->prepare($query);
        $stmt->execute([$date, $type]);
        $pointages = $stmt->fetchAll(PDO::FETCH_ASSOC);
        Auth::sendSuccess(['count' => count($pointages), 'pointages' => $pointages], 'Checked in buses/taxis details retrieved successfully');
    }

    /**
     * Get absent buses/taxis count
     */
    private function getAbsentBuses($type, $date) {
        // Récupérer le nombre de buses/taxis disponibles
        $query = "SELECT COUNT(*) as count FROM buses WHERE type = ? AND actif = 1";
        $stmt = $this->db->prepare($query);
        $stmt->execute([$type]);
        $disponible = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
        
        // Récupérer le nombre de buses/taxis pointer
        $query = "
            SELECT COUNT(*) as count 
            FROM checkins 
            JOIN buses ON checkins.bus_id = buses.id 
            WHERE checkins.checkin_date = ? AND buses.type = ?
        ";
        $stmt = $this->db->prepare($query);
        $stmt->execute([$date, $type]);
        $pointer = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
        
        $absent = $disponible - $pointer;
        Auth::sendSuccess(['count' => $absent], 'Absent buses/taxis count retrieved successfully');
    }

    /**
     * Get default dashboard data
     */
    private function getDefaultData($date) {
        // Récupérer les buses disponibles
        $stmt = $this->db->prepare("SELECT COUNT(*) as count FROM buses WHERE type = 'Bus' AND actif = 1");
        $stmt->execute();
        $busDisponible = $stmt->fetch(PDO::FETCH_ASSOC)['count'];

        // Récupérer les taxis disponibles
        $stmt = $this->db->prepare("SELECT COUNT(*) as count FROM buses WHERE type = 'Taxi' AND actif = 1");
        $stmt->execute();
        $taxiDisponible = $stmt->fetch(PDO::FETCH_ASSOC)['count'];

        // Récupérer les buses pointer
        $stmt = $this->db->prepare("
            SELECT COUNT(*) as count 
            FROM checkins 
            JOIN buses ON checkins.bus_id = buses.id 
            WHERE checkins.checkin_date = ? AND buses.type = 'Bus'
        ");
        $stmt->execute([$date]);
        $busPointer = $stmt->fetch(PDO::FETCH_ASSOC)['count'];

        // Récupérer les taxis pointer
        $stmt = $this->db->prepare("
            SELECT COUNT(*) as count 
            FROM checkins 
            JOIN buses ON checkins.bus_id = buses.id 
            WHERE checkins.checkin_date = ? AND buses.type = 'Taxi'
        ");
        $stmt->execute([$date]);
        $taxiPointer = $stmt->fetch(PDO::FETCH_ASSOC)['count'];

        // Calculer les absent
        $busAbsent = $busDisponible - $busPointer;
        $taxiAbsent = $taxiDisponible - $taxiPointer;

        // Récupérer les pointages pour le tableau
        $stmt = $this->db->prepare("
            SELECT 
                c.id,
                b.matricule,
                b.type,
                o.name as operateur,
                l.name as ligne,
                c.checkin_date as date,
                c.checkin_time as time,
                a.full_name as agent,
                c.latitude,
                c.longitude
            FROM checkins c
            JOIN buses b ON c.bus_id = b.id
            JOIN agents a ON c.agent_id = a.id
            LEFT JOIN operators o ON b.id_operateur = o.id
            LEFT JOIN lignes l ON b.id_ligne = l.id
            WHERE c.checkin_date = ?
            ORDER BY c.checkin_time ASC
        ");
        $stmt->execute([$date]);
        $pointages = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Réponse JSON
        $data = [
            'busDisponible' => $busDisponible,
            'taxiDisponible' => $taxiDisponible,
            'busPointer' => $busPointer,
            'taxiPointer' => $taxiPointer,
            'busAbsent' => $busAbsent,
            'taxiAbsent' => $taxiAbsent,
            'pointages' => $pointages
        ];
        Auth::sendSuccess($data, 'Dashboard data retrieved successfully');
    }
}
?>