<?php

class PointagesController {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }

    /**
     * Récupère les statistiques et la liste des pointages pour le tableau de bord
     */
    public function getDashboardData() {
        $date = $_GET['date'] ?? date('Y-m-d');

        try {
            // 1- Bus Disponible = tous les enregistrements de la table "buses" avec champ "type"=Bus avec le champ actif=1
            $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'];

            // 2- Taxi Disponible : tous les enregistrements de la table "buses" avec champ "type"=Taxi avec le champ actif=1
            $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'];

            // 3- Bus Pointer : Distinct bus_id from checkins where bus is a Bus
            $stmt = $this->db->prepare("
                SELECT COUNT(DISTINCT c.bus_id) as count 
                FROM checkins c 
                INNER JOIN buses b ON c.bus_id = b.id 
                WHERE b.type = 'Bus' AND c.checkin_date = ?
            ");
            $stmt->execute([$date]);
            $busPointer = $stmt->fetch(PDO::FETCH_ASSOC)['count'];

            // 4- Taxi Pointer : Distinct bus_id from checkins where bus is a Taxi
            $stmt = $this->db->prepare("
                SELECT COUNT(DISTINCT c.bus_id) as count 
                FROM checkins c 
                INNER JOIN buses b ON c.bus_id = b.id 
                WHERE b.type = 'Taxi' AND c.checkin_date = ?
            ");
            $stmt->execute([$date]);
            $taxiPointer = $stmt->fetch(PDO::FETCH_ASSOC)['count'];

            // 5- Bus Absent : Bus Disponible – Bus Pointer
            $busAbsent = max(0, $busDisponible - $busPointer);

            // 6- Taxi Absent : Taxi Disponible – Taxi Pointer
            $taxiAbsent = max(0, $taxiDisponible - $taxiPointer);

            // Récupérer la liste des pointages avec les jointures demandées
            $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
                INNER JOIN buses b ON c.bus_id = b.id
                LEFT JOIN operators o ON b.id_operateur = o.id
                LEFT JOIN lignes l ON b.id_ligne = l.ligne_code
                LEFT JOIN agents a ON c.agent_id = a.id
                WHERE c.checkin_date = ?
                ORDER BY c.checkin_time DESC
            ");
            $stmt->execute([$date]);
            $pointages = $stmt->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode([
                'success' => true,
                'busDisponible' => $busDisponible,
                'busPointer' => $busPointer,
                'busAbsent' => $busAbsent,
                'taxiDisponible' => $taxiDisponible,
                'taxiPointer' => $taxiPointer,
                'taxiAbsent' => $taxiAbsent,
                'pointages' => $pointages
            ]);
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Erreur: ' . $e->getMessage()]);
        }
    }

    /**
     * Récupère les détails d'une catégorie (Disponible, Pointer, Absent)
     */
    public function getDetails() {
        $type = $_GET['type'] ?? ''; // 'Bus' ou 'Taxi'
        $category = $_GET['category'] ?? ''; // 'Disponible', 'Pointer', 'Absent'
        $date = $_GET['date'] ?? date('Y-m-d');

        try {
            if ($category === 'Disponible') {
                $stmt = $this->db->prepare("
                    SELECT b.matricule, b.type, o.name as operateur, l.name as ligne
                    FROM buses b
                    LEFT JOIN operators o ON b.id_operateur = o.id
                    LEFT JOIN lignes l ON b.id_ligne = l.ligne_code
                    WHERE b.type = ? AND b.actif = 1
                    ORDER BY b.matricule ASC
                ");
                $stmt->execute([$type]);
            } elseif ($category === 'Pointer') {
                $stmt = $this->db->prepare("
                    SELECT DISTINCT b.matricule, b.type, o.name as operateur, l.name as ligne, c.checkin_time as time, a.full_name as agent
                    FROM checkins c
                    INNER JOIN buses b ON c.bus_id = b.id
                    LEFT JOIN operators o ON b.id_operateur = o.id
                    LEFT JOIN lignes l ON b.id_ligne = l.ligne_code
                    LEFT JOIN agents a ON c.agent_id = a.id
                    WHERE b.type = ? AND c.checkin_date = ?
                    ORDER BY c.checkin_time DESC
                ");
                $stmt->execute([$type, $date]);
            } elseif ($category === 'Absent') {
                // Ceux qui sont actifs mais n'ont pas de pointage à cette date
                $stmt = $this->db->prepare("
                    SELECT b.matricule, b.type, o.name as operateur, l.name as ligne
                    FROM buses b
                    LEFT JOIN operators o ON b.id_operateur = o.id
                    LEFT JOIN lignes l ON b.id_ligne = l.ligne_code
                    WHERE b.type = ? AND b.actif = 1
                    AND b.id NOT IN (SELECT bus_id FROM checkins WHERE checkin_date = ?)
                    ORDER BY b.matricule ASC
                ");
                $stmt->execute([$type, $date]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Catégorie invalide']);
                return;
            }

            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode([
                'success' => true,
                'count' => count($results),
                'details' => $results
            ]);
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Erreur: ' . $e->getMessage()]);
        }
    }
}
