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

if ($_SESSION['user_role'] !== 'SUPER_ADMIN') die("Accès interdit.");

$msg = "";

// --- 1. TRAITEMENT DU CHANGEMENT DE STATUT (Code inchangé) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_status') {
    $cmd_id = $_POST['cmd_id'];
    $new_status = $_POST['new_status'];
    
    $stmt = $pdo->prepare("SELECT c.*, e.pourcentage_cagnotte, e.id as cse_id FROM commandes c JOIN beneficiaires b ON c.beneficiaire_id = b.id JOIN entreprises e ON b.entreprise_id = e.id WHERE c.id = ?");
    $stmt->execute([$cmd_id]);
    $cmd = $stmt->fetch();

    if ($cmd) {
        $old_status = $cmd['statut'];
        $pdo->prepare("UPDATE commandes SET statut = ? WHERE id = ?")->execute([$new_status, $cmd_id]);
        
        if ($new_status == 'VALIDE' && $old_status != 'VALIDE') {
            $gain = $cmd['total_ttc'] * ($cmd['pourcentage_cagnotte'] / 100);
            $pdo->prepare("UPDATE entreprises SET solde_cagnotte = solde_cagnotte + ? WHERE id = ?")->execute([$gain, $cmd['cse_id']]);
            $msg = "<div class='alert alert-success'>✅ Commande validée ! Cagnotte créditée de ".number_format($gain, 2)."€.</div>";
        }
        elseif ($new_status == 'REFUSE' && $cmd['montant_cagnotte_utilise'] > 0) {
            $pdo->prepare("UPDATE entreprises SET solde_cagnotte = solde_cagnotte + ? WHERE id = ?")->execute([$cmd['montant_cagnotte_utilise'], $cmd['cse_id']]);
            $msg = "<div class='alert alert-warning'>Commande refusée. Cagnotte remboursée.</div>";
        } else {
            $msg = "<div class='alert alert-info'>Statut mis à jour : $new_status</div>";
        }
    }
}

// --- 2. GESTION DES FILTRES ---
$cse_filter = isset($_GET['cse']) ? $_GET['cse'] : '';
$campagne_search = isset($_GET['campagne']) ? trim($_GET['campagne']) : ''; // Nouveau filtre
$date_debut = isset($_GET['date_debut']) ? $_GET['date_debut'] : '';
$date_fin   = isset($_GET['date_fin']) ? $_GET['date_fin'] : '';

// --- 3. REQUÊTE SQL (On récupère aussi le nom de la campagne) ---
$sql = "
    SELECT c.*, b.nom as b_nom, b.prenom as b_prenom, e.nom as cse_nom, 
    camp.nom as nom_campagne, camp.id as id_campagne,
    GROUP_CONCAT(lc.quantite || 'x ' || lc.nom_produit_historique, ', ') as details
    FROM commandes c
    JOIN beneficiaires b ON c.beneficiaire_id = b.id
    JOIN entreprises e ON b.entreprise_id = e.id
    LEFT JOIN lignes_commande lc ON c.id = lc.commande_id
    LEFT JOIN campagnes camp ON c.campagne_id = camp.id
    WHERE 1=1 
";

$params = [];
if (!empty($cse_filter)) { $sql .= " AND e.id = ?"; $params[] = $cse_filter; }
if (!empty($campagne_search)) { $sql .= " AND camp.nom LIKE ?"; $params[] = "%$campagne_search%"; } // Filtre Campagne
if (!empty($date_debut)) { $sql .= " AND c.date_creation >= ?"; $params[] = $date_debut . ' 00:00:00'; }
if (!empty($date_fin)) { $sql .= " AND c.date_creation <= ?"; $params[] = $date_fin . ' 23:59:59'; }

$sql .= " GROUP BY c.id ORDER BY camp.id DESC, c.date_creation DESC"; // On trie d'abord par Campagne

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$raw_commandes = $stmt->fetchAll();

// --- 4. REGROUPEMENT PHP PAR CAMPAGNE ---
// On transforme la liste plate en tableau structuré : [NomCampagne => [Commandes...]]
$grouped_orders = [];
$total_global_page = 0;

foreach ($raw_commandes as $cmd) {
    // Si pas de campagne liée, on met "Hors Campagne"
    $campKey = $cmd['nom_campagne'] ? $cmd['nom_campagne'] . " (" . $cmd['cse_nom'] . ")" : "Commandes Isolées / Hors Campagne (" . $cmd['cse_nom'] . ")";
    $campId = $cmd['id_campagne'] ?? 0;
    
    if (!isset($grouped_orders[$campKey])) {
        $grouped_orders[$campKey] = [
            'id_camp' => $campId,
            'total_camp' => 0,
            'count' => 0,
            'orders' => []
        ];
    }
    
    $grouped_orders[$campKey]['orders'][] = $cmd;
    
    if($cmd['statut'] != 'REFUSE' && $cmd['statut'] != 'ANNULE') {
        $grouped_orders[$campKey]['total_camp'] += $cmd['total_ttc'];
        $total_global_page += $cmd['total_ttc'];
    }
    $grouped_orders[$campKey]['count']++;
}

