<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

$route = strtolower(trim((string) ($_GET['route'] ?? 'dashboard')));
$allowedRoutes = ['login', 'dashboard', 'settings', 'layout', 'pages', 'plugins', 'logout'];
if (!in_array($route, $allowedRoutes, true)) {
    $route = admin_is_authenticated() ? 'dashboard' : 'login';
}

$state = admin_refresh_state($route !== 'login');
$config = $state['config'];
$availableThemes = $state['availableThemes'];
$themeRegistry = $state['themeRegistry'] ?? [];
$pluginRegistry = $state['pluginRegistry'];
$registeredBlocks = $state['registeredBlocks'];
$dbAvailable = $state['dbAvailable'];
$homepageBlocks = is_array($config['homepage_blocks'] ?? null) ? $config['homepage_blocks'] : [];
$subpagePluginOptions = $pluginRegistry;
$infoChartBaseSlug = function_exists('cms_info_chart_base_slug') ? cms_info_chart_base_slug($config) : (string) ($config['info_chart_base_slug'] ?? 'info-chart');

$errors = [];
$notice = '';

if ($route === 'logout') {
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 3600, $params['path'], $params['domain'], (bool) $params['secure'], (bool) $params['httponly']);
    }
    session_destroy();
    admin_redirect('/admin/?route=login');
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrfToken = (string) ($_POST['csrf_token'] ?? '');

    if (!admin_verify_csrf($csrfToken)) {
        $errors[] = 'Security token mismatch. Please refresh and try again.';
    } elseif ($route === 'login') {
        $username = trim((string) ($_POST['username'] ?? ''));
        $password = (string) ($_POST['password'] ?? '');

        if ($username === '' || $password === '') {
            $errors[] = 'Username and password are required.';
        } elseif (($user = cms_authenticate_user($username, $password)) === null) {
            $errors[] = 'Invalid login credentials.';
        } else {
            session_regenerate_id(true);
            $_SESSION['cms_user'] = $user;
            admin_redirect('/admin/');
        }
    } elseif (admin_is_authenticated() && $route === 'plugins') {
        $action = strtolower(trim((string) ($_POST['plugin_manager_action'] ?? '')));
        $activePlugins = cms_get_active_plugins($config);

        if ($action === 'toggle') {
            $pluginSlug = strtolower(trim((string) ($_POST['plugin_slug'] ?? '')));
            if (!isset($pluginRegistry[$pluginSlug])) {
                $payload = ['ok' => false, 'message' => 'Plugin not found.'];
                if (admin_is_ajax()) {
                    admin_json_response($payload, 404);
                }
                $errors[] = $payload['message'];
            } else {
                if (in_array($pluginSlug, $activePlugins, true)) {
                    $activePlugins = array_values(array_filter($activePlugins, static fn(string $slug): bool => $slug !== $pluginSlug));
                    $newStatus = 'inactive';
                } else {
                    $activePlugins[] = $pluginSlug;
                    $activePlugins = array_values(array_unique($activePlugins));
                    $newStatus = 'active';
                }

                $config['active_plugins'] = $activePlugins;
                if (cms_save_config($config, CMS_ROOT)) {
                    cms_set_plugin_status($pluginSlug, $newStatus === 'active');
                    $state = admin_refresh_state();
                    $config = $state['config'];
                    $availableThemes = $state['availableThemes'];
                    $themeRegistry = $state['themeRegistry'] ?? [];
                    $pluginRegistry = $state['pluginRegistry'];
                    $registeredBlocks = $state['registeredBlocks'];
                    $homepageBlocks = is_array($config['homepage_blocks'] ?? null) ? $config['homepage_blocks'] : [];
                    $payload = [
                        'ok' => true,
                        'message' => 'Plugin ' . ($newStatus === 'active' ? 'activated' : 'deactivated') . '.',
                        'status' => $newStatus,
                    ];
                    if (admin_is_ajax()) {
                        admin_json_response($payload);
                    }
                    $notice = $payload['message'];
                } else {
                    $payload = ['ok' => false, 'message' => 'Plugin state could not be saved.'];
                    if (admin_is_ajax()) {
                        admin_json_response($payload, 500);
                    }
                    $errors[] = $payload['message'];
                }
            }
        } elseif ($action === 'create') {
            $pluginName = trim((string) ($_POST['plugin_name'] ?? ''));
            $pluginSlug = trim((string) ($_POST['plugin_slug'] ?? ''));
            $activateNow = !empty($_POST['activate_now']);
            $result = admin_create_plugin($pluginName, $pluginSlug, $activateNow);
            if ($result['ok']) {
                $state = admin_refresh_state();
                $config = $state['config'];
                $availableThemes = $state['availableThemes'];
                $themeRegistry = $state['themeRegistry'] ?? [];
                $pluginRegistry = $state['pluginRegistry'];
                $registeredBlocks = $state['registeredBlocks'];
                $homepageBlocks = is_array($config['homepage_blocks'] ?? null) ? $config['homepage_blocks'] : [];
                $notice = (string) $result['message'];
            } else {
                $errors[] = (string) $result['message'];
            }
        }
    } elseif (admin_is_authenticated() && $route === 'layout') {
        $enabledBlocks = $_POST['homepage_blocks'] ?? [];
        $layoutOrder = trim((string) ($_POST['layout_order'] ?? ''));

        if (!is_array($enabledBlocks)) {
            $enabledBlocks = [];
        }

        $enabledBlocks = array_values(array_unique(array_map(static fn($value): string => strtolower(trim((string) $value)), $enabledBlocks)));
        $enabledBlocks = array_values(array_filter($enabledBlocks, static fn(string $value): bool => in_array($value, $registeredBlocks, true)));
        $orderedBlocks = array_values(array_filter(array_map('trim', explode(',', $layoutOrder))));
        $orderedBlocks = array_values(array_filter($orderedBlocks, static fn(string $value): bool => in_array($value, $registeredBlocks, true)));

        $finalBlocks = [];
        foreach ($orderedBlocks as $blockName) {
            if (in_array($blockName, $enabledBlocks, true) && !in_array($blockName, $finalBlocks, true)) {
                $finalBlocks[] = $blockName;
            }
        }
        foreach ($enabledBlocks as $blockName) {
            if (!in_array($blockName, $finalBlocks, true)) {
                $finalBlocks[] = $blockName;
            }
        }

        $config['homepage_blocks'] = $finalBlocks;
        if (cms_save_config($config, CMS_ROOT)) {
            cms_save_homepage_blocks_wp($finalBlocks);
            $state = admin_refresh_state();
            $config = $state['config'];
            $availableThemes = $state['availableThemes'];
            $themeRegistry = $state['themeRegistry'] ?? [];
            $pluginRegistry = $state['pluginRegistry'];
            $registeredBlocks = $state['registeredBlocks'];
            $homepageBlocks = is_array($config['homepage_blocks'] ?? null) ? $config['homepage_blocks'] : [];
            $notice = 'Homepage layout updated.';
        } else {
            $errors[] = 'Homepage layout could not be saved.';
        }
    } elseif (admin_is_authenticated() && $route === 'settings') {
        $settingsAction = strtolower(trim((string) ($_POST['settings_action'] ?? 'save')));
        if ($settingsAction === 'clear_cache') {
            if (function_exists('db_cache_flush')) {
                db_cache_flush();
                $notice = 'Cache cleared.';
            } else {
                $errors[] = 'Cache system is not available in this environment.';
            }
        } else {
            $siteTitlePost = trim((string) ($_POST['site_title'] ?? ''));
            $activeThemePost = trim((string) ($_POST['active_theme'] ?? ''));
            $infoChartBaseSlugPost = function_exists('cms_normalize_route_slug')
                ? cms_normalize_route_slug((string) ($_POST['info_chart_base_slug'] ?? 'info-chart'), 'info-chart')
                : 'info-chart';
            if ($siteTitlePost === '') {
                $errors[] = 'Site title is required.';
            }
            if (!in_array($activeThemePost, $availableThemes, true)) {
                $errors[] = 'Please choose a valid theme.';
            }
            if ($errors === []) {
                $config['site_title'] = $siteTitlePost;
                $config['active_theme'] = $activeThemePost;
                $config['info_chart_base_slug'] = $infoChartBaseSlugPost;
                if (cms_save_config($config, CMS_ROOT)) {
                    if ($dbAvailable) {
                        cms_set_setting('site_title', $siteTitlePost);
                        cms_set_setting('active_theme', $activeThemePost);
                        if (function_exists('cms_set_info_chart_base_slug')) {
                            cms_set_info_chart_base_slug($infoChartBaseSlugPost);
                        }
                    }
                    $state = admin_refresh_state();
                    $config = $state['config'];
                    $availableThemes = $state['availableThemes'];
                    $themeRegistry = $state['themeRegistry'] ?? [];
                    $pluginRegistry = $state['pluginRegistry'];
                    $registeredBlocks = $state['registeredBlocks'];
                    $homepageBlocks = is_array($config['homepage_blocks'] ?? null) ? $config['homepage_blocks'] : [];
                    $infoChartBaseSlug = function_exists('cms_info_chart_base_slug') ? cms_info_chart_base_slug($config) : (string) ($config['info_chart_base_slug'] ?? 'info-chart');
                    $notice = 'Settings saved.';
                } else {
                    $errors[] = 'Settings could not be saved.';
                }
            }
        }
    } elseif (admin_is_authenticated() && $route === 'pages') {
        $pageAction = strtolower(trim((string) ($_POST['page_action'] ?? 'save')));
        if (!$dbAvailable) {
            $errors[] = 'Database connection is required for pages.';
        } elseif ($pageAction === 'delete') {
            $pageId = (int) ($_POST['page_id'] ?? 0);
            if ($pageId < 1 || !cms_delete_page($pageId)) {
                $errors[] = 'Page could not be deleted.';
            } else {
                $notice = 'Page deleted.';
            }
        } else {
            $pagePayload = [
                'id' => (int) ($_POST['page_id'] ?? 0),
                'slug' => (string) ($_POST['slug'] ?? ''),
                'title' => (string) ($_POST['title'] ?? ''),
                'content' => (string) ($_POST['content'] ?? ''),
                'header_content' => (string) ($_POST['header_content'] ?? ''),
                'footer_content' => (string) ($_POST['footer_content'] ?? ''),
                'hidden_blocks' => $_POST['hidden_blocks'] ?? [],
                'meta_title' => (string) ($_POST['meta_title'] ?? ''),
                'meta_description' => (string) ($_POST['meta_description'] ?? ''),
                'schema_json' => (string) ($_POST['schema_json'] ?? ''),
            ];
            $schemaJson = trim((string) $pagePayload['schema_json']);
            if ($schemaJson !== '') {
                json_decode($schemaJson, true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $errors[] = 'Schema JSON-LD is not valid JSON.';
                }
            }
            if ($errors === [] && !cms_save_page($pagePayload)) {
                $errors[] = 'Page could not be saved.';
            } elseif ($errors === []) {
                $notice = 'Page saved.';
            }
        }
    }
}

