<?php
// admin_guides.php - VERSION FINALE : SAUVEGARDE DANS attraction_contents
ini_set('display_errors', 0); // Désactivé pour éviter de casser l'affichage
error_reporting(E_ALL);

require 'db.php';
require 'auth.php';

if (file_exists('includes/api_layer.php')) {
    require_once 'includes/api_layer.php';
} else {
    die("Erreur critique : Le fichier includes/api_layer.php est manquant.");
}

requireAdmin();

$msg = "";

// --- 1. RECUPERATION DES PARCS ---
try {
    $allParks = $pdo->query("SELECT id, name FROM parcs ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $allParks = []; }

$inputParkId = $_GET['park_id'] ?? ($allParks[0]['id'] ?? '354');

// --- 2. RÉCUPÉRATION DU WIKI_ID DU PARC ---
$targetWikiId = $inputParkId;
if (is_numeric($inputParkId)) {
    try {
        $stmtP = $pdo->prepare("SELECT wiki_id FROM parcs WHERE id = ?");
        $stmtP->execute([$inputParkId]);
        $foundId = $stmtP->fetchColumn();
        if ($foundId) $targetWikiId = $foundId;
    } catch (Exception $e) {}
}

// --- 3. SAUVEGARDE DU GUIDE (DANS attraction_contents) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save') {
    try {
        $attrId = $_POST['attraction_id'];
        $content = $_POST['guide_content']; // Le HTML de TinyMCE
        
        // On vérifie si un contenu existe déjà pour cet ID dans la table 'attraction_contents'
        $check = $pdo->prepare("SELECT attraction_id FROM attraction_contents WHERE attraction_id = ?");
        $check->execute([$attrId]);
        
        if ($check->rowCount() > 0) {
            // MISE À JOUR (UPDATE)
            $stmt = $pdo->prepare("UPDATE attraction_contents SET html_content = ?, updated_at = NOW() WHERE attraction_id = ?");
            $stmt->execute([$content, $attrId]);
        } else {
            // CRÉATION (INSERT)
            $stmt = $pdo->prepare("INSERT INTO attraction_contents (attraction_id, html_content, updated_at) VALUES (?, ?, NOW())");
            $stmt->execute([$attrId, $content]);
        }
        $msg = "✅ Guide enregistré avec succès dans la base !";
    } catch (Exception $e) {
        $msg = "❌ Erreur SQL : " . $e->getMessage();
    }
}

// --- 4. RECUPERATION DES CONFIGS LOCALES (Pour les icônes check vert) ---
$localContents = [];
try {
    $stmt = $pdo->query("SELECT attraction_id, html_content FROM attraction_contents");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $localContents[$row['attraction_id']] = $row;
    }
} catch (Exception $e) {}

// --- 5. RECUPERATION API (Liste des attractions à gauche) ---
$attractions = [];
try {
    $apiData = getApiDataCached('live', $targetWikiId, 3600);

    if (!function_exists('flatten')) {
        function flatten($data, &$result) {
            if (!is_array($data)) return;
            foreach ($data as $item) {
                if (isset($item['entityType']) && ($item['entityType'] === 'ATTRACTION' || $item['entityType'] === 'SHOW' || $item['entityType'] === 'RESTAURANT')) {
                    $result[] = $item;
                }
                if (isset($item['children']) && is_array($item['children'])) flatten($item['children'], $result);
                if (isset($item['liveData']) && is_array($item['liveData'])) flatten($item['liveData'], $result);
            }
        }
    }

    $rootData = $apiData['liveData'] ?? ($apiData['children'] ?? []);
    flatten($rootData, $attractions);

    usort($attractions, function($a, $b) { return strcmp($a['name'] ?? '', $b['name'] ?? ''); });

} catch (Exception $e) { $attractions = []; }

// --- 6. PRÉPARATION ÉDITION ---
$editContent = "";
$editName = "";
$editId = $_GET['edit_id'] ?? "";

