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

// On récupère l'ID du CSE connecté
$mon_cse_id = $_SESSION['entreprise_id'];

// REQUÊTE SIMPLIFIÉE ET ROBUSTE
// On prend toutes les commandes dont le bénéficiaire appartient à CE cse.
$sql = "
    SELECT 
        c.id, c.reference, c.date_creation, c.total_ttc, c.statut,
        b.nom, b.prenom, b.email,
        camp.nom as nom_campagne
    FROM commandes c
    JOIN beneficiaires b ON c.beneficiaire_id = b.id
    LEFT JOIN campagnes camp ON c.campagne_id = camp.id
    WHERE b.entreprise_id = ? 
    ORDER BY c.date_creation DESC
";

$stmtList = $pdo->prepare($sql);
$stmtList->execute([$mon_cse_id]);
$commandes = $stmtList->fetchAll();

// Calcul du total affiché
$total_page = 0;
foreach($commandes as $cmd) {
    if($cmd['statut'] != 'REFUSE' && $cmd['statut'] != 'ANNULE') {
        $total_page += $cmd['total_ttc'];
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Listing Commandes - Naïta</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">
    <link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
</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>Listing Global</span>
        </a>
        <a href="dashboard.php" class="btn btn-outline-light btn-sm">Retour Menu</a>
    </nav>

    <div class="container">
        
        <div class="card mb-4 shadow-sm border-gold">
            <div class="card-body d-flex justify-content-between align-items-center">
                <div>
                    <h5 class="card-title text-uppercase text-muted mb-0">Total Commandes (Validées/Attente)</h5>
                    <small>Cumul global de votre CSE</small>
                </div>
                <div class="text-end">
                    <span class="h2 fw-bold text-dark">
                        <?= number_format($total_page, 2, ',', ' ') ?> €
                    </span>
                </div>
            </div>
        </div>

        <div class="card p-3 shadow-sm">
            <table id="tableOrders" class="table table-striped table-hover" style="width:100%">
                <thead>
                    <tr>
                        <th>Référence</th>
                        <th>Campagne</th>
                        <th>Bénéficiaire (Salarié)</th>
                        <th>Date</th>
                        <th>Montant</th>
                        <th>Statut</th>
                        <th class="text-center">PDF</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($commandes as $c): ?>
                    <tr>
                        <td class="fw-bold"><?= htmlspecialchars($c['reference']) ?></td>
                        <td><?= htmlspecialchars($c['nom_campagne'] ?? 'Standard') ?></td>
                        <td><?= htmlspecialchars($c['nom'] . ' ' . $c['prenom']) ?></td>
                        <td><?= date('d/m/Y', strtotime($c['date_creation'])) ?></td>
                        <td class="fw-bold"><?= number_format($c['total_ttc'], 2) ?> €</td>
                        <td>
                             <?php 
                                $badges = ['EN_ATTENTE'=>'bg-warning text-dark', 'VALIDE'=>'bg-success', 'REFUSE'=>'bg-danger'];
                                $badge = $badges[$c['statut']] ?? 'bg-secondary';
                             ?>
                             <span class="badge <?= $badge ?>"><?= $c['statut'] ?></span>
                        </td>
                        <td class="text-center">
                            <a href="print_order.php?id=<?= $c['id'] ?>" target="_blank" class="text-danger" title="Télécharger le bon">
                                <i class="material-icons">picture_as_pdf</i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#tableOrders').DataTable({
                language: { url: '//cdn.datatables.net/plug-ins/1.13.4/i18n/fr-FR.json' },
                order: [[ 3, "desc" ]] // Tri par date décroissant par défaut
            });
        });
    </script>

</body>
</html>