$siteTitle = admin_site_title($config);
$activeTheme = admin_active_theme($config);
$infoChartBaseSlug = function_exists('cms_info_chart_base_slug') ? cms_info_chart_base_slug($config) : (string) ($config['info_chart_base_slug'] ?? 'info-chart');
$activeThemeMeta = $themeRegistry[$activeTheme] ?? ['name' => $activeTheme, 'version' => '', 'author' => '', 'description' => '', 'screenshot' => ''];
$themeCount = count($availableThemes);
$pluginCount = count($pluginRegistry);
$activePluginCount = count(array_filter($pluginRegistry, static fn(array $plugin): bool => !empty($plugin['active'])));
$pages = $dbAvailable ? cms_get_pages() : [];
$editingPageId = (int) ($_GET['page_id'] ?? 0);
$editingPage = null;
foreach ($pages as $pageRow) {
    if ((int) ($pageRow['id'] ?? 0) === $editingPageId) {
        $editingPage = $pageRow;
        break;
    }
}
$editingHiddenBlocks = cms_normalize_page_hidden_blocks($editingPage['hidden_blocks_json'] ?? []);

$layoutBlocks = [];
foreach ($registeredBlocks as $blockName) {
    $layoutBlocks[$blockName] = in_array($blockName, $homepageBlocks, true);
}
uksort($layoutBlocks, static function (string $left, string $right) use ($homepageBlocks): int {
    $leftOrder = array_search($left, $homepageBlocks, true);
    $rightOrder = array_search($right, $homepageBlocks, true);
    $leftOrder = $leftOrder === false ? 999 : (int) $leftOrder;
    $rightOrder = $rightOrder === false ? 999 : (int) $rightOrder;
    return $leftOrder <=> $rightOrder;
});

