<?php
/**
 * API pour les pointages Boumerdes
 * FactDGR - Système de facturation
 */

if (!defined('BASE_URL')) {
    define('BASE_URL', 'http://localhost/FactDGR');
}

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

// Vérifier l'authentification
if (!auth()->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Vous n\'êtes pas connecté']);
    exit();
}

// Vérifier les permissions
if (!auth()->hasPermission('pointages_boumerdes.access')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Vous n\'avez pas la permission d\'accéder à cette API']);
    exit();
}

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

// Gérer les différentes actions
if ($action == 'details') {
    // Récupérer les détails des buses/taxis disponibles
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM buses WHERE type = ? AND actif = 1");
    $stmt->execute([$type]);
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    echo json_encode(['success' => true, 'count' => $count]);
} elseif ($action == 'pointer') {
    // Récupérer les détails des pointer
    $stmt = $pdo->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.ligne_code
        WHERE c.checkin_date = ? AND b.type = ?
        ORDER BY c.checkin_time ASC
    ");
    $stmt->execute([$date, $type]);
    $pointages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['success' => true, 'count' => count($pointages), 'pointages' => $pointages]);
} elseif ($action == 'absent') {
    // Récupérer le nombre de buses/taxis disponibles
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM buses WHERE type = ? AND actif = 1");
    $stmt->execute([$type]);
    $disponible = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    // Récupérer le nombre de buses/taxis pointer
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count 
        FROM checkins 
        JOIN buses ON checkins.bus_id = buses.id 
        WHERE checkins.checkin_date = ? AND buses.type = ?
    ");
    $stmt->execute([$date, $type]);
    $pointer = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    $absent = $disponible - $pointer;
    echo json_encode(['success' => true, 'count' => $absent]);
} else {
    // Action par défaut : récupérer les données pour la page principale
    // Récupérer les buses disponibles
    $stmt = $pdo->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 = $pdo->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 = $pdo->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 = $pdo->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 = $pdo->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.ligne_code
        WHERE c.checkin_date = ?
        ORDER BY c.checkin_time ASC
    ");
    $stmt->execute([$date]);
    $pointages = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Réponse JSON
    echo json_encode([
        'success' => true,
        'busDisponible' => $busDisponible,
        'taxiDisponible' => $taxiDisponible,
        'busPointer' => $busPointer,
        'taxiPointer' => $taxiPointer,
        'busAbsent' => $busAbsent,
        'taxiAbsent' => $taxiAbsent,
        'pointages' => $pointages
    ]);
}
?>