<?php
// Fichier: history.php
require 'includes/db.php';
require 'includes/auth.php';
require_login();

$mon_cse_id = $_SESSION['entreprise_id'];

// --- 1. REQUÊTE SQL AVEC CAMPAGNE ---
$sql = "
    SELECT 
        c.id, c.reference, c.date_creation, c.total_ttc, c.statut, c.montant_cagnotte_utilise,
        b.nom as b_nom, b.prenom as b_prenom,
        camp.nom as nom_campagne,
        GROUP_CONCAT(lc.quantite || 'x ' || lc.nom_produit_historique, ', ') as detail_produits
    FROM commandes c
    JOIN beneficiaires b ON c.beneficiaire_id = b.id
    LEFT JOIN lignes_commande lc ON c.id = lc.commande_id
    LEFT JOIN campagnes camp ON c.campagne_id = camp.id
    WHERE b.entreprise_id = ? 
    GROUP BY c.id
    ORDER BY camp.id DESC, c.date_creation DESC
";

$stmt = $pdo->prepare($sql);
$stmt->execute([$mon_cse_id]);
$mes_commandes = $stmt->fetchAll();

// --- 2. REGROUPEMENT PHP ---
$grouped = [];
foreach ($mes_commandes as $c) {
    $campName = $c['nom_campagne'] ? $c['nom_campagne'] : 'Commandes Hors Campagne';
    
    if (!isset($grouped[$campName])) {
        $grouped[$campName] = ['total' => 0, 'count' => 0, 'orders' => []];
    }
    
    $grouped[$campName]['orders'][] = $c;
    if($c['statut'] != 'ANNULE' && $c['statut'] != 'REFUSE') {
        $grouped[$campName]['total'] += $c['total_ttc'];
    }
    $grouped[$campName]['count']++;
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Historique Commandes</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>

    <nav class="navbar navbar-dark bg-dark mb-4 px-4">
        <a class="navbar-brand" href="dashboard.php">
            <img src="assets/logo.jpg" alt="Naïta" class="rounded-circle" style="border: 2px solid white; height:40px; margin-right:10px;"> 
            <span>Mes Commandes</span>
        </a>
        <a href="dashboard.php" class="btn btn-outline-light btn-sm">Retour</a>
    </nav>

    <div class="container">
        
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h4 class="text-uppercase" style="color:var(--primary-dark)">Historique par Campagne</h4>
            <button onclick="window.print()" class="btn btn-gold btn-sm d-print-none">
                <i class="material-icons align-middle" style="font-size:16px">print</i> Imprimer page
            </button>
        </div>

        <div class="accordion" id="historyAccordion">
            <?php if(empty($grouped)): ?>
                <div class="alert alert-light text-center">Aucune commande.</div>
            <?php endif; ?>

            <?php $i=0; foreach($grouped as $campName => $data): $i++; ?>
                <div class="accordion-item mb-3 shadow-sm border-gold">
                    <h2 class="accordion-header" id="heading<?= $i ?>">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse<?= $i ?>">
                            <div class="d-flex justify-content-between w-100 align-items-center pe-3">
                                <div>
                                    <strong class="text-dark fs-5"><?= htmlspecialchars($campName) ?></strong>
                                    <span class="badge bg-secondary ms-2"><?= $data['count'] ?> commandes</span>
                                </div>
                                <span class="fw-bold text-success"><?= number_format($data['total'], 2) ?> €</span>
                            </div>
                        </button>
                    </h2>
                    <div id="collapse<?= $i ?>" class="accordion-collapse collapse" data-bs-parent="#historyAccordion">
                        <div class="accordion-body p-0">
                            <div class="table-responsive">
                                <table class="table table-striped table-hover mb-0 align-middle">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Date</th>
                                            <th>Réf</th>
                                            <th>Salarié</th>
                                            <th>Produits</th>
                                            <th>Total</th>
                                            <th>Statut</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach($data['orders'] as $c): ?>
                                        <tr>
                                            <td><?= date('d/m/Y', strtotime($c['date_creation'])) ?></td>
                                            <td class="fw-bold small"><?= $c['reference'] ?></td>
                                            <td><?= htmlspecialchars($c['b_nom'].' '.$c['b_prenom']) ?></td>
                                            <td class="small text-muted"><?= htmlspecialchars($c['detail_produits']) ?></td>
                                            <td class="fw-bold text-end">
                                                <?= number_format($c['total_ttc'], 2) ?> €
                                                <?php if($c['montant_cagnotte_utilise'] > 0): ?>
                                                    <br><small class="text-success" style="font-size:0.7em">Cagnotte: -<?= $c['montant_cagnotte_utilise'] ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php $badges = ['EN_ATTENTE'=>'bg-warning text-dark', 'VALIDE'=>'bg-success', 'ANNULE'=>'bg-danger']; ?>
                                                <span class="badge <?= $badges[$c['statut']] ?? 'bg-secondary' ?>"><?= $c['statut'] ?></span>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>