<?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'];
$pluginRegistry = is_array($state['pluginRegistry'] ?? null) ? $state['pluginRegistry'] : [];
$homepageBlocks = is_array($config['homepage_blocks'] ?? null) ? $config['homepage_blocks'] : [];
$subpagePluginOptions = $pluginRegistry;
$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 {
        $pageAction = strtolower(trim((string) ($_POST['page_action'] ?? 'save')));
        if ($pageAction === 'delete') {
            $pageId = (int) ($_POST['page_id'] ?? 0);
            if ($pageId < 1 || !cms_delete_page_wp($pageId)) {
                $errors[] = 'Page could not be deleted.';
            } else {
                $notice = 'Page deleted.';
            }
        } else {
            $payload = [
                'id' => (int) ($_POST['page_id'] ?? 0),
                'title' => (string) ($_POST['title'] ?? ''),
                'slug' => (string) ($_POST['slug'] ?? ''),
                'content' => (string) ($_POST['content'] ?? ''),
                'status' => (string) ($_POST['status'] ?? 'publish'),
                '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) $payload['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_wp($payload)) {
                $errors[] = 'Page could not be saved.';
            } elseif ($errors === []) {
                $notice = 'Page saved.';
            }
        }
    }
}

$pages = cms_get_pages_wp();
$editingPageId = (int) ($_GET['page_id'] ?? 0);
$editingPage = $editingPageId > 0 ? cms_get_page_by_id_wp($editingPageId) : null;
$editingHiddenBlocks = cms_normalize_page_hidden_blocks($editingPage['hidden_blocks_json'] ?? []);
$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); ?> Pages</title>
    <?php echo admin_shared_styles(); ?>
</head>
<body>
<div class="app">
    <?php admin_render_sidebar('pages'); ?>
    <main class="content">
        <div class="page-header"><div><h1 class="page-title">Pages</h1><div class="page-subtitle">Create, edit, and optimize pages with a mobile-friendly content workflow.</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/pages.php<?php echo $editingPage ? '?page_id=' . (int) $editingPage['id'] : ''; ?>">
                <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="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="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="status">Status</label>
                    <select id="status" name="status">
                        <option value="publish" <?php echo (($editingPage['status'] ?? 'publish') === 'publish') ? 'selected' : ''; ?>>Publish</option>
                        <option value="draft" <?php echo (($editingPage['status'] ?? '') === 'draft') ? 'selected' : ''; ?>>Draft</option>
                    </select>
                </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>

        <div class="panel">
            <div class="grid">
                <?php foreach ($pages as $page): ?>
                    <div class="card">
                        <h3 style="margin-top:0;"><?php echo admin_escape((string) $page['title']); ?></h3>
                        <p style="color:#746655;"><?php echo admin_escape((string) $page['slug']); ?> | <?php echo admin_escape((string) $page['status']); ?></p>
                        <p><a href="/admin/pages.php?page_id=<?php echo (int) $page['id']; ?>">Edit</a></p>
                        <form method="post" action="/admin/pages.php" style="margin-top:12px;">
                            <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>
        </div>
    </main>
</div>
</body>
</html>
