<?php
/**
 * API de liste des chauffeurs
 * GET /api/chauffeurs
 */

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth.php';

// Vérifier la méthode HTTP
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'Méthode non autorisée'
    ]);
    exit;
}

// Authentification requise
$payload = requireAuth();

try {
    $db = getDB();

    // Récupérer tous les chauffeurs actifs
    $stmt = $db->prepare("
        SELECT id, matricule, nom, prenom, nomprenom, role, photo_reference
        FROM employees
        WHERE role = 'Chauffeur' AND actif = 1
        ORDER BY nom, prenom
    ");
    $stmt->execute();
    $chauffeurs = $stmt->fetchAll();

    $response = array_map(function($c) {
        return [
            'id' => (int)$c['id'],
            'matricule' => $c['matricule'],
            'nom' => $c['nom'],
            'prenom' => $c['prenom'],
            'nomprenom' => $c['nomprenom'] ?? ($c['nom'] . ' ' . $c['prenom']),
            'role' => $c['role'],
            'photo_reference' => $c['photo_reference']
        ];
    }, $chauffeurs);

    echo json_encode([
        'success' => true,
        'message' => 'Liste des chauffeurs',
        'chauffeurs' => $response
    ]);

} catch (Exception $e) {
    error_log("Erreur chauffeurs: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Erreur serveur'
    ]);
}
