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

$role = $_SESSION['user_role'];
$year = isset($_GET['year']) ? intval($_GET['year']) : date('Y');

// --- DONNÉES POUR ADMIN ---
if ($role === 'SUPER_ADMIN') {
    // 1. COMPTEUR COMMANDES "À TRAITER"
    // On compte 'EN_ATTENTE' (à valider) + 'VALIDE' (à expédier).
    // On ne compte PAS 'EXPEDIE' ni 'REFUSE' ni 'ANNULE'.
    $nb_orders_todo = $pdo->query("SELECT count(*) FROM commandes WHERE statut IN ('EN_ATTENTE', 'VALIDE')")->fetchColumn();
    
    // Pour la cloche de notification, on garde le focus sur l'URGENCE (En attente seulement)
    $nb_orders_urgent = $pdo->query("SELECT count(*) FROM commandes WHERE statut = 'EN_ATTENTE'")->fetchColumn();
    
    // 2. COMPTEUR CAMPAGNES "EN COURS"
    // On compte les campagnes qui sont 'OUVERTE' ET dont la date de fin n'est pas passée.
    $today = date('Y-m-d');
    $nb_campaigns_active = $pdo->prepare("SELECT count(*) FROM campagnes WHERE statut = 'OUVERTE' AND date_fin >= ?");
    $nb_campaigns_active->execute([$today]);
    $nb_active_camp = $nb_campaigns_active->fetchColumn();

    // Notification : Demandes de prolongation
    $nb_ext = $pdo->query("SELECT count(*) FROM campagnes WHERE date_fin_demandee IS NOT NULL AND date_fin_demandee != ''")->fetchColumn();

    // Total des notifs (Cloche)
    $total_notif = $nb_orders_urgent + $nb_ext;

    // 3. Top 10 CSE par CA
    $top_cse = $pdo->query("
        SELECT e.nom, SUM(c.total_ttc) as ca 
        FROM commandes c JOIN beneficiaires b ON c.beneficiaire_id = b.id JOIN entreprises e ON b.entreprise_id = e.id 
        WHERE c.statut != 'REFUSE' GROUP BY e.id ORDER BY ca DESC LIMIT 10
    ")->fetchAll();

    // 4. Stats Mensuelles
    $stats_N = array_fill(1, 12, 0);
    $req = $pdo->prepare("SELECT strftime('%m', date_creation) as mois, SUM(total_ttc) as ca FROM commandes WHERE strftime('%Y', date_creation) = ? AND statut != 'REFUSE' GROUP BY mois");
    $req->execute(["$year"]);
    while($row = $req->fetch()) { $stats_N[intval($row['mois'])] = $row['ca']; }

    $stats_N1 = array_fill(1, 12, 0);
    $req->execute([strval($year - 1)]);
    while($row = $req->fetch()) { $stats_N1[intval($row['mois'])] = $row['ca']; }
}

// --- DONNÉES POUR CSE ---
if ($role !== 'SUPER_ADMIN') {
    $mon_solde = $pdo->prepare("SELECT solde_cagnotte FROM entreprises WHERE id = ?");
    $mon_solde->execute([$_SESSION['entreprise_id']]);
    $ma_cagnotte = $mon_solde->fetchColumn();
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tableau de bord - 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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>

    <nav class="navbar navbar-expand-lg navbar-dark mb-4" style="background-color: <?= $role === 'SUPER_ADMIN' ? '#dc3545' : 'var(--primary-dark)' ?>;">
        <div class="container-fluid px-4">
            <a class="navbar-brand" href="#">
                <img src="assets/logo.jpg" alt="Naïta" class="rounded-circle" style="border: 2px solid white; height:40px; margin-right:10px;"> 
                <span class="fw-bold">NAÏTA <?= $role==='SUPER_ADMIN'?'ADMIN':'' ?></span>
            </a>
            
            <div class="d-flex align-items-center text-white">
                
                <?php if($role === 'SUPER_ADMIN'): ?>
                    <div class="dropdown d-inline-block me-4">
                        <a href="#" class="text-white position-relative" id="notifDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="material-icons fs-3">notifications</i>
                            <?php if($total_notif > 0): ?>
                            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-warning text-dark">
                                <?= $total_notif ?>
                            </span>
                            <?php endif; ?>
                        </a>
                        
                        <ul class="dropdown-menu dropdown-menu-end shadow" aria-labelledby="notifDropdown">
                            <li><h6 class="dropdown-header">À Traiter en priorité</h6></li>
                            
                            <?php if($nb_orders_urgent > 0): ?>
                                <li>
                                    <a class="dropdown-item d-flex align-items-center text-warning" href="admin_orders.php">
                                        <i class="material-icons me-2 fs-6">shopping_cart</i>
                                        <strong><?= $nb_orders_urgent ?></strong>&nbsp;Nouvelles commandes
                                    </a>
                                </li>
                            <?php endif; ?>

                            <?php if($nb_ext > 0): ?>
                                <li>
                                    <a class="dropdown-item d-flex align-items-center text-info" href="admin_campaigns.php">
                                        <i class="material-icons me-2 fs-6">event_available</i>
                                        <strong><?= $nb_ext ?></strong>&nbsp;Demandes prolongation
                                    </a>
                                </li>
                            <?php endif; ?>

                            <?php if($total_notif == 0): ?>
                                <li><span class="dropdown-item text-muted small">Aucune urgence.</span></li>
                            <?php endif; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <span class="me-3 d-none d-md-inline"><?= htmlspecialchars($_SESSION['user_nom']) ?></span>
                <a href="logout.php" class="btn btn-sm btn-outline-light">Déconnexion</a>
            </div>
        </div>
    </nav>

    <div class="container">

        <?php if ($role === 'SUPER_ADMIN'): ?>
            
            <div class="row mb-4">
                <div class="col-md-8">
                    <div class="card shadow-sm h-100">
                        <div class="card-header bg-white d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">Chiffre d'Affaires Mensuel</h5>
                            <form method="GET" class="d-flex">
                                <select name="year" class="form-select form-select-sm" onchange="this.form.submit()">
                                    <?php for($y=date('Y'); $y>=2024; $y--): ?>
                                        <option value="<?=$y?>" <?=$y==$year?'selected':''?>><?=$y?></option>
                                    <?php endfor; ?>
                                </select>
                            </form>
                        </div>
                        <div class="card-body">
                            <canvas id="caChart"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card shadow-sm h-100">
                        <div class="card-header bg-gold text-white">🏆 Top 10 CSE</div>
                        <ul class="list-group list-group-flush">
                            <?php foreach($top_cse as $idx => $t): ?>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    <span>#<?= $idx+1 ?> <strong><?= $t['nom'] ?></strong></span>
                                    <span class="badge bg-secondary"><?= number_format($t['ca'], 0) ?>€</span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            </div>

            <h5 class="text-danger border-bottom pb-2 mb-3">Outils de Gestion</h5>
            <div class="row g-3 pb-5">
                <div class="col-md-3">
                    <div class="dashboard-card bg-light border-danger" onclick="window.location.href='admin_orders.php'">
                        <i class="material-icons text-danger">shopping_cart</i>
                        <h5 class="text-danger">Commandes (<?= $nb_orders_todo ?>)</h5>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="dashboard-card bg-light border-danger" onclick="window.location.href='admin_users.php'">
                        <i class="material-icons text-danger">manage_accounts</i>
                        <h5 class="text-danger">Utilisateurs</h5>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="dashboard-card bg-light border-danger" onclick="window.location.href='admin_products.php'">
                        <i class="material-icons text-danger">inventory_2</i>
                        <h5 class="text-danger">Produits</h5>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="dashboard-card bg-light border-danger" onclick="window.location.href='admin_campaigns.php'">
                        <i class="material-icons text-danger">event</i>
                        <h5 class="text-danger">Campagnes (<?= $nb_active_camp ?>)</h5>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="dashboard-card bg-light border-danger" onclick="window.location.href='admin_companies.php'">
                        <i class="material-icons text-danger">business</i>
                        <h5 class="text-danger">Fiches CSE</h5>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="dashboard-card bg-light border-danger" onclick="window.location.href='admin_stats_products.php'">
                        <i class="material-icons text-danger">insights</i>
                        <h5 class="text-danger">Statistiques Ventes</h5>
                    </div>
                </div>
            </div>
            
            <script>
                const ctx = document.getElementById('caChart').getContext('2d');
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil', 'Août', 'Sep', 'Oct', 'Nov', 'Déc'],
                        datasets: [{
                            label: 'CA <?= $year ?>',
                            data: <?= json_encode(array_values($stats_N)) ?>,
                            borderColor: '#c5a059', tension: 0.3, fill: false
                        }, {
                            label: 'CA <?= $year-1 ?>',
                            data: <?= json_encode(array_values($stats_N1)) ?>,
                            borderColor: '#cccccc', borderDash: [5, 5], tension: 0.3, fill: false
                        }]
                    }
                });
            </script>
        <?php endif; ?>

        <?php if ($role !== 'SUPER_ADMIN'): ?>
            <div class="row mb-4">
                <div class="col-md-12">
                    <div class="card text-white bg-success shadow-sm" style="background: linear-gradient(45deg, #198754, #20c997);">
                        <div class="card-body d-flex justify-content-between align-items-center px-4">
                            <div>
                                <h3 class="mb-0 fw-bold"><?= number_format($ma_cagnotte, 2) ?> €</h3>
                                <small>Ma Cagnotte Validée et Disponible</small>
                            </div>
                            <i class="material-icons" style="font-size: 3rem; opacity:0.8">savings</i>
                        </div>
                    </div>
                </div>
            </div>

            <h5 class="mb-3 text-uppercase fw-bold text-dark">Mon Espace</h5>
            <div class="row g-3 mb-4">
                <div class="col-md-4"><div class="dashboard-card" onclick="window.location.href='profile.php'"><i class="material-icons">person</i><h5>Infos</h5></div></div>
                <div class="col-md-4"><div class="dashboard-card" onclick="window.location.href='history.php'"><i class="material-icons">history</i><h5>Historique</h5></div></div>
                <div class="col-md-4"><div class="dashboard-card" onclick="window.location.href='campaigns.php'"><i class="material-icons">list_alt</i><h5>Campagnes</h5></div></div>
            </div>
            <h5 class="mb-3 text-uppercase fw-bold text-dark">Actions</h5>
            <div class="row g-3">
                <div class="col-md-6"><div class="dashboard-card border-gold" onclick="window.location.href='new_order.php'"><i class="material-icons text-gold">add_shopping_cart</i><h5>Nouvelle Commande</h5></div></div>
                <div class="col-md-6"><div class="dashboard-card border-gold" onclick="window.location.href='orders_listing.php'"><i class="material-icons text-gold">assignment</i><h5>Listing & PDF</h5></div></div>
            </div>
        <?php endif; ?>

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