<?php
session_start();
require_once '../db.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: login.php');
    exit;
}

$message = '';

// 1. Récupération de tous les parcs (FILTRÉ : Uniquement ceux qui possèdent une API Queue-Times)
try {
    $stmt = $pdo->query("SELECT id, nom, api_slug, cover_image FROM parcs WHERE api_slug IS NOT NULL AND api_slug != '' ORDER BY nom ASC");
    $parcs = $stmt->fetchAll();
} catch (PDOException $e) {
    die("Erreur SQL : " . $e->getMessage());
}

// 2. Gestion du parc sélectionné pour l'édition
$parcSelectionne = null;
$id_selectionne = isset($_GET['edit_id']) ? intval($_GET['edit_id']) : 0;

if ($id_selectionne > 0) {
    foreach ($parcs as $p) {
        if ($p['id'] === $id_selectionne) {
            $parcSelectionne = $p;
            break;
        }
    }
}

// 3. Traitement du formulaire (Enregistrement / Action de suppression / Importation de fichier)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $parcSelectionne) {
    $nom = isset($_POST['nom']) ? trim($_POST['nom']) : '';
    $api_slug = isset($_POST['api_slug']) ? trim($_POST['api_slug']) : '';
    $cover_image = $parcSelectionne['cover_image']; // Par défaut, on garde l'ancienne valeur

    $upload_ok = true;

    // ACTION A : Suppression de l'image actuelle
    if (isset($_POST['action_supprimer_image'])) {
        if (!empty($cover_image) && file_exists("../img/covers/" . $cover_image)) {
            @unlink("../img/covers/" . $cover_image);
        }
        $cover_image = '';
    } 
    // ACTION B : Traitement de l'importation si un fichier est envoyé
    elseif (isset($_FILES['fichier_image']) && $_FILES['fichier_image']['error'] === UPLOAD_ERR_OK) {
        $file_tmp = $_FILES['fichier_image']['tmp_name'];
        $file_name = $_FILES['fichier_image']['name'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        $extensions_autorisees = ['jpg', 'jpeg', 'png', 'webp'];
        
        if (in_array($file_ext, $extensions_autorisees)) {
            $nouveau_nom_fichier = "parc_" . $parcSelectionne['id'] . "." . $file_ext;
            $destination = "../img/covers/" . $nouveau_nom_fichier;
            
            if (move_uploaded_file($file_tmp, $destination)) {
                $cover_image = $nouveau_nom_fichier;
            } else {
                $message = "<div class='pt-alert pt-alert-danger'><i class='fa-solid fa-circle-xmark'></i> Erreur lors du déplacement du fichier vers le dossier cible.</div>";
                $upload_ok = false;
            }
        } else {
            $message = "<div class='pt-alert pt-alert-danger'><i class='fa-solid fa-circle-xmark'></i> Format invalide. Uniquement JPG, JPEG, PNG ou WEBP.</div>";
            $upload_ok = false;
        }
    }

    // Sauvegarde en BDD
    if ($upload_ok && !empty($nom) && !empty($api_slug)) {
        try {
            $update = $pdo->prepare("UPDATE parcs SET nom = ?, api_slug = ?, cover_image = ? WHERE id = ?");
            $update->execute([$nom, $api_slug, $cover_image, $parcSelectionne['id']]);
            
            header("Location: modifsparcswait.php?edit_id=" . $parcSelectionne['id'] . "&success=1");
            exit;
        } catch (PDOException $e) {
            $message = "<div class='pt-alert pt-alert-danger'><i class='fa-solid fa-circle-xmark'></i> Erreur base de données : " . $e->getMessage() . "</div>";
        }
    }
}

