<?php
$db = getDB();
$msg = '';
$msgType = '';

if (isset($_GET['delete']) && verifyCsrfToken($_GET['token'] ?? '')) {
    $db->prepare("DELETE FROM menu_items WHERE id = ?")->execute([(int)$_GET['delete']]);
    header('Location: /admin/menu?deleted=1');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCsrfToken($_POST['csrf_token'] ?? '')) {
    $title = trim($_POST['title'] ?? '');
    $url = trim($_POST['url'] ?? '');
    $parent_id = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
    $icon = trim($_POST['icon'] ?? '');
    $target = $_POST['target'] ?? '_self';
    $sort_order = (int)($_POST['sort_order'] ?? 0);

    if ($title && $url) {
        if (!empty($_POST['edit_id'])) {
            $stmt = $db->prepare("UPDATE menu_items SET title=?, url=?, parent_id=?, icon=?, target=?, sort_order=? WHERE id=?");
            $stmt->execute([$title, $url, $parent_id, $icon, $target, $sort_order, (int)$_POST['edit_id']]);
            $msg = 'Menu item updated.';
        } else {
            $stmt = $db->prepare("INSERT INTO menu_items (title, url, parent_id, icon, target, sort_order) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$title, $url, $parent_id, $icon, $target, $sort_order]);
            $msg = 'Menu item added.';
        }
        $msgType = 'success';
    } else {
        $msg = 'Title and URL are required.';
        $msgType = 'error';
    }
}

if (isset($_GET['deleted'])) {
    $msg = 'Menu item deleted.';
    $msgType = 'success';
}

$editItem = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM menu_items WHERE id = ?");
    $stmt->execute([(int)$_GET['edit']]);
    $editItem = $stmt->fetch();
}

$menuItems = getMenuItems();
$allItems = $db->query("SELECT * FROM menu_items WHERE parent_id IS NULL ORDER BY sort_order ASC")->fetchAll();
$csrfToken = generateCsrfToken();

include __DIR__ . '/admin_header.php';
?>

