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

// SÉCURITÉ : Seul le Super Admin (Vous) peut accéder ici
if ($_SESSION['user_role'] !== 'SUPER_ADMIN') {
    die("<div class='alert alert-danger m-5'>⛔ Accès interdit. Réservé à l'administration Naïta. <a href='dashboard.php'>Retour</a></div>");
}

$msg = "";

// --- TRAITEMENT : AJOUTER UN PRODUIT ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'add_product') {
    try {
        $ref = strtoupper(trim($_POST['reference']));
        $nom = trim($_POST['nom']);
        $prix = floatval($_POST['prix']);
        
        $sql = "INSERT INTO produits (reference, nom, prix_unitaire, actif) VALUES (?, ?, ?, 1)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$ref, $nom, $prix]);
        
        $msg = "<div class='alert alert-success'>✅ Produit <strong>$nom</strong> ajouté au catalogue !</div>";
    } catch (PDOException $e) {
        $msg = "<div class='alert alert-danger'>❌ Erreur (Réf existe déjà ?) : " . $e->getMessage() . "</div>";
    }
}

// --- TRAITEMENT : ACTIVER / DÉSACTIVER ---
if (isset($_GET['toggle_id'])) {
    $id = intval($_GET['toggle_id']);
    // On inverse l'état (Si 1 devient 0, Si 0 devient 1)
    $pdo->query("UPDATE produits SET actif = NOT actif WHERE id = $id");
    header('Location: admin_products.php'); // Recharge propre
    exit();
}

// Récupération de tous les produits
$produits = $pdo->query("SELECT * FROM produits ORDER BY reference 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 Produits - 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">
</head>
<body>

    <nav class="navbar navbar-dark bg-danger mb-4">
        <div class="container-fluid px-4">
            <span class="navbar-brand mb-0 h1">
                <i class="material-icons align-middle">admin_panel_settings</i>
                Administration Catalogue
            </span>
            <a href="dashboard.php" class="btn btn-outline-light btn-sm">Retour Dashboard</a>
        </div>
    </nav>

    <div class="container">
        <?= $msg ?>

        <div class="d-flex justify-content-between align-items-center mb-4">
            <h3>Catalogue Naïta</h3>
            <button class="btn btn-gold" data-bs-toggle="modal" data-bs-target="#modalAddProduct">
                <i class="material-icons align-middle">add</i> Nouveau Produit
            </button>
        </div>

        <div class="card shadow-sm">
            <div class="card-body p-0">
                <table class="table table-striped table-hover mb-0">
                    <thead class="table-dark">
                        <tr>
                            <th>État</th>
                            <th>Référence</th>
                            <th>Désignation</th>
                            <th>Prix Unitaire</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($produits as $p): ?>
                        <tr style="<?= $p['actif'] ? '' : 'opacity:0.6; background:#fbeeee' ?>">
                            <td>
                                <?php if($p['actif']): ?>
                                    <span class="badge bg-success">Actif</span>
                                <?php else: ?>
                                    <span class="badge bg-danger">Inactif</span>
                                <?php endif; ?>
                            </td>
                            <td class="fw-bold"><?= htmlspecialchars($p['reference']) ?></td>
                            <td><?= htmlspecialchars($p['nom']) ?></td>
                            <td class="fw-bold"><?= number_format($p['prix_unitaire'], 2) ?> €</td>
                            <td class="text-end">
                                <a href="?toggle_id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-secondary" title="Activer/Désactiver">
                                    <i class="material-icons align-middle" style="font-size:16px">power_settings_new</i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modalAddProduct" tabindex="-1">
        <div class="modal-dialog">
            <form method="POST" class="modal-content">
                <input type="hidden" name="action" value="add_product">
                <div class="modal-header bg-dark text-white">
                    <h5 class="modal-title">Ajouter un produit</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Référence (Code unique)</label>
                        <input type="text" name="reference" class="form-control" placeholder="Ex: NAITA-SAVON-01" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nom du produit</label>
                        <input type="text" name="nom" class="form-control" placeholder="Ex: Savon au lait d'ânesse" required>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Prix H.T (ou TTC selon choix)</label>
                            <input type="number" step="0.01" name="prix" class="form-control" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                    <button type="submit" class="btn btn-gold">Enregistrer</button>
                </div>
            </form>
        </div>
    </div>

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