<?php
ob_start();
header('Content-Type: text/plain; charset=utf-8');
header("HTTP/1.0 200 OK");
register_shutdown_function(function() {
    $size = ob_get_length();
    header('Content-Length: ' . $size);
    ob_end_flush();
});

require_once 'config/database.php';

// Params: code, site_id, date_vente (DD/MM/YYYY), prix, nbr, start_num, desig_fr, desig_ar, imei (session_id)
$code = isset($_POST['code']) ? trim($_POST['code']) : '';
$site_id = isset($_POST['site_id']) ? trim($_POST['site_id']) : '';
$date_vente = isset($_POST['date_vente']) ? trim($_POST['date_vente']) : '';
$prix = isset($_POST['prix']) ? trim($_POST['prix']) : '';
$nbr = isset($_POST['nbr']) ? (int)$_POST['nbr'] : 0;
$start_num = isset($_POST['start_num']) ? (double)$_POST['start_num'] : 0;
$desig_fr = isset($_POST['desig_fr']) ? trim($_POST['desig_fr']) : '';
$desig_ar = isset($_POST['desig_ar']) ? trim($_POST['desig_ar']) : '';

if (empty($code) || empty($site_id) || empty($date_vente) || $nbr <= 0 || $start_num <= 0) {
    echo "ERR|Paramètres manquants ou invalides";
    exit;
}

try {
    $pdo->beginTransaction();

    // Date conversion
    $date_mysql = date('Y-m-d H:i:s');
    if (preg_match('/(\d{2})\/(\d{2})\/(\d{4})/', $date_vente, $m)) {
        $date_mysql = $m[3] . "-" . $m[2] . "-" . $m[1] . " " . date('H:i:s');
    } elseif (preg_match('/(\d{4})-(\d{2})-(\d{2})/', $date_vente, $m)) {
        $date_mysql = $m[1] . "-" . $m[2] . "-" . $m[3] . " " . date('H:i:s');
    }

    $stmt = $pdo->prepare("INSERT INTO Tickets_Parking (numero_ticket, date_heure, prix, designation, code_utilisateur, designationAR, SiteID) 
                          VALUES (?, ?, ?, ?, ?, ?, ?)");

    for ($i = 0; $i < $nbr; $i++) {
        $current_num = $start_num + $i;
        $stmt->execute([
            str_pad($current_num, 10, "0", STR_PAD_LEFT),
            $date_mysql, 
            $prix, 
            $desig_fr, 
            $code, 
            $desig_ar, 
            $site_id
        ]);
    }

    // Mise à jour last_ticket_number dans Utilisateurs
    $stmtUpdate = $pdo->prepare("UPDATE Utilisateurs SET last_ticket_number = ? WHERE code_utilisateur = ?");
    $stmtUpdate->execute([str_pad($start_num + $nbr - 1, 10, "0", STR_PAD_LEFT), $code]);

    // Log
    $stmtLog = $pdo->prepare("INSERT INTO SystemLogs (date_heure, type, code_utilisateur, SiteID, description, statut) 
                             VALUES (NOW(), 'MANUAL', ?, ?, ?, 'SUCCES')");
    $stmtLog->execute([$code, $site_id, "Vente Manuelle Admin: $nbr tickets de $prix DA"]);

    $pdo->commit();
    echo "OK|Vente manuelle enregistrée avec succès";

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo "ERR|" . $e->getMessage();
}
?>
