<?php
header('Content-Type: text/plain; charset=utf-8');
require_once 'config/database.php';

$type = isset($_REQUEST['type']) ? $_REQUEST['type'] : ''; // RETRAIT ou DEPOT
$role = isset($_REQUEST['role']) ? $_REQUEST['role'] : '';
$user = isset($_REQUEST['user']) ? $_REQUEST['user'] : '';

try {
    if ($type === 'RETRAIT') {
        // Liste de tous les soumissionnaires avec Montant et total Generale
        $stmt = $pdo->query("SELECT NomPrenom, Montant, Date_Retrait, UserRet FROM cahier_des_charges ORDER BY Date_Retrait DESC");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $total = 0;
        foreach ($rows as $row) {
            echo $row['NomPrenom'] . ";" . $row['Montant'] . ";" . $row['Date_Retrait'] . ";" . $row['UserRet'] . "|";
            $total += floatval($row['Montant']);
        }
        echo "TOTAL;" . $total;

    } elseif ($type === 'DEPOT') {
        // DEPOTS
        $sql = "SELECT NomPrenom, DATE_FORMAT(Date_Depot, '%H:%i') as Heure_Depot, UserDep FROM cahier_des_charges WHERE Date_Depot IS NOT NULL";
        
        if ($role === 'Agent') {
            $sql .= " AND UserDep = ?";
            $stmt = $pdo->prepare($sql . " ORDER BY Date_Depot DESC");
            $stmt->execute([$user]);
        } else {
            // Admin sees all
            $stmt = $pdo->query($sql . " ORDER BY Date_Depot DESC");
        }
        
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $count = 0;
        foreach ($rows as $row) {
            // Format: Nom;Heure;User|
            echo $row['NomPrenom'] . ";" . $row['Heure_Depot'] . ";" . $row['UserDep'] . "|";
            $count++;
        }
        // Add Total count at the end
        echo "TOTAL_DEPOTS;" . $count;

    } else {
        die("ERR|Type de rapport inconnu");
    }

} catch (PDOException $e) {
    die("ERR|Erreur SQL: " . $e->getMessage());
}
?>