<?php
require_once 'db_config.php';
require_once 'security.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Valider le token et appliquer rate limiting/whitelist
$auth = new ApiSecurity();
$tokenData = $auth->requireAuth(true);
header('X-RateLimit-Remaining: ' . ($auth->checkRateLimit()['remaining'] ?? 'unknown'));

// Désactiver l'affichage des erreurs en production
error_reporting(0);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/checkin_errors.log');

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

// Nettoyage et validation des entrées
function sanitizeCheckinInput($data) {
    if (!isset($data) || is_null($data)) return '';
    return trim($data);
}

// Récupération des paramètres
$id_operateur = sanitizeCheckinInput($_POST['id_operateur'] ?? '');
$type         = sanitizeCheckinInput($_POST['type'] ?? '');
$matricule    = sanitizeCheckinInput($_POST['matricule'] ?? '');
$agent_id     = sanitizeCheckinInput($_POST['agent_id'] ?? '');
$siteID       = sanitizeCheckinInput($_POST['siteID'] ?? '');

// Validation SiteID
if (!preg_match('/^[a-zA-Z0-9_-]+$/', $siteID)) {
    echo json_encode(['success' => false, 'message' => 'SiteID invalide']);
    exit;
}

// Limiter la longueur des entrées
if (strlen($matricule) > 100) $matricule = substr($matricule, 0, 100);
if (strlen($agent_id) > 50) $agent_id = substr($agent_id, 0, 50);
if (strlen($type) > 50) $type = substr($type, 0, 50);
if (strlen($id_operateur) > 50) $id_operateur = substr($id_operateur, 0, 50);

if (empty($id_operateur) || empty($type) || empty($agent_id) || empty($siteID)) {
    echo json_encode(['success' => false, 'message' => 'Paramètres requis manquants']);
    exit;
}

$conn = getConnectionPointage();
if (!$conn) {
    echo json_encode(['success' => false, 'message' => 'Erreur de connexion à la base de données']);
    exit;
}

// ====================== 1. Recherche du véhicule ======================
$sql_vehicule = "SELECT id, id_type_vehicule, matricule
                 FROM vehicules_circuits
                 WHERE id_operateur = ? AND type = ? AND status = 'Active' AND SiteID = ?
                 LIMIT 1";

$stmt = $conn->prepare($sql_vehicule);
$stmt->bind_param("iss", $id_operateur, $type, $siteID);
$stmt->execute();
$stmt->bind_result($vehicule_row_id, $vehicule_id, $vehicule_matricule);

if (!$stmt->fetch()) {
    echo json_encode(['success' => false, 'message' => 'Véhicule non trouvé pour cet opérateur/type/site']);
    $stmt->close();
    $conn->close();
    exit;
}
$stmt->close();

$month_start = date('Y-m-01');
$next_month_start = date('Y-m-01', strtotime('+1 month'));

// ====================== 2. Vérification doublon Operateur + Type ======================
$sql_doublon_ot = "SELECT COUNT(*) as nb
                   FROM checkins_circuits c
                   INNER JOIN vehicules_circuits v ON v.id_type_vehicule = c.vehicule_id
                   WHERE v.id_operateur = ?
                     AND v.type = ?
                     AND v.SiteID = ?
                     AND c.checkin_date >= ?
                     AND c.checkin_date < ?";

$stmt_doublon = $conn->prepare($sql_doublon_ot);
$stmt_doublon->bind_param("sssss", $id_operateur, $type, $siteID, $month_start, $next_month_start);
$stmt_doublon->execute();
$stmt_doublon->bind_result($nb_doublon_ot);
$stmt_doublon->fetch();
$stmt_doublon->close();

if ($nb_doublon_ot > 0) {
    echo json_encode([
        'success' => false,
        'message' => 'Doublon',
        'error_type' => 'DOUBLON_VEHICULE',
        'error_detail' => 'Un véhicule avec cet opérateur et ce type a déjà été pointé ce mois-ci'
    ]);
    $conn->close();
    exit;
}

// ====================== 3. Vérification doublon Matricule (si non vide) ======================
if (!empty($matricule)) {
    $sql_doublon_mat = "SELECT COUNT(*) as nb
                        FROM checkins_circuits c
                        INNER JOIN vehicules_circuits v ON v.id_type_vehicule = c.vehicule_id
                        WHERE v.SiteID = ?
                          AND TRIM(c.notes) = ?
                          AND IFNULL(c.notes, '') != ''
                          AND c.checkin_date >= ?
                          AND c.checkin_date < ?";

    $stmt_mat = $conn->prepare($sql_doublon_mat);
    $stmt_mat->bind_param("ssss", $siteID, $matricule, $month_start, $next_month_start);
    $stmt_mat->execute();
    $stmt_mat->bind_result($nb_doublon_mat);
    $stmt_mat->fetch();
    $stmt_mat->close();

    if ($nb_doublon_mat > 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Doublon',
            'error_type' => 'DOUBLON_MATRICULE',
            'error_detail' => 'Ce matricule a déjà été checké ce mois-ci'
        ]);
        $conn->close();
        exit;
    }
}

// ====================== 4. Insertion ======================
$checkin_date = date('Y-m-d');
$checkin_time = date('H:i:s');
$checkin_datetime = date('Y-m-d H:i:s');

$sql_insert = "INSERT INTO checkins_circuits
               (vehicule_id, operateur_id, agent_id, checkin_date, checkin_time, checkin_datetime,
                notes, is_valid, created_at)
               VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?)";

$stmt_insert = $conn->prepare($sql_insert);
$stmt_insert->bind_param("iiisssss",
    $vehicule_id,
    $id_operateur,
    $agent_id,
    $checkin_date,
    $checkin_time,
    $checkin_datetime,
    $matricule,
    $checkin_datetime
);

if ($stmt_insert->execute()) {
    $id_checkin = $stmt_insert->insert_id;

    echo json_encode([
        'success' => true,
        'message' => 'Pointage enregistre avec succes',
        'data' => [
            'id_checkin' => $id_checkin,
            'vehicule_id' => $vehicule_id,
            'operateur_id' => $id_operateur,
            'agent_id' => $agent_id,
            'checkin_date' => $checkin_date,
            'checkin_time' => $checkin_time,
            'matricule' => $matricule
        ]
    ]);
} else {
    error_log("CHECKIN INSERT ERROR: " . $stmt_insert->error);
    echo json_encode(['success' => false, 'message' => 'Erreur lors de l\'enregistrement']);
}

$stmt_insert->close();
$conn->close();
?>