$liste_cse = $pdo->query("SELECT * FROM entreprises ORDER BY nom")->fetchAll();
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Supervision 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-danger 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>Supervision par Campagne</span>
        </a>
        <a href="dashboard.php" class="btn btn-outline-light btn-sm">Retour</a>
    </nav>

    <div class="container-fluid px-4">
        <?= $msg ?>
        
        <div class="card mb-4 shadow-sm border-gold">
            <div class="card-body py-3">
                <form class="row g-3 align-items-end" method="GET">
                    <div class="col-md-3">
                        <label class="small fw-bold text-muted">Filtrer par CSE</label>
                        <select name="cse" class="form-select">
                            <option value="">-- Tous --</option>
                            <?php foreach($liste_cse as $cse): ?>
                                <option value="<?= $cse['id'] ?>" <?= $cse_filter == $cse['id'] ? 'selected':'' ?>><?= $cse['nom'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="small fw-bold text-muted">Recherche Campagne</label>
                        <input type="text" name="campagne" class="form-control" placeholder="Ex: Noël..." value="<?= htmlspecialchars($campagne_search) ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="small fw-bold text-muted">Date début</label>
                        <input type="date" name="date_debut" class="form-control" value="<?= htmlspecialchars($date_debut) ?>">
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-dark w-100"><i class="material-icons align-middle">filter_alt</i> Filtrer</button>
                    </div>
                    <div class="col-md-2 text-end">
                        <small class="text-muted d-block">Total Affiché</small>
                        <span class="fs-5 fw-bold text-success"><?= number_format($total_global_page, 2) ?> €</span>
                    </div>
                </form>
            </div>
        </div>

        <div class="accordion" id="accordionOrders">
            <?php if(empty($grouped_orders)): ?>
                <div class="alert alert-light text-center">Aucune commande trouvée.</div>
            <?php endif; ?>

            <?php $i = 0; foreach ($grouped_orders as $campName => $data): $i++; ?>
                <div class="accordion-item mb-3 shadow-sm border-0">
                    <h2 class="accordion-header" id="heading<?= $i ?>">
                        <button class="accordion-button collapsed bg-light" 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-danger text-uppercase"><?= htmlspecialchars($campName) ?></strong>
                                    <span class="badge bg-secondary ms-2"><?= $data['count'] ?> commandes</span>
                                </div>
                                <div class="text-end">
                                    <span class="fw-bold text-dark fs-5"><?= number_format($data['total_camp'], 2) ?> €</span>
                                </div>
                            </div>
                        </button>
                    </h2>
                    <div id="collapse<?= $i ?>" class="accordion-collapse collapse" data-bs-parent="#accordionOrders">
                        <div class="accordion-body p-0">
                            <div class="table-responsive">
                                <table class="table table-hover mb-0 align-middle table-sm">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Date</th>
                                            <th>Salarié</th>
                                            <th>Détail Commande</th>
                                            <th>Total</th>
                                            <th>Statut</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($data['orders'] as $c): ?>
                                        <tr class="<?= $c['statut'] == 'EN_ATTENTE' ? 'table-warning' : '' ?>">
                                            <td><?= date('d/m H:i', strtotime($c['date_creation'])) ?></td>
                                            <td class="fw-bold"><?= htmlspecialchars($c['b_nom'].' '.$c['b_prenom']) ?></td>
                                            <td class="small text-muted"><?= htmlspecialchars($c['details']) ?></td>
                                            <td class="fw-bold"><?= number_format($c['total_ttc'], 2) ?> €</td>
                                            <td>
                                                <?php $badges = ['EN_ATTENTE'=>'bg-warning text-dark', 'VALIDE'=>'bg-success', 'EXPEDIE'=>'bg-info text-dark', 'REFUSE'=>'bg-danger']; ?>
                                                <span class="badge <?= $badges[$c['statut']] ?? 'bg-secondary' ?>"><?= $c['statut'] ?></span>
                                            </td>
                                            <td>
                                                <form method="POST" class="d-flex">
                                                    <input type="hidden" name="action" value="update_status">
                                                    <input type="hidden" name="cmd_id" value="<?= $c['id'] ?>">
                                                    <select name="new_status" class="form-select form-select-sm me-1" style="width:auto;">
                                                        <option value="EN_ATTENTE" <?= $c['statut']=='EN_ATTENTE'?'selected':'' ?>>Attente</option>
                                                        <option value="VALIDE" <?= $c['statut']=='VALIDE'?'selected':'' ?>>VALIDER</option>
                                                        <option value="EXPEDIE" <?= $c['statut']=='EXPEDIE'?'selected':'' ?>>EXPÉDIER</option>
                                                        <option value="REFUSE" <?= $c['statut']=='REFUSE'?'selected':'' ?>>REFUSER</option>
                                                    </select>
                                                    <button type="submit" class="btn btn-sm btn-dark">OK</button>
                                                </form>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <div class="p-2 text-end bg-light">
                                 <?php if($data['id_camp'] > 0): ?>
                                     <a href="admin_master_order.php?id=<?= $data['id_camp'] ?>" target="_blank" class="btn btn-sm btn-outline-gold">
                                         <i class="material-icons align-middle" style="font-size:14px">inventory</i> Voir Master Commande
                                     </a>
                                 <?php endif; ?>
                             </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>