<?php
/**
 * API de récupération des photos de référence d'un chauffeur
 * GET /api/employee-photos?employee_id=X
 * Retourne la liste de toutes les photos disponibles (EMP001.jpg, EMP001-1.jpg, EMP001-2.jpg, etc.)
 */

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

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

$payload = requireAuth();

$employeeId = isset($_GET['employee_id']) ? (int)$_GET['employee_id'] : 0;

if ($employeeId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'employee_id requis']);
    exit;
}

try {
    $db = getDB();

    // Récupérer l'employé
    $stmt = $db->prepare("
        SELECT id, matricule, nom, prenom, nomprenom, photo_reference
        FROM employees
        WHERE id = :id AND actif = 1
    ");
    $stmt->execute(['id' => $employeeId]);
    $employee = $stmt->fetch();

    if (!$employee) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Employé non trouvé']);
        exit;
    }

    $matricule = $employee['matricule'];
    $uploadDir = __DIR__ . '/../uploads/';
    $photos = [];

    // Chercher toutes les photos du chauffeur dans uploads/
    // Formats acceptés : jpg, jpeg, png
    $extensions = ['jpg', 'jpeg', 'png'];

    // Photo principale : EMP001.jpg
    foreach ($extensions as $ext) {
        $mainPhoto = $matricule . '.' . $ext;
        if (file_exists($uploadDir . $mainPhoto)) {
            $photos[] = [
                'url' => 'uploads/' . $mainPhoto,
                'name' => $mainPhoto,
                'is_primary' => true
            ];
            break;
        }
    }

    // Photos supplémentaires : EMP001-1.jpg, EMP001-2.jpg, EMP001-3.jpg, etc.
    for ($i = 1; $i <= 50; $i++) {
        foreach ($extensions as $ext) {
            $photoName = $matricule . '-' . $i . '.' . $ext;
            if (file_exists($uploadDir . $photoName)) {
                $photos[] = [
                    'url' => 'uploads/' . $photoName,
                    'name' => $photoName,
                    'is_primary' => false
                ];
            }
        }
    }

    // Aussi vérifier le champ photo_reference s'il existe
    if (!empty($employee['photo_reference'])) {
        $refPath = $employee['photo_reference'];
        $exists = false;
        foreach ($photos as $p) {
            if ($p['url'] === $refPath) {
                $exists = true;
                break;
            }
        }
        if (!$exists && file_exists($uploadDir . basename($refPath))) {
            array_unshift($photos, [
                'url' => $refPath,
                'name' => basename($refPath),
                'is_primary' => true
            ]);
        }
    }

    echo json_encode([
        'success' => true,
        'message' => count($photos) . ' photo(s) trouvée(s)',
        'matricule' => $matricule,
        'photos' => $photos,
        'total' => count($photos)
    ]);

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