<?php
// Fichier: admin_campaigns.php
require 'includes/db.php';
require 'includes/auth.php';
require_login();
if ($_SESSION['user_role'] !== 'SUPER_ADMIN') die("Accès interdit.");

$msg = "";

// --- 1. TRAITEMENTS ACTIONS (POST) ---

// Ouvrir une campagne
if (isset($_POST['action']) && $_POST['action'] == 'add_campaign') {
    $sql = "INSERT INTO campagnes (entreprise_id, nom, date_debut, date_fin, statut) VALUES (?, ?, ?, ?, 'OUVERTE')";
    $pdo->prepare($sql)->execute([$_POST['entreprise_id'], $_POST['nom'], $_POST['date_debut'], $_POST['date_fin']]);
    $msg = "<div class='alert alert-success'>✅ Campagne ouverte avec succès !</div>";
}

// Valider une prolongation
if (isset($_POST['action']) && $_POST['action'] == 'accept_extension') {
    $camp_id = $_POST['campagne_id'];
    $new_date = $_POST['new_date'];
    $pdo->prepare("UPDATE campagnes SET date_fin = ?, date_fin_demandee = NULL WHERE id = ?")->execute([$new_date, $camp_id]);
    $msg = "<div class='alert alert-success'>✅ Campagne prolongée jusqu'au ".date('d/m/Y', strtotime($new_date))." !</div>";
}

// Modifier date manuellement
if (isset($_POST['action']) && $_POST['action'] == 'manual_update') {
    $pdo->prepare("UPDATE campagnes SET date_fin = ? WHERE id = ?")->execute([$_POST['date_fin'], $_POST['campagne_id']]);
    $msg = "<div class='alert alert-success'>✅ Date de fin mise à jour.</div>";
}

// --- 2. GESTION DES FILTRES (GET) ---
$cse_filter = isset($_GET['cse']) ? $_GET['cse'] : '';
$date_debut = isset($_GET['date_debut']) ? $_GET['date_debut'] : '';
$date_fin   = isset($_GET['date_fin']) ? $_GET['date_fin'] : '';

// Construction de la requête
$sql = "SELECT c.*, e.nom as nom_cse 
        FROM campagnes c 
        JOIN entreprises e ON c.entreprise_id = e.id 
        WHERE 1=1 ";

$params = [];

// Filtre CSE
if (!empty($cse_filter)) {
    $sql .= " AND e.id = ?";
    $params[] = $cse_filter;
}
// Filtre Période (Basé sur la date de début de la campagne)
if (!empty($date_debut)) {
    $sql .= " AND c.date_debut >= ?";
    $params[] = $date_debut;
}
if (!empty($date_fin)) {
    $sql .= " AND c.date_debut <= ?";
    $params[] = $date_fin;
}

$sql .= " ORDER BY c.id DESC"; // Les plus récentes en haut

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

