<?php
session_start();

$adminPassword = 'admin123';
$dataFile = dirname(__DIR__) . '/data/seo-pages.json';
$message = '';
$error = '';

function h($value) {
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}

function normalize_route($route) {
    $route = '/' . trim((string) $route, '/');
    return $route === '/index.php' ? '/' : $route;
}

function load_seo_pages($dataFile) {
    if (!is_file($dataFile)) {
        return [];
    }
    $data = json_decode((string) file_get_contents($dataFile), true);
    return is_array($data) ? $data : [];
}

function save_seo_pages($dataFile, array $pages) {
    ksort($pages);
    $json = json_encode($pages, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    if ($json === false) {
        return false;
    }
    return file_put_contents($dataFile, $json . PHP_EOL, LOCK_EX) !== false;
}

function empty_page($route) {
    return [
        'label' => trim($route, '/') ?: 'Home',
        'title' => '',
        'description' => '',
        'keywords' => '',
        'robots' => 'index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1',
        'author' => 'Home & Soul Mall',
        'canonical' => '',
        'alternate_hreflang' => 'en-IN',
        'theme_color' => '#000000',
        'og_type' => 'website',
        'og_site_name' => 'Home & Soul Mall',
        'og_title' => '',
        'og_description' => '',
        'og_url' => '',
        'og_image' => '',
        'og_locale' => 'en_IN',
        'twitter_card' => 'summary_large_image',
        'twitter_title' => '',
        'twitter_description' => '',
        'twitter_image' => '',
        'geo_region' => 'IN-UP',
        'geo_placename' => 'Greater Noida West',
        'schema_json' => '',
        'custom_head' => '',
    ];
}

if (isset($_GET['logout'])) {
    $_SESSION = [];
    session_destroy();
    header('Location: index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'login') {
    if (hash_equals($adminPassword, (string) ($_POST['password'] ?? ''))) {
        $_SESSION['seo_admin'] = true;
        header('Location: index.php');
        exit;
    }
    $error = 'Invalid password.';
}

$isLoggedIn = !empty($_SESSION['seo_admin']);
$pages = load_seo_pages($dataFile);

if ($isLoggedIn && $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save') {
    $route = normalize_route($_POST['route'] ?? '/');
    $schema = trim((string) ($_POST['schema_json'] ?? ''));
    if ($schema !== '') {
        json_decode($schema);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $error = 'Schema JSON is invalid: ' . json_last_error_msg();
        }
    }

    if ($error === '') {
        $pages[$route] = [
            'label' => trim((string) ($_POST['label'] ?? '')),
            'title' => trim((string) ($_POST['title'] ?? '')),
            'description' => trim((string) ($_POST['description'] ?? '')),
            'keywords' => trim((string) ($_POST['keywords'] ?? '')),
            'robots' => trim((string) ($_POST['robots'] ?? '')),
            'author' => trim((string) ($_POST['author'] ?? '')),
            'canonical' => trim((string) ($_POST['canonical'] ?? '')),
            'alternate_hreflang' => trim((string) ($_POST['alternate_hreflang'] ?? '')),
            'theme_color' => trim((string) ($_POST['theme_color'] ?? '')),
            'og_type' => trim((string) ($_POST['og_type'] ?? '')),
            'og_site_name' => trim((string) ($_POST['og_site_name'] ?? '')),
            'og_title' => trim((string) ($_POST['og_title'] ?? '')),
            'og_description' => trim((string) ($_POST['og_description'] ?? '')),
            'og_url' => trim((string) ($_POST['og_url'] ?? '')),
            'og_image' => trim((string) ($_POST['og_image'] ?? '')),
            'og_locale' => trim((string) ($_POST['og_locale'] ?? '')),
            'twitter_card' => trim((string) ($_POST['twitter_card'] ?? '')),
            'twitter_title' => trim((string) ($_POST['twitter_title'] ?? '')),
            'twitter_description' => trim((string) ($_POST['twitter_description'] ?? '')),
            'twitter_image' => trim((string) ($_POST['twitter_image'] ?? '')),
            'geo_region' => trim((string) ($_POST['geo_region'] ?? '')),
            'geo_placename' => trim((string) ($_POST['geo_placename'] ?? '')),
            'schema_json' => $schema,
            'custom_head' => trim((string) ($_POST['custom_head'] ?? '')),
        ];
        if (save_seo_pages($dataFile, $pages)) {
            $message = 'SEO data saved for ' . $route . '.';
        } else {
            $error = 'Unable to save SEO data. Check write permission on /data/seo-pages.json.';
        }
    }
}

if ($isLoggedIn && $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete') {
    $route = normalize_route($_POST['route'] ?? '/');
    if ($route === '/') {
        $error = 'Home route cannot be deleted.';
    } else {
        unset($pages[$route]);
        $message = save_seo_pages($dataFile, $pages) ? 'Deleted ' . $route . '.' : 'Unable to delete route.';
    }
}

$selectedRoute = normalize_route($_GET['route'] ?? array_key_first($pages) ?? '/');
if (!isset($pages[$selectedRoute])) {
    $pages[$selectedRoute] = empty_page($selectedRoute);
}
$page = array_merge(empty_page($selectedRoute), $pages[$selectedRoute]);
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="noindex, nofollow">
    <title>SEO Admin | Home & Soul Mall</title>
    <style>
        :root { --bg: #f5f5f2; --ink: #171717; --muted: #666; --line: #ddd8cf; --panel: #fff; --accent: #111; }
        * { box-sizing: border-box; }
        body { margin: 0; font-family: Arial, sans-serif; background: var(--bg); color: var(--ink); }
        a { color: inherit; }
        .wrap { max-width: 1320px; margin: 0 auto; padding: 28px; }
        .top { display: flex; justify-content: space-between; align-items: center; gap: 16px; margin-bottom: 22px; }
        h1 { margin: 0; font-size: 24px; font-weight: 700; }
        .layout { display: grid; grid-template-columns: 260px 1fr; gap: 20px; align-items: start; }
        .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; }
        .routes { padding: 10px; }
        .routes a { display: block; padding: 11px 12px; border-radius: 6px; text-decoration: none; color: #333; }
        .routes a.active, .routes a:hover { background: #111; color: #fff; }
        .form { padding: 22px; }
        .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
        .full { grid-column: 1 / -1; }
        label { display: block; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; margin-bottom: 7px; }
        input, textarea, select { width: 100%; border: 1px solid #cfc8bd; border-radius: 6px; padding: 11px 12px; font: inherit; background: #fff; color: #111; }
        textarea { min-height: 94px; resize: vertical; }
        textarea.code { min-height: 220px; font-family: Consolas, monospace; font-size: 13px; line-height: 1.45; }
        .actions { display: flex; justify-content: space-between; gap: 12px; margin-top: 18px; }
        button, .btn { border: 0; border-radius: 6px; background: #111; color: #fff; padding: 11px 16px; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; }
        .danger { background: #a51d1d; }
        .ghost { background: #e8e3da; color: #111; }
        .notice { padding: 12px 14px; border-radius: 6px; margin-bottom: 14px; }
        .ok { background: #e8f6ed; border: 1px solid #b8e0c5; }
        .err { background: #fdecec; border: 1px solid #efb7b7; }
        .hint { color: var(--muted); font-size: 12px; margin-top: 5px; }
        .login { max-width: 420px; margin: 12vh auto; padding: 28px; }
        @media (max-width: 900px) { .layout, .grid { grid-template-columns: 1fr; } .wrap { padding: 16px; } }
    </style>
</head>
<body>
<?php if (!$isLoggedIn): ?>
    <form class="panel login" method="post">
        <input type="hidden" name="action" value="login">
        <h1>SEO Admin</h1>
        <p class="hint">Default password: admin123</p>
        <?php if ($error): ?><div class="notice err"><?= h($error) ?></div><?php endif; ?>
        <label for="password">Password</label>
        <input id="password" type="password" name="password" autofocus>
        <div class="actions">
            <button type="submit">Login</button>
            <a class="btn ghost" href="../">Back to site</a>
        </div>
    </form>
<?php else: ?>
    <div class="wrap">
        <div class="top">
            <h1>SEO Admin</h1>
            <div>
                <a class="btn ghost" href="../" target="_blank">View Site</a>
                <a class="btn" href="?logout=1">Logout</a>
            </div>
        </div>
        <?php if ($message): ?><div class="notice ok"><?= h($message) ?></div><?php endif; ?>
        <?php if ($error): ?><div class="notice err"><?= h($error) ?></div><?php endif; ?>
        <div class="layout">
            <aside class="panel routes">
                <?php foreach ($pages as $routeName => $routeSeo): ?>
                    <a class="<?= $routeName === $selectedRoute ? 'active' : '' ?>" href="?route=<?= urlencode($routeName) ?>">
                        <?= h(($routeSeo['label'] ?? '') ?: $routeName) ?><br>
                        <small><?= h($routeName) ?></small>
                    </a>
                <?php endforeach; ?>
                <a href="?route=/new-page">+ Add route</a>
            </aside>
            <main class="panel form">
                <form method="post">
                    <input type="hidden" name="action" value="save">
                    <div class="grid">
                        <div>
                            <label>Route</label>
                            <input name="route" value="<?= h($selectedRoute) ?>" placeholder="/shop">
                            <div class="hint">Use clean route format, for example /shop or /leasing-enquiry.</div>
                        </div>
                        <div>
                            <label>Admin Label</label>
                            <input name="label" value="<?= h($page['label']) ?>">
                        </div>
                        <div class="full">
                            <label>Meta Title</label>
                            <input name="title" value="<?= h($page['title']) ?>">
                        </div>
                        <div class="full">
                            <label>Meta Description</label>
                            <textarea name="description"><?= h($page['description']) ?></textarea>
                        </div>
                        <div class="full">
                            <label>Meta Keywords</label>
                            <textarea name="keywords"><?= h($page['keywords']) ?></textarea>
                        </div>
                        <div>
                            <label>Robots</label>
                            <input name="robots" value="<?= h($page['robots']) ?>">
                        </div>
                        <div>
                            <label>Author</label>
                            <input name="author" value="<?= h($page['author']) ?>">
                        </div>
                        <div>
                            <label>Canonical Override</label>
                            <input name="canonical" value="<?= h($page['canonical']) ?>" placeholder="Leave blank for automatic URL">
                        </div>
                        <div>
                            <label>Alternate Hreflang</label>
                            <input name="alternate_hreflang" value="<?= h($page['alternate_hreflang']) ?>">
                        </div>
                        <div>
                            <label>Theme Color</label>
                            <input name="theme_color" value="<?= h($page['theme_color']) ?>">
                        </div>
                        <div>
                            <label>OG Type</label>
                            <input name="og_type" value="<?= h($page['og_type']) ?>">
                        </div>
                        <div>
                            <label>OG Site Name</label>
                            <input name="og_site_name" value="<?= h($page['og_site_name']) ?>">
                        </div>
                        <div>
                            <label>OG Locale</label>
                            <input name="og_locale" value="<?= h($page['og_locale']) ?>">
                        </div>
                        <div class="full">
                            <label>OG Title</label>
                            <input name="og_title" value="<?= h($page['og_title']) ?>" placeholder="Leave blank to use meta title">
                        </div>
                        <div class="full">
                            <label>OG Description</label>
                            <textarea name="og_description" placeholder="Leave blank to use meta description"><?= h($page['og_description']) ?></textarea>
                        </div>
                        <div class="full">
                            <label>OG URL</label>
                            <input name="og_url" value="<?= h($page['og_url']) ?>" placeholder="Leave blank to use canonical">
                        </div>
                        <div class="full">
                            <label>OG Image</label>
                            <input name="og_image" value="<?= h($page['og_image']) ?>" placeholder="Absolute URL recommended">
                        </div>
                        <div>
                            <label>Twitter Card</label>
                            <select name="twitter_card">
                                <?php foreach (['summary_large_image', 'summary'] as $card): ?>
                                    <option value="<?= h($card) ?>" <?= $page['twitter_card'] === $card ? 'selected' : '' ?>><?= h($card) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label>Geo Region</label>
                            <input name="geo_region" value="<?= h($page['geo_region']) ?>">
                        </div>
                        <div class="full">
                            <label>Twitter Title</label>
                            <input name="twitter_title" value="<?= h($page['twitter_title']) ?>" placeholder="Leave blank to use meta title">
                        </div>
                        <div class="full">
                            <label>Twitter Description</label>
                            <textarea name="twitter_description" placeholder="Leave blank to use meta description"><?= h($page['twitter_description']) ?></textarea>
                        </div>
                        <div class="full">
                            <label>Twitter Image</label>
                            <input name="twitter_image" value="<?= h($page['twitter_image']) ?>" placeholder="Leave blank to use OG image">
                        </div>
                        <div>
                            <label>Geo Placename</label>
                            <input name="geo_placename" value="<?= h($page['geo_placename']) ?>">
                        </div>
                        <div class="full">
                            <label>Schema JSON</label>
                            <textarea class="code" name="schema_json" spellcheck="false"><?= h($page['schema_json']) ?></textarea>
                            <div class="hint">Must be valid JSON. Leave blank to use the default ShoppingCenter schema.</div>
                        </div>
                        <div class="full">
                            <label>Custom Head Tags</label>
                            <textarea class="code" name="custom_head" spellcheck="false"><?= h($page['custom_head']) ?></textarea>
                            <div class="hint">Optional raw tags for anything extra, such as verification tags or additional meta tags.</div>
                        </div>
                    </div>
                    <div class="actions">
                        <button type="submit">Save SEO Data</button>
                        <a class="btn ghost" href="../<?= h(trim($selectedRoute, '/')) ?>" target="_blank">Preview Page</a>
                    </div>
                </form>
                <?php if ($selectedRoute !== '/'): ?>
                    <form method="post" onsubmit="return confirm('Delete this route SEO data?');" style="margin-top: 12px;">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="route" value="<?= h($selectedRoute) ?>">
                        <button class="danger" type="submit">Delete Route SEO</button>
                    </form>
                <?php endif; ?>
            </main>
        </div>
    </div>
<?php endif; ?>
</body>
</html>