$isLoginRoute = $route === 'login';
?>
<!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); ?> Admin</title>
    <?php echo admin_shared_styles('.login-shell { min-height:100vh; display:grid; place-items:center; padding:24px; } .login-card { width:min(460px,100%); padding:32px; } .plugin-card form { margin-top:14px; } .layout-item { cursor:move; }'); ?>
</head>
<body>
<?php if ($isLoginRoute): ?>
    <div class="login-shell">
        <form class="login-card" method="post" action="/admin/?route=login">
            <h1 style="margin-top:0;">CMS Admin</h1>
            <?php foreach ($errors as $error): ?><div class="message error"><?php echo admin_escape($error); ?></div><?php endforeach; ?>
            <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
            <div class="form-row">
                <label for="username">Username</label>
                <input id="username" name="username" type="text" required>
            </div>
            <div class="form-row">
                <label for="password">Password</label>
                <input id="password" name="password" type="password" required>
            </div>
            <button class="btn" type="submit">Login</button>
        </form>
    </div>
<?php else: ?>
    <div class="app">
        <?php admin_render_sidebar($route === 'plugins' ? 'plugins' : $route); ?>
        <main class="content">
            <?php if ($route === 'plugins'): ?>
                <div class="page-header"><div><h1 class="page-title">Plugin Manager</h1><div class="page-subtitle">Manage installed plugins and quick activation from one place.</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">
                    <div class="grid">
                        <?php foreach ($pluginRegistry as $plugin): ?>
                            <div class="stat-card plugin-card" data-plugin="<?php echo admin_escape((string) $plugin['slug']); ?>">
                                <div class="stat-label plugin-status"><?php echo !empty($plugin['active']) ? 'Active' : 'Inactive'; ?></div>
                                <div class="stat-value" style="font-size:22px;"><?php echo admin_escape((string) $plugin['name']); ?></div>
                                <p style="margin:10px 0 0;color:var(--muted);"><?php echo admin_escape((string) $plugin['description']); ?></p>
                                <p style="margin:8px 0 0;color:var(--muted);font-size:13px;">Slug: <?php echo admin_escape((string) ($plugin['declared_slug'] ?? $plugin['slug'])); ?></p>
                                <p style="margin:6px 0 0;color:var(--muted);font-size:13px;">Version: <?php echo admin_escape((string) $plugin['version']); ?></p>
                                <?php if (!empty($plugin['error'])): ?><div class="message error" style="margin-top:12px;"><?php echo admin_escape((string) $plugin['error']); ?></div><?php endif; ?>
                                <form method="post" action="/admin/?route=plugins" class="plugin-toggle-form">
                                    <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                                    <input type="hidden" name="plugin_manager_action" value="toggle">
                                    <input type="hidden" name="response_format" value="json">
                                    <input type="hidden" name="plugin_slug" value="<?php echo admin_escape((string) $plugin['slug']); ?>">
                                    <button class="btn plugin-toggle-button" type="submit"><?php echo !empty($plugin['active']) ? 'Deactivate' : 'Activate'; ?></button>
                                </form>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="panel">
                    <h2 style="margin-top:0;">Add New Plugin</h2>
                    <form method="post" action="/admin/?route=plugins">
                        <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                        <input type="hidden" name="plugin_manager_action" value="create">
                        <div class="form-row">
                            <label for="plugin_name">Plugin Name</label>
                            <input id="plugin_name" name="plugin_name" type="text" required>
                        </div>
                        <div class="form-row">
                            <label for="plugin_slug">Plugin Slug</label>
                            <input id="plugin_slug" name="plugin_slug" type="text" required>
                        </div>
                        <label style="display:flex;gap:10px;align-items:center;margin:0 0 16px;">
                            <input type="checkbox" name="activate_now" value="1" checked>
                            Activate immediately
                        </label>
                        <button class="btn" type="submit">Create Plugin</button>
                    </form>
                </div>
            <?php elseif ($route === 'layout'): ?>
                <div class="page-header"><div><h1 class="page-title">Block Layout Builder</h1><div class="page-subtitle">Reorder homepage blocks with a touch-friendly layout builder.</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/?route=layout" id="layout-builder-form">
                        <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                        <input type="hidden" name="layout_order" id="layout_order" value="<?php echo admin_escape(implode(',', array_keys($layoutBlocks))); ?>">
                        <div id="layout-builder" style="display:grid;gap:14px;">
                            <?php foreach ($layoutBlocks as $blockName => $enabled): ?>
                                <div class="stat-card layout-item" draggable="true" data-block="<?php echo admin_escape($blockName); ?>">
                                    <div style="display:flex;justify-content:space-between;gap:14px;align-items:center;">
                                        <div>
                                            <div class="stat-value" style="font-size:20px;"><?php echo admin_escape(ucwords(str_replace(['-', '_'], ' ', $blockName))); ?></div>
                                            <div class="stat-label"><?php echo admin_escape($blockName); ?></div>
                                        </div>
                                        <label style="display:flex;gap:10px;align-items:center;">
                                            <input type="checkbox" name="homepage_blocks[]" value="<?php echo admin_escape($blockName); ?>" <?php echo $enabled ? 'checked' : ''; ?>>
                                            Enabled
                                        </label>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <div style="margin-top:18px;"><button class="btn" type="submit">Save Layout</button></div>
                    </form>
                </div>
            <?php elseif ($route === 'settings'): ?>
                <div class="page-header"><div><h1 class="page-title">Settings</h1><div class="page-subtitle">Theme, site title, and cache controls in a simpler WordPress-style screen.</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/?route=settings">
                        <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                        <input type="hidden" name="settings_action" value="save">
                        <div class="form-row">
                            <label for="site_title">Site Title</label>
                            <input id="site_title" name="site_title" type="text" value="<?php echo admin_escape($siteTitle); ?>" required>
                        </div>
                        <div class="form-row">
                            <label for="active_theme">Active Theme</label>
                            <select id="active_theme" name="active_theme">
                                <?php foreach ($availableThemes as $theme): ?>
                                    <?php $themeMeta = $themeRegistry[$theme] ?? ['name' => $theme, 'version' => '']; ?>
                                    <option value="<?php echo admin_escape($theme); ?>" <?php echo $theme === $activeTheme ? 'selected' : ''; ?>><?php echo admin_escape((string) ($themeMeta['name'] ?? $theme)); ?><?php echo !empty($themeMeta['version']) ? ' v' . admin_escape((string) $themeMeta['version']) : ''; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-row">
                            <label for="info_chart_base_slug">Info Chart Base URL</label>
                            <input id="info_chart_base_slug" name="info_chart_base_slug" type="text" value="<?php echo admin_escape($infoChartBaseSlug); ?>" required>
                        </div>
                        <div class="inline-actions">
                            <button class="btn" type="submit">Save Settings</button>
                        </div>
                    </form>
                    <div class="stat-card" style="margin-top:18px;">
                        <div class="stat-label">Current Theme</div>
                        <div class="stat-value" style="font-size:24px;"><?php echo admin_escape((string) ($activeThemeMeta['name'] ?? $activeTheme)); ?></div>
                        <?php if (!empty($activeThemeMeta['version'])): ?><p style="margin:10px 0 0;color:var(--muted);">Version: <?php echo admin_escape((string) $activeThemeMeta['version']); ?></p><?php endif; ?>
                        <?php if (!empty($activeThemeMeta['author'])): ?><p style="margin:6px 0 0;color:var(--muted);">Author: <?php echo admin_escape((string) $activeThemeMeta['author']); ?></p><?php endif; ?>
                        <?php if (!empty($activeThemeMeta['description'])): ?><p style="margin:10px 0 0;color:var(--muted);"><?php echo admin_escape((string) $activeThemeMeta['description']); ?></p><?php endif; ?>
                        <?php if (!empty($activeThemeMeta['screenshot'])): ?>
                            <p style="margin:14px 0 0;"><img src="<?php echo admin_escape((string) $activeThemeMeta['screenshot']); ?>" alt="Theme Screenshot" style="max-width:280px;width:100%;border-radius:14px;border:1px solid var(--line);"></p>
                        <?php endif; ?>
                    </div>
                    <form method="post" action="/admin/?route=settings" style="margin-top:14px;">
                        <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                        <input type="hidden" name="settings_action" value="clear_cache">
                        <button class="btn secondary" type="submit">Clear Cache</button>
                    </form>
                </div>
            <?php elseif ($route === 'pages'): ?>
                <div class="page-header"><div><h1 class="page-title">Pages</h1><div class="page-subtitle">Manage content, SEO fields, and custom header or footer boxes.</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">
                    <?php if (!$dbAvailable): ?>
                        <div class="message error">Database connection is required for pages.</div>
                    <?php else: ?>
                        <form method="post" action="/admin/?route=pages">
                            <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                            <input type="hidden" name="page_action" value="save">
                            <input type="hidden" name="page_id" value="<?php echo admin_escape((string) ($editingPage['id'] ?? '0')); ?>">
                            <div class="form-row"><label for="slug">Slug</label><input id="slug" name="slug" type="text" value="<?php echo admin_escape((string) ($editingPage['slug'] ?? '')); ?>" required></div>
                            <div class="form-row"><label for="title">Title</label><input id="title" name="title" type="text" value="<?php echo admin_escape((string) ($editingPage['title'] ?? '')); ?>" required></div>
                            <div class="form-row"><label for="header_content">Header Content Box</label><textarea id="header_content" name="header_content"><?php echo admin_escape((string) ($editingPage['header_content'] ?? '')); ?></textarea></div>
                            <div class="form-row"><label for="meta_title">Meta Title</label><input id="meta_title" name="meta_title" type="text" value="<?php echo admin_escape((string) ($editingPage['meta_title'] ?? '')); ?>"></div>
                            <div class="form-row"><label for="meta_description">Meta Description</label><textarea id="meta_description" name="meta_description"><?php echo admin_escape((string) ($editingPage['meta_description'] ?? '')); ?></textarea></div>
                            <div class="form-row"><label for="schema_json">Schema JSON-LD</label><textarea id="schema_json" name="schema_json" placeholder='{"@context":"https://schema.org","@type":"WebPage"}'><?php echo admin_escape((string) ($editingPage['schema_json'] ?? '')); ?></textarea></div>
                            <div class="form-row"><label for="content">Content</label><textarea id="content" name="content"><?php echo admin_escape((string) ($editingPage['content'] ?? '')); ?></textarea></div>
                            <div class="form-row"><label for="footer_content">Footer Content Box</label><textarea id="footer_content" name="footer_content"><?php echo admin_escape((string) ($editingPage['footer_content'] ?? '')); ?></textarea></div>
                            <?php if ($subpagePluginOptions !== []): ?>
                                <div class="form-row">
                                    <label>Hide Plugins On This Subpage</label>
                                    <div class="card" style="display:grid;gap:10px;">
                                        <?php foreach ($subpagePluginOptions as $pluginSlug => $pluginMeta): ?>
                                            <?php
                                            $pluginBlocks = is_array($pluginMeta['blocks'] ?? null) ? $pluginMeta['blocks'] : [];
                                            $isActivePlugin = !empty($pluginMeta['active']);
                                            $isRenderingOnSubpage = $isActivePlugin && array_intersect($pluginBlocks, $homepageBlocks) !== [];
                                            ?>
                                            <label style="display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap;margin:0;">
                                                <span style="display:flex;gap:10px;align-items:center;">
                                                    <input type="checkbox" name="hidden_blocks[]" value="<?php echo admin_escape((string) $pluginSlug); ?>" <?php echo in_array((string) $pluginSlug, $editingHiddenBlocks, true) ? 'checked' : ''; ?>>
                                                    <span><?php echo admin_escape((string) ($pluginMeta['name'] ?? $pluginSlug)); ?></span>
                                                </span>
                                                <span class="stat-label" style="margin-left:auto;"><?php echo $isRenderingOnSubpage ? 'Active' : ($isActivePlugin ? 'Loaded' : 'Inactive'); ?></span>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                            <button class="btn" type="submit">Save Page</button>
                        </form>
                        <div class="grid" style="margin-top:22px;">
                            <?php foreach ($pages as $page): ?>
                                <div class="stat-card">
                                    <div class="stat-value" style="font-size:20px;"><?php echo admin_escape((string) $page['title']); ?></div>
                                    <div class="stat-label"><?php echo admin_escape((string) $page['slug']); ?></div>
                                    <p style="margin:12px 0 0;"><a href="/admin/?route=pages&page_id=<?php echo (int) $page['id']; ?>">Edit</a></p>
                                    <form method="post" action="/admin/?route=pages" style="margin-top:10px;">
                                        <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                                        <input type="hidden" name="page_action" value="delete">
                                        <input type="hidden" name="page_id" value="<?php echo (int) $page['id']; ?>">
                                        <button class="btn secondary" type="submit">Delete</button>
                                    </form>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="page-header"><div><h1 class="page-title">Dashboard</h1><div class="page-subtitle">A clean overview of themes, plugins, and your active CMS modules.</div></div></div>
                <div class="grid">
                    <div class="stat-card"><div class="stat-label">Site Title</div><div class="stat-value"><?php echo admin_escape($siteTitle); ?></div></div>
                    <div class="stat-card"><div class="stat-label">Active Theme</div><div class="stat-value"><?php echo admin_escape($activeTheme); ?></div></div>
                    <div class="stat-card"><div class="stat-label">Available Themes</div><div class="stat-value"><?php echo (string) $themeCount; ?></div></div>
                    <div class="stat-card"><div class="stat-label">Installed Plugins</div><div class="stat-value"><?php echo (string) $pluginCount; ?></div></div>
                    <div class="stat-card"><div class="stat-label">Active Plugins</div><div class="stat-value"><?php echo (string) $activePluginCount; ?></div></div>
                    <div class="stat-card"><div class="stat-label">Registered Blocks</div><div class="stat-value"><?php echo (string) count($registeredBlocks); ?></div></div>
                </div>
            <?php endif; ?>
        </main>
    </div>