// Liste des CSE pour le menu déroulant
$entreprises = $pdo->query("SELECT * FROM entreprises ORDER BY nom ASC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Campagnes</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>Gestion Campagnes</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="form-label small fw-bold text-muted">Filtrer par CSE</label>
                        <select name="cse" class="form-select">
                            <option value="">-- Tous les CSE --</option>
                            <?php foreach($entreprises as $e): ?>
                                <option value="<?= $e['id'] ?>" <?= $cse_filter == $e['id'] ? 'selected':'' ?>>
                                    <?= htmlspecialchars($e['nom']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label small fw-bold text-muted">Début Période :</label>
                        <input type="date" name="date_debut" class="form-control" value="<?= htmlspecialchars($date_debut) ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small fw-bold text-muted">Fin Période :</label>
                        <input type="date" name="date_fin" class="form-control" value="<?= htmlspecialchars($date_fin) ?>">
                    </div>

                    <div class="col-md-3 d-flex">
                        <button type="submit" class="btn btn-dark w-100 me-2">
                            <i class="material-icons align-middle" style="font-size:18px">filter_alt</i> Filtrer
                        </button>
                        <a href="admin_campaigns.php" class="btn btn-outline-secondary" title="Réinitialiser">
                            <i class="material-icons align-middle" style="font-size:18px">restart_alt</i>
                        </a>
                    </div>
                    
                    <div class="col-md-2 text-end">
                        <button class="btn btn-gold w-100" type="button" data-bs-toggle="collapse" data-bs-target="#blocNew">
                            <i class="material-icons align-middle">add</i> Créer
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="collapse mb-4" id="blocNew">
            <div class="card card-body bg-light border-gold">
                <h6 class="mb-3 fw-bold">Ouvrir une nouvelle campagne de vente</h6>
                <form method="POST" class="row g-3">
                    <input type="hidden" name="action" value="add_campaign">
                    <div class="col-md-3">
                        <label class="form-label">Client (CSE)</label>
                        <select name="entreprise_id" class="form-select" required>
                            <?php foreach ($entreprises as $e): echo "<option value='{$e['id']}'>{$e['nom']}</option>"; endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Nom Campagne</label>
                        <input type="text" name="nom" class="form-control" placeholder="Ex: Vente Été 2026" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Date Début</label>
                        <input type="date" name="date_debut" class="form-control" value="<?= date('Y-m-d') ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Date Fin</label>
                        <input type="date" name="date_fin" class="form-control" required>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-success w-100">Valider Ouverture</button>
                    </div>
                </form>
            </div>
        </div>

        <div class="table-responsive shadow-sm">
            <table class="table table-bordered table-hover bg-white mb-0 align-middle">
                <thead class="table-light">
                    <tr>
                        <th>Statut</th>
                        <th>CSE</th>
                        <th>Campagne</th>
                        <th>Période</th>
                        <th>Prolongation ?</th>
                        <th>Master Commande</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(count($campagnes) == 0): ?>
                        <tr><td colspan="6" class="text-center py-4">Aucune campagne trouvée avec ces filtres.</td></tr>
                    <?php endif; ?>

                    <?php foreach ($campagnes as $c): 
                        $today = date('Y-m-d');
                        // Une campagne est ouverte si la date de fin n'est pas passée ET si le statut BDD est OUVERTE
                        $isOpen = ($c['date_fin'] >= $today && $c['statut'] == 'OUVERTE');
                    ?>
                    <tr>
                        <td>
                            <span class="badge bg-<?= $isOpen ? 'success' : 'secondary' ?>"><?= $isOpen ? 'OUVERTE' : 'TERMINÉE' ?></span>
                        </td>
                        <td class="fw-bold text-danger"><?= htmlspecialchars($c['nom_cse']) ?></td>
                        <td><?= htmlspecialchars($c['nom']) ?></td>
                        <td>
                            <div class="d-flex align-items-center">
                                <span class="me-2 small">Fin le :</span>
                                <form method="POST" class="d-flex align-items-center">
                                    <input type="hidden" name="action" value="manual_update">
                                    <input type="hidden" name="campagne_id" value="<?= $c['id'] ?>">
                                    <input type="date" name="date_fin" class="form-control form-control-sm me-1" value="<?= $c['date_fin'] ?>" style="width:135px;">
                                    <button class="btn btn-sm btn-link text-muted p-0" title="Enregistrer la modification"><i class="material-icons" style="font-size:16px">save</i></button>
                                </form>
                            </div>
                        </td>
                        <td>
                            <?php if ($c['date_fin_demandee']): ?>
                                <div class="alert alert-warning p-1 mb-0 d-flex align-items-center justify-content-between" style="font-size:0.85rem;">
                                    <span>Demande : <strong><?= date('d/m', strtotime($c['date_fin_demandee'])) ?></strong></span>
                                    <form method="POST" class="ms-2">
                                        <input type="hidden" name="action" value="accept_extension">
                                        <input type="hidden" name="campagne_id" value="<?= $c['id'] ?>">
                                        <input type="hidden" name="new_date" value="<?= $c['date_fin_demandee'] ?>">
                                        <button class="btn btn-sm btn-success py-0 px-2">OK</button>
                                    </form>
                                </div>
                            <?php else: ?>
                                <span class="text-muted small">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <a href="admin_master_order.php?id=<?= $c['id'] ?>" target="_blank" class="btn btn-outline-dark btn-sm w-100">
                                <i class="material-icons align-middle" style="font-size:16px">inventory</i> Liste Globale
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

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