<?php
/**
 * Admin Menu Content Management
 */
require_once 'includes/header.php';

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'save_content') {
        $section = $_POST['section'] ?? '';
        $content = $_POST['content'] ?? '[]';
        
        try {
            // Validate JSON
            json_decode($content);
            if (json_last_error() !== JSON_ERROR_NONE) throw new Exception('Invalid JSON');
            
            setSetting('menu_' . $section, $content);
            $message = 'Content saved!';
            $messageType = 'success';
        } catch (Exception $e) {
            $message = 'Error: ' . $e->getMessage();
            $messageType = 'error';
        }
    }
}

$sections = [
    'whats_new' => "What's New",
    'top_traders' => 'Top Traders',
    'bonuses' => 'Bonuses',
    'education' => 'Education',
    'market' => 'Market',
    'tournaments' => 'Tournaments'
];

$currentContent = [];
foreach ($sections as $key => $label) {
    $currentContent[$key] = getSetting('menu_' . $key, '[]');
}
?>

<style>
.content-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; padding: 1.5rem; margin-bottom: 1.5rem; }
.content-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem; }
.content-title { font-size: 1.1rem; font-weight: 600; }
.content-textarea { width: 100%; min-height: 200px; background: var(--bg-tertiary); border: 1px solid var(--border-color); border-radius: 8px; padding: 1rem; color: #fff; font-family: monospace; font-size: 0.9rem; resize: vertical; }
.content-help { font-size: 0.8rem; color: var(--text-muted); margin-top: 0.5rem; }
.preview-box { background: var(--bg-tertiary); border-radius: 8px; padding: 1rem; margin-top: 1rem; }
.preview-item { display: flex; align-items: center; gap: 1rem; padding: 0.75rem; background: var(--bg-card); border-radius: 8px; margin-bottom: 0.5rem; }
.preview-icon { font-size: 1.5rem; }
.preview-info h4 { font-size: 0.9rem; margin-bottom: 0.25rem; }
.preview-info p { font-size: 0.8rem; color: var(--text-muted); }
</style>

<div class="page-header">
    <h1 class="page-title">Menu Content Management</h1>
</div>

<?php if ($message): ?>
<div class="alert alert-<?= $messageType ?>">
    <i class="fas fa-<?= $messageType === 'success' ? 'check-circle' : 'exclamation-circle' ?>"></i>
    <?= $message ?>
</div>
<?php endif; ?>

<?php foreach ($sections as $key => $label): ?>
<div class="content-card">
    <div class="content-header">
        <h3 class="content-title"><?= $label ?></h3>
        <button class="btn btn-sm btn-primary" onclick="saveContent('<?= $key ?>')">
            <i class="fas fa-save"></i> Save
        </button>
    </div>
    
    <form id="form_<?= $key ?>">
        <textarea class="content-textarea" id="content_<?= $key ?>" name="content"><?= htmlspecialchars($currentContent[$key]) ?></textarea>
        <div class="content-help">
            JSON format: [{"title": "Item Title", "desc": "Description", "icon": "🎁", "link": "/page.php"}]
        </div>
    </form>
    
    <div class="preview-box">
        <strong>Preview:</strong>
        <div id="preview_<?= $key ?>"></div>
    </div>
</div>
<?php endforeach; ?>

<script>
function saveContent(section) {
    const content = document.getElementById('content_' + section).value;
    
    fetch('menu-content.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'action=save_content&section=' + section + '&content=' + encodeURIComponent(content)
    }).then(r => {
        if (r.ok) {
            alert('Saved!');
            updatePreview(section);
        }
    });
}

function updatePreview(section) {
    try {
        const content = JSON.parse(document.getElementById('content_' + section).value);
        let html = '';
        content.forEach(item => {
            html += `<div class="preview-item">
                <span class="preview-icon">${item.icon || '📌'}</span>
                <div class="preview-info">
                    <h4>${item.title || 'No title'}</h4>
                    <p>${item.desc || 'No description'}</p>
                </div>
            </div>`;
        });
        document.getElementById('preview_' + section).innerHTML = html || '<p>No items</p>';
    } catch(e) {
        document.getElementById('preview_' + section).innerHTML = '<p style="color:red">Invalid JSON</p>';
    }
}

// Init previews
<?php foreach ($sections as $key => $label): ?>
updatePreview('<?= $key ?>');
document.getElementById('content_<?= $key ?>').addEventListener('input', () => updatePreview('<?= $key ?>'));
<?php endforeach; ?>
</script>

<?php require_once 'includes/footer.php'; ?>
