<?php
/**
 * API PHP pour DTW Boumerdes - Pointage Taxi avec période
 * Endpoint: apidtw_pointage_taxi.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 pointages avec jointures - Type Taxi uniquement
    $sql = "SELECT 
                c.id as checkin_id,
                c.checkin_datetime,
                c.bus_id,
                b.matricule,
                b.id_operateur,
                o.name as operator_name
            FROM checkins c
            INNER JOIN buses b ON b.id = c.bus_id
            INNER JOIN operators o ON o.id = b.id_operateur
            WHERE b.type = 'Taxi'
            AND c.checkin_date BETWEEN :date_du AND :date_au
            ORDER BY c.checkin_datetime DESC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':date_du', $date_du);
    $stmt->bindParam(':date_au', $date_au);
    $stmt->execute();
    
    $pointages = $stmt->fetchAll();
    
    echo json_encode([
        'success' => true,
        'data' => $pointages,
        '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);
}
?>