<?php endif; ?>
<script>
document.querySelectorAll('.plugin-toggle-form').forEach(function (form) {
    form.addEventListener('submit', function (event) {
        event.preventDefault();
        var button = form.querySelector('.plugin-toggle-button');
        button.disabled = true;
        fetch(form.action, {
            method: 'POST',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            body: new FormData(form)
        }).then(function (response) {
            return response.json();
        }).then(function (payload) {
            if (!payload.ok) {
                alert(payload.message || 'Plugin update failed.');
                return;
            }
            var card = form.closest('.plugin-card');
            var status = card.querySelector('.plugin-status');
            var active = payload.status === 'active';
            status.textContent = active ? 'Active' : 'Inactive';
            button.textContent = active ? 'Deactivate' : 'Activate';
        }).catch(function () {
            alert('Plugin update failed.');
        }).finally(function () {
            button.disabled = false;
        });
    });
});

(function () {
    var list = document.getElementById('layout-builder');
    var orderInput = document.getElementById('layout_order');
    if (!list || !orderInput) {
        return;
    }

    var dragging = null;
    function syncOrder() {
        orderInput.value = Array.prototype.map.call(list.querySelectorAll('.layout-item'), function (item) {
            return item.getAttribute('data-block');
        }).join(',');
    }

    list.querySelectorAll('.layout-item').forEach(function (item) {
        item.addEventListener('dragstart', function () { dragging = item; });
        item.addEventListener('dragover', function (event) { event.preventDefault(); });
        item.addEventListener('drop', function (event) {
            event.preventDefault();
            if (!dragging || dragging === item) {
                return;
            }
            var rect = item.getBoundingClientRect();
            var before = event.clientY < rect.top + rect.height / 2;
            list.insertBefore(dragging, before ? item : item.nextSibling);
            syncOrder();
        });
    });
    syncOrder();
})();
</script>
</body>
</html>