if ($editId) {
    // On va chercher le contenu HTML existant dans 'attraction_contents'
    $stmtEdit = $pdo->prepare("SELECT html_content FROM attraction_contents WHERE attraction_id = ?");
    $stmtEdit->execute([$editId]);
    $editContent = $stmtEdit->fetchColumn() ?: "";
    
    foreach($attractions as $a) { 
        if(isset($a['id']) && $a['id'] == $editId) { $editName = $a['name']; break; } 
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Administration des Guides</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.2/tinymce.min.js" referrerpolicy="origin"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&display=swap" rel="stylesheet">
    <style>
        body { background-color: #090b11; color: #e2e8f0; font-family: 'Outfit', sans-serif; margin:0; padding:20px; }
        .container { max-width: 1400px; margin: 0 auto; display:grid; grid-template-columns: 350px 1fr; gap:30px; }
        
        .sidebar { background: #151b23; border-radius: 20px; border: 1px solid #30363d; padding: 20px; height: 85vh; display:flex; flex-direction:column; }
        .park-select { width: 100%; padding: 12px; background: #0d1117; color: white; border: 1px solid #38bdf8; border-radius: 12px; font-weight: bold; cursor: pointer; margin-bottom: 20px; font-family: inherit; }
        
        .attr-list { overflow-y: auto; flex: 1; }
        .attr-item { display: flex; align-items: center; padding: 12px; border-bottom: 1px solid rgba(255,255,255,0.03); color: #8b949e; text-decoration: none; transition: 0.2s; font-size: 0.9em; }
        .attr-item:hover { background: rgba(56, 189, 248, 0.05); color: white; }
        .attr-item.active { background: #38bdf8; color: black; font-weight: 800; border-radius: 10px; }
        .has-guide { color: #10b981; margin-right:10px; }
        
        .editor-area { background: #151b23; border-radius: 20px; border: 1px solid #30363d; padding: 30px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); }
        .btn-save { background: #10b981; color: white; border: none; padding: 12px 30px; border-radius: 10px; cursor: pointer; font-weight: 800; transition: 0.3s; display: flex; align-items: center; gap: 10px; }
        .btn-save:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(16, 185, 129, 0.4); }

        .tox-tinymce { border-radius: 12px !important; border: 1px solid #30363d !important; }
    </style>
</head>
<body>

<?php include 'includes/navbar.php'; ?>

    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:30px;">
        <h1 style="margin:0; font-weight:800; color:#38bdf8;"><i class="fa-solid fa-pen-nib"></i> Éditeur de Guides</h1>
        <a href="admin_dashboard.php" style="color:#8b949e; text-decoration:none; font-weight:bold;">⬅ Retour</a>
    </div>

    <div class="container">
        <!-- BARRE LATERALE -->
        <div class="sidebar">
            <select class="park-select" onchange="window.location.href='?park_id='+this.value">
                <?php foreach($allParks as $p): ?>
                    <option value="<?php echo $p['id']; ?>" <?php echo ($p['id'] == $inputParkId) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($p['name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <div class="attr-list">
                <?php foreach ($attractions as $attr): 
                    $aId = $attr['id'];
                    $hasGuide = !empty($localContents[$aId]);
                ?>
                    <a href="?park_id=<?php echo $inputParkId; ?>&edit_id=<?php echo $aId; ?>" 
                       class="attr-item <?php echo ($editId == $aId) ? 'active' : ''; ?>">
                        <?php if($hasGuide): ?><i class="fa-solid fa-check-circle has-guide"></i><?php endif; ?>
                        <?php echo htmlspecialchars($attr['name']); ?>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- ZONE EDITEUR -->
        <div class="editor-area">
            <?php if($editId): ?>
                <form method="POST">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:25px;">
                        <div>
                            <span style="font-size:0.8em; color:#8b949e; text-transform:uppercase; font-weight:800;">Édition du guide pour :</span>
                            <h2 style="margin:0; color:#fbbf24;"><?php echo htmlspecialchars($editName); ?></h2>
                        </div>
                        <button type="submit" class="btn-save"><i class="fa-solid fa-cloud-arrow-up"></i> ENREGISTRER</button>
                    </div>

                    <?php if($msg): ?><div style="background:rgba(16,185,129,0.1); color:#10b981; padding:15px; border-radius:12px; margin-bottom:20px; text-align:center; border:1px solid #10b981; font-weight:bold;"><?php echo $msg; ?></div><?php endif; ?>

                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="attraction_id" value="<?php echo $editId; ?>">
                    <textarea name="guide_content" id="editor"><?php echo htmlspecialchars($editContent); ?></textarea>
                </form>
            <?php else: ?>
                <div style="text-align:center; padding:150px 20px; color:#30363d;">
                    <i class="fa-solid fa-arrow-pointer fa-4x" style="margin-bottom:20px;"></i>
                    <h3>Sélectionnez une attraction pour créer ou modifier un guide.</h3>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        tinymce.init({
            selector: '#editor', 
            height: 650, 
            menubar: true, 
            skin: 'oxide-dark', 
            content_css: 'dark',
            plugins: 'image link lists media table code wordcount emoticons',
            toolbar: 'undo redo | blocks fontfamily | bold italic forecolor | alignleft aligncenter alignright | bullist numlist | link image emoticons | removeformat | code',
            content_style: "body { background-color: #0d1117; color: #e2e8f0; font-family: sans-serif; font-size: 16px; padding: 20px; } img { max-width:100%; border-radius:15px; }",
            branding: false,
            promotion: false
        });
    </script>
</body>
</html>