if (isset($_GET['success'])) {
    $message = "<div class='pt-alert pt-alert-success'><i class='fa-solid fa-circle-check'></i> Mise à jour appliquée avec succès !</div>";
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Parcs Temps d'Attentes | ParcoTrip Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/style.css">
    
    <style>
        :root {
            --primary-admin: #4a51ff;
            --primary-light: rgba(74, 81, 255, 0.08);
            --bg-admin: #f8fafc;
            --border-color: #e2e8f0;
            --text-dark: #0f172a;
            --text-muted: #64748b;
        }

        body { background-color: var(--bg-admin); color: var(--text-dark); }
        .admin-main-grid { display: grid; grid-template-columns: 420px 1fr; gap: 30px; max-width: 1400px; margin: 0 auto; padding: 40px 20px; box-sizing: border-box; }
        @media (max-width: 992px) { .admin-main-grid { grid-template-columns: 1fr; } }

        .pt-admin-card { background: #ffffff; border: 1px solid var(--border-color); border-radius: 20px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.02); padding: 30px; box-sizing: border-box; }
        .pt-card-header { margin-bottom: 25px; border-bottom: 1px solid var(--border-color); padding-bottom: 20px; }
        .pt-card-header h2, .pt-card-header h3 { font-size: 1.35rem; font-weight: 800; color: var(--text-dark); margin: 0 0 6px 0; }
        .pt-card-header p { color: var(--text-muted); margin: 0; font-size: 0.88rem; line-height: 1.4; }

        .pt-park-list-wrapper { display: flex; flex-direction: column; gap: 10px; max-height: 650px; overflow-y: auto; padding-right: 5px; }
        .pt-park-list-wrapper::-webkit-scrollbar { width: 6px; }
        .pt-park-list-wrapper::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 10px; }

        .pt-admin-list-item { display: flex; align-items: center; gap: 16px; padding: 12px 16px; text-decoration: none; border-radius: 14px; border: 1px solid var(--border-color); transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1); background: #ffffff; }
        .pt-admin-list-item:hover { transform: translateY(-2px); box-shadow: 0 6px 15px rgba(74, 81, 255, 0.06); border-color: var(--primary-admin); }
        .pt-item-active { background: var(--primary-light) !important; border-color: var(--primary-admin) !important; }

        .pt-list-thumb-container { width: 64px; height: 48px; border-radius: 8px; overflow: hidden; background: #f1f5f9; flex-shrink: 0; border: 1px solid rgba(0,0,0,0.05); display: flex; align-items: center; justify-content: center; }
        .pt-list-thumb { width: 100%; height: 100%; object-fit: cover; }

        .pt-item-info-block { flex: 1; display: flex; flex-direction: column; gap: 4px; }
        .pt-item-title { font-weight: 700; font-size: 0.95rem; color: var(--text-dark); }
        .pt-item-active .pt-item-title { color: var(--primary-admin); }

        .pt-item-meta { display: flex; align-items: center; gap: 8px; }
        .pt-admin-badge { font-size: 0.75rem; font-weight: 700; padding: 2px 8px; border-radius: 6px; background: #f1f5f9; color: #475569; }
        .pt-item-active .pt-admin-badge { background: rgba(74, 81, 255, 0.15); color: var(--primary-admin); }

        .pt-status-dot { width: 6px; height: 6px; border-radius: 50%; }
        .pt-status-has-img { background-color: #22c55e; }
        .pt-status-no-img { background-color: #94a3b8; }

        .pt-form-group { display: flex; flex-direction: column; gap: 8px; margin-bottom: 20px; }
        .pt-form-group label { font-size: 0.88rem; font-weight: 700; color: #334155; }

        .pt-form-control { width: 100%; padding: 12px 16px; border-radius: 12px; border: 1px solid #cbd5e1; font-family: inherit; font-size: 0.95rem; box-sizing: border-box; transition: all 0.2s; background-color: #f8fafc; }
        .pt-form-control:focus { outline: none; background-color: #ffffff; border-color: var(--primary-admin); box-shadow: 0 0 0 4px rgba(74, 81, 255, 0.1); }

        .pt-alert { padding: 14px 18px; border-radius: 12px; font-size: 0.92rem; font-weight: 600; margin-bottom: 25px; display: flex; align-items: center; gap: 10px; line-height: 1.4; }
        .pt-alert-success { background: #f0fdf4; color: #166534; border: 1px solid #bbf7d0; }
        .pt-alert-danger { background: #fef2f2; color: #991b1b; border: 1px solid #fee2e2; }

        .pt-preview-banner-box { position: relative; width: 100%; height: 180px; border-radius: 14px; overflow: hidden; background: #f1f5f9; border: 1px dashed #cbd5e1; margin-bottom: 20px; }
        .pt-preview-banner-img { width: 100%; height: 100%; object-fit: cover; }
        .pt-preview-overlay-delete { position: absolute; top: 15px; right: 15px; }

        .pt-btn-delete-img { background: rgba(239, 68, 68, 0.95); color: #ffffff; border: none; padding: 8px 14px; border-radius: 8px; font-size: 0.8rem; font-weight: 700; cursor: pointer; box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2); }
        .pt-btn-delete-img:hover { background: #dc2626; }

        .pt-upload-wrapper { position: relative; width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 25px; background: #f8fafc; border: 2px dashed #cbd5e1; border-radius: 12px; box-sizing: border-box; cursor: pointer; transition: all 0.2s; }
        .pt-upload-wrapper:hover { border-color: var(--primary-admin); background: var(--primary-light); }
        .pt-upload-wrapper input[type="file"] { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
        .pt-upload-text { font-size: 0.88rem; font-weight: 600; color: #475569; margin-top: 8px; text-align: center; }

        .pt-btn-submit-form { background: #0f172a; color: #ffffff; padding: 14px 24px; border: none; border-radius: 12px; font-weight: 700; font-size: 0.95rem; cursor: pointer; width: 100%; }
        .pt-btn-submit-form:hover { background: var(--primary-admin); }
    </style>
</head>
<body>

    <?php include_once 'sidebaradmin.php'; ?>

    <main class="admin-main-grid">
        
        <div class="pt-admin-card">
            <div class="pt-card-header">
                <h2>Parcs Temps d'Attentes</h2>
                <p>Retrouvez la liste des parcs connectés et l'état de leurs images de couverture.</p>
            </div>

            <div class="pt-park-list-wrapper">
                <?php foreach ($parcs as $p): 
                    $has_cover = !empty($p['cover_image']) && file_exists("../img/covers/" . $p['cover_image']);
                    $image_src = $has_cover ? "../img/covers/" . $p['cover_image'] : "../img/covers/default.jpg";
                ?>
                    <a href="modifsparcswait.php?edit_id=<?php echo $p['id']; ?>" 
                       class="pt-admin-list-item <?php echo ($id_selectionne === $p['id']) ? 'pt-item-active' : ''; ?>">
                        
                        <div class="pt-list-thumb-container">
                            <img src="<?php echo $image_src; ?>" alt="Miniature" class="pt-list-thumb">
                        </div>

                        <div class="pt-item-info-block">
                            <span class="pt-item-title"><?php echo htmlspecialchars($p['nom']); ?></span>
                            <div class="pt-item-meta">
                                <span class="pt-status-dot <?php echo !empty($p['cover_image']) ? 'pt-status-has-img' : 'pt-status-no-img'; ?>"></span>
                                <span class="pt-admin-badge">ID API : <?php echo htmlspecialchars($p['api_slug']); ?></span>
                            </div>
                        </div>

                        <div><i class="fa-solid fa-chevron-right" style="font-size: 0.8rem; opacity: 0.4;"></i></div>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>

        <div>
            <?php echo $message; ?>

            <div class="pt-admin-card" style="position: sticky; top: 120px;">
                <?php if ($parcSelectionne): 
                    $has_cover_sel = !empty($parcSelectionne['cover_image']) && file_exists("../img/covers/" . $parcSelectionne['cover_image']);
                    $image_src_sel = $has_cover_sel ? "../img/covers/" . $parcSelectionne['cover_image'] : "../img/covers/default.jpg";
                ?>
                    <div class="pt-card-header">
                        <h3>Édition : <?php echo htmlspecialchars($parcSelectionne['nom']); ?></h3>
                        <p>Ajustez les valeurs ou importez une image directement sur votre serveur.</p>
                    </div>

                    <form action="modifsparcswait.php?edit_id=<?php echo $parcSelectionne['id']; ?>" method="POST" enctype="multipart/form-data">
                        
                        <div class="pt-form-group">
                            <label>Couverture du complexe</label>
                            
                            <?php if (!empty($parcSelectionne['cover_image'])): ?>
                                <div class="pt-preview-banner-box">
                                    <img src="<?php echo $image_src_sel; ?>" alt="Preview" class="pt-preview-banner-img">
                                    <div class="pt-preview-overlay-delete">
                                        <button type="submit" name="action_supprimer_image" class="pt-btn-delete-img" onclick="return confirm('Supprimer définitivement l\'image de couverture de ce parc ?');"><i class="fa-solid fa-trash-can"></i> Détacher l'image</button>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div class="pt-upload-wrapper">
                                    <i class="fa-solid fa-cloud-arrow-up" style="font-size: 2rem; color: var(--primary-admin);"></i>
                                    <span class="pt-upload-text">Cliquez ici pour importer une image</span>
                                    <small style="color: var(--text-muted); font-size: 0.75rem; margin-top: 4px;">Fichiers acceptés : JPG, PNG, WEBP</small>
                                    <input type="file" name="fichier_image" accept="image/*" onchange="this.form.submit();">
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="pt-form-group">
                            <label for="nom">Nom du complexe de loisirs</label>
                            <input type="text" name="nom" id="nom" class="pt-form-control" value="<?php echo htmlspecialchars($parcSelectionne['nom']); ?>" required>
                        </div>

                        <div class="pt-form-group" style="margin-bottom: 30px;">
                            <label for="api_slug">Identifiant API (Queue-Times)</label>
                            <input type="text" name="api_slug" id="api_slug" class="pt-form-control" value="<?php echo htmlspecialchars($parcSelectionne['api_slug']); ?>" required>
                        </div>

                        <button type="submit" class="pt-btn-submit-form">
                            <i class="fa-solid fa-floppy-disk"></i> Enregistrer les informations
                        </button>

                    </form>
                <?php else: ?>
                    <div style="text-align: center; padding: 60px 20px; color: var(--text-muted);">
                        <i class="fa-solid fa-wand-magic-sparkles" style="font-size: 2.5rem; margin-bottom: 15px; color: #cbd5e1; display: block;"></i>
                        <p style="font-weight: 700; margin: 0; font-size: 1.1rem; color: var(--text-dark);">Aucun parc sélectionné</p>
                        <p style="font-size: 0.88rem; margin: 8px 0 0 0; line-height: 1.5;">Sélectionnez un parc dans la colonne de gauche pour mettre à jour son contenu ou importer son image de fond.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

    </main>

    <footer class="main-footer" style="margin-top: 60px; text-align: center; padding: 20px; color: var(--text-muted);">
        <p>&copy; 2026 ParcoTrip Administration.</p>
    </footer>

</body>
</html>