<?php
/**
 * API d'enregistrement des pointages
 * POST /api/attendance
 * Récupère les coordonnées du site via site_id de l'employé
 * Compare la position GPS avec le site, marque "hors_site" si hors rayon
 * Ne sauvegarde PAS l'image (comparaison uniquement)
 */

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

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

$payload = requireAuth();
$userId = $payload['user_id'];

// Vérifier que l'utilisateur est Admin
$db = getDB();
$stmtAdmin = $db->prepare("SELECT role FROM employees WHERE id = :id AND actif = 1");
$stmtAdmin->execute(['id' => $userId]);
$adminCheck = $stmtAdmin->fetch();

if (!$adminCheck || $adminCheck['role'] !== 'Admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Accès réservé à l\'administrateur']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

// Vérifier les champs obligatoires
$requiredFields = ['employee_id', 'type_pointage', 'latitude', 'longitude', 'precision_gps', 'appareil'];
foreach ($requiredFields as $field) {
    if (!isset($input[$field])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => "Le champ $field est requis"]);
        exit;
    }
}

$validTypes = ['entree', 'sortie'];
if (!in_array($input['type_pointage'], $validTypes)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Type de pointage invalide']);
    exit;
}

try {
    // Récupérer l'employé avec son site
    $stmt = $db->prepare("
        SELECT e.id, e.nom, e.prenom, e.nomprenom, e.site_id,
               s.latitude as site_latitude, s.longitude as site_longitude, s.rayon_autorise, s.nom as site_nom
        FROM employees e
        LEFT JOIN sites s ON e.site_id = s.id
        WHERE e.id = :id AND e.actif = 1
    ");
    $stmt->execute(['id' => $input['employee_id']]);
    $employee = $stmt->fetch();

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

    // Vérifier si le chauffeur a déjà pointé ce type aujourd'hui
    $today = date('Y-m-d');
    $stmtCheck = $db->prepare("
        SELECT id, date_heure FROM attendances
        WHERE employee_id = :employee_id
        AND type_pointage = :type_pointage
        AND DATE(date_heure) = :today
        LIMIT 1
    ");
    $stmtCheck->execute([
        'employee_id' => $input['employee_id'],
        'type_pointage' => $input['type_pointage'],
        'today' => $today
    ]);
    $existingPointage = $stmtCheck->fetch();

    error_log("Check duplicate: employee_id={$input['employee_id']}, type={$input['type_pointage']}, today=$today, found=" . ($existingPointage ? 'YES' : 'NO'));

    if ($existingPointage) {
        $typeLabel = $input['type_pointage'] === 'entree' ? 'Entrée' : 'Sortie';
        $heure = date('H:i', strtotime($existingPointage['date_heure']));
        http_response_code(409);
        echo json_encode([
            'success' => false,
            'message' => "Le pointage $typeLabel a déjà été enregistré aujourd'hui à $heure pour ce chauffeur",
            'already_pointed' => true,
            'existing_time' => $existingPointage['date_heure']
        ]);
        exit;
    }

    // Calculer la distance avec le site
    $distance = 0;
    $inZone = true;
    $horsSite = false;

    if (!empty($employee['site_latitude']) && !empty($employee['site_longitude'])) {
        $distance = calculateDistance(
            $input['latitude'],
            $input['longitude'],
            $employee['site_latitude'],
            $employee['site_longitude']
        );
        $rayonAutorise = $employee['rayon_autorise'] ?? 100;
        $inZone = $distance <= $rayonAutorise;
        $horsSite = !$inZone;
    }

    // Insérer le pointage (sans image, avec score de reconnaissance faciale)
    $now = date('Y-m-d H:i:s');
    $scoreVisage = isset($input['score_visage']) ? (float)$input['score_visage'] : null;

    $stmt = $db->prepare("
        INSERT INTO attendances (
            employee_id, type_pointage, date_heure,
            latitude, longitude, precision_gps,
            score_visage, appareil, statut_validation,
            distance_meters
        ) VALUES (
            :employee_id, :type_pointage, :date_heure,
            :latitude, :longitude, :precision_gps,
            :score_visage, :appareil, :statut_validation,
            :distance_meters
        )
    ");

    $statutValidation = $horsSite ? 'hors_site' : 'validated';

    try {
        $stmt->execute([
            'employee_id' => $input['employee_id'],
            'type_pointage' => $input['type_pointage'],
            'date_heure' => $now,
            'latitude' => $input['latitude'],
            'longitude' => $input['longitude'],
            'precision_gps' => $input['precision_gps'],
            'score_visage' => $scoreVisage,
            'appareil' => $input['appareil'],
            'statut_validation' => $statutValidation,
            'distance_meters' => round($distance)
        ]);
    } catch (PDOException $e) {
        error_log("Erreur INSERT attendance - statut_validation='$statutValidation', PDO error: " . $e->getMessage());
        throw $e;
    }

    $attendanceId = $db->lastInsertId();

    $stmt = $db->prepare("SELECT * FROM attendances WHERE id = :id");
    $stmt->execute(['id' => $attendanceId]);
    $attendance = $stmt->fetch();

    $responseAttendance = [
        'id' => (int)$attendance['id'],
        'employee_id' => (int)$attendance['employee_id'],
        'type_pointage' => $attendance['type_pointage'],
        'date_heure' => $attendance['date_heure'],
        'latitude' => (float)$attendance['latitude'],
        'longitude' => (float)$attendance['longitude'],
        'precision_gps' => (float)$attendance['precision_gps'],
        'score_visage' => $attendance['score_visage'] ? (float)$attendance['score_visage'] : null,
        'appareil' => $attendance['appareil'],
        'statut_validation' => $attendance['statut_validation'],
        'distance_meters' => (int)$attendance['distance_meters']
    ];

    $message = $horsSite
        ? "Pointage enregistré - Hors site (distance: " . round($distance) . "m, rayon: " . ($employee['rayon_autorise'] ?? 100) . "m)"
        : "Pointage enregistré avec succès";

    echo json_encode([
        'success' => true,
        'message' => $message,
        'attendance' => $responseAttendance,
        'in_zone' => $inZone,
        'hors_site' => $horsSite,
        'distance' => round($distance),
        'site_nom' => $employee['site_nom'] ?? 'Non défini'
    ]);

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

function calculateDistance($lat1, $lon1, $lat2, $lon2) {
    $earthRadius = 6371000;
    $dLat = deg2rad($lat2 - $lat1);
    $dLon = deg2rad($lon2 - $lon1);
    $a = sin($dLat / 2) * sin($dLat / 2) +
        cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
        sin($dLon / 2) * sin($dLon / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    return $earthRadius * $c;
}
