<?php
/**
 * API pour les pointages Boumerdes (Version Distante)
 * À installer sur le serveur cPanel dans le dossier api/apiggr/ (ou apipointage/)
 */

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once __DIR__ . '/../config/database.php';

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

try {
    $db = Database::getInstance();

    switch ($action) {
        case 'dashboard':
            $busDisponible = $db->selectOne("SELECT COUNT(*) as count FROM buses WHERE type = 'Bus' AND actif = 1")['count'];
            $taxiDisponible = $db->selectOne("SELECT COUNT(*) as count FROM buses WHERE type = 'Taxi' AND actif = 1")['count'];

            $queryBus = "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'";
            $paramsBus = [];
            if ($date) {
                $queryBus .= " AND c.checkin_date = ?";
                $paramsBus[] = $date;
            }
            $busPointer = $db->selectOne($queryBus, $paramsBus)['count'];

            $queryTaxi = "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'";
            $paramsTaxi = [];
            if ($date) {
                $queryTaxi .= " AND c.checkin_date = ?";
                $paramsTaxi[] = $date;
            }
            $taxiPointer = $db->selectOne($queryTaxi, $paramsTaxi)['count'];

            $busAbsent = $busDisponible - $busPointer;
            $taxiAbsent = $taxiDisponible - $taxiPointer;

            $queryPointages = "
                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
            ";
            
            $paramsPointages = [];
            if ($date) {
                $queryPointages .= " WHERE c.checkin_date = ?";
                $paramsPointages[] = $date;
            }
            $queryPointages .= " ORDER BY c.checkin_date DESC, c.checkin_time DESC";
            
            $pointages = $db->select($queryPointages, $paramsPointages);

            echo json_encode([
                'success' => true,
                'message' => 'Données récupérées avec succès',
                'busDisponible' => $busDisponible,
                'taxiDisponible' => $taxiDisponible,
                'busPointer' => $busPointer,
                'taxiPointer' => $taxiPointer,
                'busAbsent' => $busAbsent,
                'taxiAbsent' => $taxiAbsent,
                'pointages' => $pointages
            ]);
            break;

        case 'tarifs':
            $tarifs = $db->select("SELECT type, ttc FROM tarifs");
            $tarifBus = 0; $tarifTaxi = 0;
            foreach ($tarifs as $tarif) {
                if ($tarif['type'] === 'Bus') $tarifBus = $tarif['ttc'];
                elseif ($tarif['type'] === 'Taxi') $tarifTaxi = $tarif['ttc'];
            }
            echo json_encode(['success' => true, 'message' => 'Tarifs récupérés avec succès', 'tarifBus' => $tarifBus, 'tarifTaxi' => $tarifTaxi]);
            break;
            
        case 'details':
            if ($type === 'All' || empty($type)) {
                $buses = $db->select("SELECT b.id, 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.actif = 1 ORDER BY b.matricule ASC");
            } else {
                $buses = $db->select("SELECT b.id, 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", [$type]);
            }
            echo json_encode(['success' => true, 'count' => count($buses), 'buses' => $buses]);
            break;

        case 'pointer':
            $queryPointer = "SELECT b.matricule, 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 = ?";
            $paramsPointer = [$type];
            if ($date) { $queryPointer .= " AND c.checkin_date = ?"; $paramsPointer[] = $date; }
            $queryPointer .= " ORDER BY c.checkin_date DESC, c.checkin_time DESC";
            $pointages = $db->select($queryPointer, $paramsPointer);
            echo json_encode(['success' => true, 'count' => count($pointages), 'pointages' => $pointages]);
            break;
            
        case 'absents':
            $allBuses = $db->select("SELECT b.id, b.matricule, 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", [$type]);
            $pointerIds = $db->select("SELECT DISTINCT bus_id FROM checkins WHERE checkin_date = ?", [$date]);
            $pointerIdsList = array_column($pointerIds, 'bus_id');
            $absents = [];
            foreach ($allBuses as $bus) {
                if (!in_array($bus['id'], $pointerIdsList)) { $absents[] = $bus; }
            }
            echo json_encode(['success' => true, 'count' => count($absents), 'buses' => $absents]);
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Action non reconnue']);
            break;
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Erreur: ' . $e->getMessage()]);
}