<style>
.menu-builder-list { border: 1px solid #e0e0e0; border-radius: 8px; }
.menu-builder-item { display: flex; align-items: center; gap: 12px; padding: 12px 15px; border-bottom: 1px solid #eee; background: #fff; cursor: move; transition: background 0.2s; }
.menu-builder-item:hover { background: #f8f9fa; }
.menu-builder-item:last-child { border-bottom: none; }
.menu-builder-child { padding-left: 45px; background: #f8f9fa; }
.menu-item-handle { color: #aaa; cursor: grab; }
.menu-item-handle:active { cursor: grabbing; }
.menu-item-info { flex: 1; }
.menu-item-title { font-weight: 600; font-size: 14px; color: #1a1a2e; }
.menu-item-url { font-size: 12px; color: #888; margin-left: 10px; }
.menu-item-actions { display: flex; gap: 5px; }
.btn-sm-xs { padding: 4px 10px; font-size: 12px; }
.menu-builder-item.dragging { opacity: 0.5; background: #e3f2fd; }
</style>

<div class="admin-topbar">
    <h2><i class="fas fa-bars"></i> Menu Builder</h2>
    <a href="/">View Site</a>
</div>

<?php if ($msg): ?>
<div class="alert alert-<?= $msgType ?>"><?= htmlspecialchars($msg) ?></div>
<?php endif; ?>

<div style="display:grid;grid-template-columns:1.5fr 1fr;gap:25px;align-items:start;">
    <div class="admin-card">
        <h3>Menu Structure</h3>
        <p style="font-size:13px;color:#666;margin-bottom:15px;">Drag items to reorder. Indent items to create dropdowns.</p>
        <div id="menu-list" class="menu-builder-list">
            <?php foreach ($menuItems as $item): ?>
            <div class="menu-builder-item" data-id="<?= $item['id'] ?>" data-parent="0">
                <div class="menu-item-handle"><i class="fas fa-grip-vertical"></i></div>
                <div class="menu-item-info">
                    <span class="menu-item-title"><?= htmlspecialchars($item['title']) ?></span>
                    <span class="menu-item-url"><?= htmlspecialchars($item['url']) ?></span>
                </div>
                <div class="menu-item-actions">
                    <a href="?edit=<?= $item['id'] ?>" class="btn-sm btn-sm-primary btn-sm-xs">Edit</a>
                    <a href="?delete=<?= $item['id'] ?>&token=<?= $csrfToken ?>" class="btn-sm btn-sm-danger btn-sm-xs" onclick="return confirm('Delete?')">Delete</a>
                </div>
            </div>
            <?php if (!empty($item['children'])): ?>
                <?php foreach ($item['children'] as $child): ?>
                <div class="menu-builder-item menu-builder-child" data-id="<?= $child['id'] ?>" data-parent="<?= $item['id'] ?>">
                    <div class="menu-item-handle"><i class="fas fa-grip-vertical"></i></div>
                    <div class="menu-item-info">
                        <span class="menu-item-title"><?= htmlspecialchars($child['title']) ?></span>
                        <span class="menu-item-url"><?= htmlspecialchars($child['url']) ?></span>
                    </div>
                    <div class="menu-item-actions">
                        <a href="?edit=<?= $child['id'] ?>" class="btn-sm btn-sm-primary btn-sm-xs">Edit</a>
                        <a href="?delete=<?= $child['id'] ?>&token=<?= $csrfToken ?>" class="btn-sm btn-sm-danger btn-sm-xs" onclick="return confirm('Delete?')">Delete</a>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
            <?php endforeach; ?>
        </div>
        <button id="save-order-btn" class="btn-sm btn-sm-success" style="margin-top:15px;" onclick="saveMenuOrder()"><i class="fas fa-save"></i> Save Order</button>
        <span id="save-status" style="margin-left:10px;font-size:13px;"></span>
    </div>

    <div class="admin-card">
        <h3><?= $editItem ? 'Edit Menu Item' : 'Add Menu Item' ?></h3>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= $csrfToken ?>">
            <?php if ($editItem): ?>
            <input type="hidden" name="edit_id" value="<?= $editItem['id'] ?>">
            <?php endif; ?>
            <div class="form-group">
                <label>Title *</label>
                <input type="text" name="title" value="<?= htmlspecialchars($editItem['title'] ?? '') ?>" required>
            </div>
            <div class="form-group">
                <label>URL *</label>
                <input type="text" name="url" value="<?= htmlspecialchars($editItem['url'] ?? '') ?>" required placeholder="e.g. /about or https://example.com">
            </div>
            <div class="form-group">
                <label>Parent Item</label>
                <select name="parent_id">
                    <option value="">— None (Top Level) —</option>
                    <?php foreach ($allItems as $pi): ?>
                    <?php if (!$editItem || $editItem['id'] != $pi['id']): ?>
                    <option value="<?= $pi['id'] ?>" <?= ($editItem && $editItem['parent_id'] == $pi['id']) ? 'selected' : '' ?>><?= htmlspecialchars($pi['title']) ?></option>
                    <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Icon Class</label>
                <input type="text" name="icon" value="<?= htmlspecialchars($editItem['icon'] ?? '') ?>" placeholder="e.g. fas fa-home">
            </div>
            <div class="form-group">
                <label>Target</label>
                <select name="target">
                    <option value="_self" <?= ($editItem && ($editItem['target'] ?? '_self') === '_self') ? 'selected' : '' ?>>Same Window (_self)</option>
                    <option value="_blank" <?= ($editItem && ($editItem['target'] ?? '') === '_blank') ? 'selected' : '' ?>>New Tab (_blank)</option>
                </select>
            </div>
            <div class="form-group">
                <label>Sort Order</label>
                <input type="number" name="sort_order" value="<?= htmlspecialchars($editItem['sort_order'] ?? '0') ?>">
            </div>
            <button type="submit" class="btn-sm btn-sm-primary"><?= $editItem ? 'Update Item' : 'Add Item' ?></button>
            <?php if ($editItem): ?>
            <a href="/admin/menu" class="btn-sm" style="margin-left:8px;">Cancel</a>
            <?php endif; ?>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var list = document.getElementById('menu-list');
    if (!list) return;
    
    var items = list.querySelectorAll('.menu-builder-item');
    var dragEl = null;
    
    items.forEach(function(item) {
        item.setAttribute('draggable', true);
        
        item.addEventListener('dragstart', function(e) {
            dragEl = this;
            this.classList.add('dragging');
            e.dataTransfer.effectAllowed = 'move';
        });
        
        item.addEventListener('dragend', function() {
            this.classList.remove('dragging');
            dragEl = null;
        });
        
        item.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
            var rect = this.getBoundingClientRect();
            var midY = rect.top + rect.height / 2;
            if (e.clientY < midY) {
                list.insertBefore(dragEl, this);
            } else {
                list.insertBefore(dragEl, this.nextSibling);
            }
        });
    });
});

function saveMenuOrder() {
    var items = document.querySelectorAll('#menu-list .menu-builder-item');
    var order = [];
    items.forEach(function(item, index) {
        order.push({
            id: parseInt(item.dataset.id),
            sort_order: index,
            parent_id: parseInt(item.dataset.parent) || 0
        });
    });
    
    var statusEl = document.getElementById('save-status');
    statusEl.textContent = 'Saving...';
    statusEl.style.color = '#0d6efd';
    
    fetch('/admin/menu-order', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ order: order, csrf_token: document.querySelector('input[name="csrf_token"]')?.value || '' })
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.success) {
            statusEl.textContent = 'Saved!';
            statusEl.style.color = '#198754';
        } else {
            statusEl.textContent = data.error || 'Failed';
            statusEl.style.color = '#dc3545';
        }
    })
    .catch(function() {
        statusEl.textContent = 'Error saving';
        statusEl.style.color = '#dc3545';
    });
}
</script>

<?php include __DIR__ . '/admin_footer.php'; ?>
