<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

if (!admin_is_authenticated()) {
    admin_redirect('/admin/?route=login');
}

$state = admin_refresh_state();
$config = $state['config'];
$errors = [];
$notice = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrfToken = (string) ($_POST['csrf_token'] ?? '');
    if (!admin_verify_csrf($csrfToken)) {
        $errors[] = 'Security token mismatch. Please refresh and try again.';
    } else {
        $labels = $_POST['menu_label'] ?? [];
        $urls = $_POST['menu_url'] ?? [];
        $enabled = $_POST['menu_enabled'] ?? [];
        $items = [];

        foreach ($labels as $index => $label) {
            $items[] = [
                'label' => (string) $label,
                'url' => (string) ($urls[$index] ?? ''),
                'enabled' => in_array((string) $index, array_map('strval', (array) $enabled), true),
            ];
        }

        if (cms_save_menu_items($items)) {
            $notice = 'Menu saved.';
        } else {
            $errors[] = 'Menu could not be saved.';
        }
    }
}

$menuItems = cms_get_menu_items();
if ($menuItems === []) {
    $menuItems = [
        ['label' => 'Home', 'url' => '/', 'status' => 'active'],
        ['label' => 'About', 'url' => '/about', 'status' => 'active'],
    ];
}
$siteTitle = admin_site_title($config);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo admin_escape($siteTitle); ?> Menus</title>
    <?php echo admin_shared_styles('.menu-item { display:grid; grid-template-columns:1.4fr 1.2fr auto; gap:12px; margin-bottom:12px; align-items:center; } @media (max-width: 720px) { .menu-item { grid-template-columns:1fr; } }'); ?>
</head>
<body>
<div class="app">
    <?php admin_render_sidebar('menus'); ?>
    <main class="content">
        <div class="page-header"><div><h1 class="page-title">Menu Builder</h1><div class="page-subtitle">Keep navigation simple and easy to update from phone or desktop.</div></div></div>
        <?php if ($notice !== ''): ?><div class="message success"><?php echo admin_escape($notice); ?></div><?php endif; ?>
        <?php foreach ($errors as $error): ?><div class="message error"><?php echo admin_escape($error); ?></div><?php endforeach; ?>
        <div class="panel">
            <form method="post" action="/admin/menus.php">
                <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                <div id="menu-builder">
                    <?php foreach ($menuItems as $index => $item): ?>
                        <div class="menu-item">
                            <input type="text" name="menu_label[]" value="<?php echo admin_escape((string) ($item['label'] ?? '')); ?>" placeholder="Label">
                            <input type="text" name="menu_url[]" value="<?php echo admin_escape((string) ($item['url'] ?? '')); ?>" placeholder="/about">
                            <label><input type="checkbox" name="menu_enabled[]" value="<?php echo (string) $index; ?>" <?php echo (($item['status'] ?? 'active') === 'active') ? 'checked' : ''; ?>> Active</label>
                        </div>
                    <?php endforeach; ?>
                    <?php for ($i = 0; $i < 3; $i++): ?>
                        <div class="menu-item">
                            <input type="text" name="menu_label[]" value="" placeholder="Label">
                            <input type="text" name="menu_url[]" value="" placeholder="/page">
                            <label><input type="checkbox" name="menu_enabled[]" value="<?php echo (string) (count($menuItems) + $i); ?>" checked> Active</label>
                        </div>
                    <?php endfor; ?>
                </div>
                <button class="btn" type="submit">Save Menu</button>
            </form>
        </div>
    </main>
</div>
</body>
</html>
