<?php
/**
 * API PHP pour DTW Boumerdes - Bus Absent (buses type=Bus non pointés)
 * Endpoint: apidtw_bus_absent.php
 * 
 * Paramètres: date_du, date_au
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

// Configuration de la base de données
$host = 'localhost';
$dbname = 'transubd_PointageBus';
$username = 'transubd_transub_user';
$password = 'Tr@nsub2@24';

// Récupérer les paramètres
$date_du = isset($_GET['date_du']) ? $_GET['date_du'] : date('Y-m-d');
$date_au = isset($_GET['date_au']) ? $_GET['date_au'] : date('Y-m-d');

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    
    // Requête pour récupérer les buses absents (type=Bus et non pointés)
    $sql = "SELECT 
                b.id as bus_id,
                b.matricule,
                b.id_operateur,
                b.id_ligne,
                o.name as operator_name,
                l.name as ligne_name
            FROM buses b
            INNER JOIN operators o ON o.id = b.id_operateur
            LEFT JOIN lignes l ON l.ligne_code = b.id_ligne
            WHERE b.type = 'Bus'
            AND b.id NOT IN (
                SELECT c.bus_id 
                FROM checkins c 
                WHERE c.checkin_date BETWEEN :date_du AND :date_au
            )
            ORDER BY o.name ASC, b.matricule ASC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':date_du', $date_du);
    $stmt->bindParam(':date_au', $date_au);
    $stmt->execute();
    
    $absents = $stmt->fetchAll();
    
    echo json_encode([
        'success' => true,
        'data' => $absents,
        'date_du' => $date_du,
        'date_au' => $date_au
    ], JSON_UNESCAPED_UNICODE);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Erreur de connexion: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>
