<?php
header('Content-Type: text/plain; charset=utf-8');
header("HTTP/1.0 200 OK");

require_once 'config/database.php';

$site_id = isset($_REQUEST['site_id']) ? trim($_REQUEST['site_id']) : '';
$type_rapport = isset($_REQUEST['type_rapport']) ? trim($_REQUEST['type_rapport']) : ''; // 'DATE' ou 'PERIODE'
$date_start = isset($_REQUEST['date_start']) ? trim($_REQUEST['date_start']) : ''; // Format: YYYY-MM-DD
$date_end = isset($_REQUEST['date_end']) ? trim($_REQUEST['date_end']) : ''; // Format: YYYY-MM-DD
$guichetier = isset($_REQUEST['guichetier']) ? trim($_REQUEST['guichetier']) : '';

if (empty($site_id) || empty($type_rapport) || empty($date_start)) {
    echo "ERR|Paramètres manquants";
    exit;
}

if ($type_rapport === 'PERIODE' && empty($date_end)) {
    echo "ERR|Date de fin manquante pour la période";
    exit;
}

try {
    $params = [$site_id, $date_start];
    
    $guichetier_cond = "";
    if (!empty($guichetier) && $guichetier !== 'ALL') {
        $guichetier_cond = " AND code_utilisateur = ?";
    }

    if ($type_rapport === 'DATE') {
        if (!empty($guichetier_cond)) $params[] = $guichetier;
        $query = "SELECT prix, designation, designationAR, COUNT(*) as nb_tickets, SUM(prix) as total_prix 
                  FROM Tickets_Parking 
                  WHERE SiteID = ? AND DATE(date_heure) = ?" . $guichetier_cond . " 
                  GROUP BY prix, designation, designationAR 
                  ORDER BY prix ASC";
    } else { // PERIODE
        $params[] = $date_end;
        if (!empty($guichetier_cond)) $params[] = $guichetier;
        $query = "SELECT prix, designation, designationAR, COUNT(*) as nb_tickets, SUM(prix) as total_prix 
                  FROM Tickets_Parking 
                  WHERE SiteID = ? AND DATE(date_heure) >= ? AND DATE(date_heure) <= ?" . $guichetier_cond . " 
                  GROUP BY prix, designation, designationAR 
                  ORDER BY prix ASC";
    }

    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (count($results) === 0) {
        echo "EMPTY|Aucun ticket trouvé pour cette " . ($type_rapport === 'DATE' ? 'date' : 'période');
        exit;
    }

    $total_tickets = 0;
    $total_montant = 0;
    $breakdown = [];

    foreach ($results as $row) {
        $total_tickets += $row['nb_tickets'];
        $total_montant += $row['total_prix'];
        
        $prixFormat = (float)$row['prix'];
        // On supprime les .00 inutiles pour l'affichage
        $prixFormat = (floor($prixFormat) == $prixFormat) ? number_format($prixFormat, 0, '.', '') : number_format($prixFormat, 2, '.', '');
        
        // Prix|Designation|Designation_AR|NombreDeTickets|TotalPrixPourCePrix
        $breakdown[] = $prixFormat . "|" . $row['designation'] . "|" . $row['designationAR'] . "|" . $row['nb_tickets'] . "|" . $row['total_prix'];
    }

    // Format de réponse: OK|TotalTickets|TotalMontant\nDetail1\nDetail2\n...
    echo "OK|" . $total_tickets . "|" . $total_montant . "\n" . implode("\n", $breakdown);

} catch (Exception $e) {
    echo "ERR|Erreur BDD: " . $e->getMessage();
}
?>
