<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
define('BASE_URL', '');

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_role('admin');

$errors = [];
$input  = [
    'title' => '', 'slug' => '', 'overview' => '', 'description' => '', 'status' => 'draft',
    // SEO fields
    'meta_title' => '', 'meta_description' => '', 'meta_keywords' => '',
    'canonical_url' => '', 'feature_image' => '', 'feature_image_alt' => '',
    'og_title' => '', 'og_description' => '', 'og_image' => '', 'og_type' => 'article',
    'twitter_card' => 'summary_large_image', 'twitter_title' => '', 'twitter_description' => '',
    'twitter_image' => '', 'twitter_site' => '',
    'schema_markup' => '', 'ai_summary' => '', 'faqs' => '[]',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_page'])) {
    // Core fields
    foreach (['title','slug','overview','description','status'] as $f) {
        $input[$f] = $f === 'description' ? ($_POST[$f] ?? '') : trim($_POST[$f] ?? '');
    }
    $input['status'] = in_array($input['status'], ['draft','published','archived']) ? $input['status'] : 'draft';

    // SEO fields — sanitize all
    $seoFields = [
        'meta_title','meta_description','meta_keywords','canonical_url',
        'feature_image','feature_image_alt','og_title','og_description','og_image','og_type',
        'twitter_card','twitter_title','twitter_description','twitter_image','twitter_site',
        'schema_markup','ai_summary','faqs',
    ];
    foreach ($seoFields as $f) {
        $input[$f] = trim($_POST[$f] ?? '');
    }
    // Validate twitter_card & og_type
    if (!in_array($input['twitter_card'], ['summary','summary_large_image','app'])) $input['twitter_card'] = 'summary_large_image';
    if (!in_array($input['og_type'], ['article','website','blog','profile']))        $input['og_type'] = 'article';

    // Validate faqs JSON
    $decodedFaqs = json_decode($input['faqs'], true);
    if (!is_array($decodedFaqs)) $input['faqs'] = '[]';

    // Validations
    if (!$input['title']) $errors['title'] = 'Title is required.';
    if (!$input['slug'])  $errors['slug']  = 'Slug is required.';
    elseif (!preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $input['slug']))
        $errors['slug'] = 'Slug must contain only lowercase letters, numbers, and hyphens.';

    if (!$errors) {
        try {
            $chk = $pdo->prepare("SELECT id FROM pages WHERE slug = ?");
            $chk->execute([$input['slug']]);
            if ($chk->fetch()) {
                $errors['slug'] = 'This slug is already taken by another page.';
            } else {
                $stmt = $pdo->prepare("INSERT INTO pages
                    (title, slug, overview, description, status,
                     meta_title, meta_description, meta_keywords, canonical_url,
                     feature_image, feature_image_alt,
                     og_title, og_description, og_image, og_type,
                     twitter_card, twitter_title, twitter_description, twitter_image, twitter_site,
                     schema_markup, ai_summary, faqs)
                    VALUES (?,?,?,?,?, ?,?,?,?, ?,?, ?,?,?,?, ?,?,?,?,?, ?,?,?)");
                $stmt->execute([
                    $input['title'], $input['slug'], $input['overview'],
                    $input['description'], $input['status'],
                    $input['meta_title'], $input['meta_description'], $input['meta_keywords'],
                    $input['canonical_url'], $input['feature_image'], $input['feature_image_alt'],
                    $input['og_title'], $input['og_description'], $input['og_image'], $input['og_type'],
                    $input['twitter_card'], $input['twitter_title'], $input['twitter_description'],
                    $input['twitter_image'], $input['twitter_site'],
                    $input['schema_markup'], $input['ai_summary'], $input['faqs'],
                ]);
                header('Location: pages.php?created=1');
                exit;
            }
        } catch (PDOException $e) {
            $errors['db'] = 'Database error: ' . $e->getMessage();
        }
    }
}

$user_name = $_SESSION['username'] ?? 'Admin';
$user_role = $_SESSION['role'] ?? 'admin';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Page — RSIS Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.3/tinymce.min.js" referrerpolicy="origin"></script>
    <style>
        body { font-family: 'Roboto', sans-serif; margin: 0; height: 100vh; overflow: hidden; }
        body.dark { background-color: #1a202c; color: #e2e8f0; }
        .sidebar { width:250px; background:#2d3748; color:white; transition:all .3s; height:100%; position:fixed; top:0; left:0; z-index:10; overflow-y:auto; }
        .sidebar.collapsed { width:70px; }
        .sidebar.collapsed .sidebar-title { display:none; }
        .content { margin-left:250px; transition:margin-left .3s; height:100vh; overflow-y:auto; }
        .content.collapsed-sidebar { margin-left:70px; }
        .nav-item { padding:10px 12px; cursor:pointer; transition:background .2s; display:flex; align-items:center; }
        .nav-item:hover { background:#4a5568; }
        .nav-item.active { background:#4a5568; border-left:4px solid #4299e1; }
        body.dark .bg-white { background-color:#2d3748; }
        body.dark input, body.dark select, body.dark textarea { background-color:#374151; color:#e5e7eb; border-color:#4b5563; }
        @media(max-width:768px){ .sidebar{transform:translateX(-250px);} .sidebar.mobile-open{transform:translateX(0);} .content{margin-left:0;} }
        .form-input { width:100%; border:1px solid #d1d5db; border-radius:.5rem; padding:.6rem .875rem; font-size:.875rem; color:#374151; transition:border-color .15s,box-shadow .15s; outline:none; }
        .form-input:focus { border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.15); }
        .form-input.has-error { border-color:#ef4444; }
        .error-msg { color:#ef4444; font-size:.75rem; margin-top:4px; display:flex; align-items:center; gap:4px; }
    </style>
</head>
<body class="bg-gray-100">

    <button onclick="toggleMobileSidebar()" class="fixed top-3 left-3 z-20 bg-gray-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>
    <?php include __DIR__ . '/include/sidebar.php'; ?>

    <div class="content" id="content">
        <!-- Topbar -->
        <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between sticky top-0 z-10 shadow-sm">
            <div class="flex items-center gap-3">
                <button onclick="toggleSidebar()" class="text-gray-500 hover:text-gray-700 hidden md:block">
                    <i class="fas fa-bars text-lg"></i>
                </button>
                <div class="flex items-center gap-2 text-sm text-gray-500">
                    <a href="pages.php" class="hover:text-blue-600 flex items-center gap-1"><i class="fas fa-file-alt"></i> Pages</a>
                    <i class="fas fa-chevron-right text-xs text-gray-400"></i>
                    <span class="text-gray-800 font-medium">Create New Page</span>
                </div>
            </div>
            <div class="flex items-center gap-3">
                <button id="darkModeToggle" class="text-gray-500 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
                    <i class="fas fa-moon"></i>
                </button>
                <a href="pages.php" class="border border-gray-300 hover:bg-gray-50 text-gray-600 px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-medium">
                    <i class="fas fa-arrow-left"></i> Back to Pages
                </a>
            </div>
        </div>

        <main class="p-6">
            <div class="mb-6">
                <h1 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
                    <i class="fas fa-plus-circle text-blue-600"></i> Create New Page
                </h1>
                <p class="text-gray-500 text-sm mt-1">Fill in the details below to add a new page</p>
            </div>

            <?php if (!empty($errors['db'])): ?>
            <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-5 rounded-lg flex items-center gap-2">
                <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($errors['db']) ?>
            </div>
            <?php endif; ?>

            <form method="POST" id="pageForm">
            <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">

                <!-- LEFT (2/3) -->
                <div class="xl:col-span-2 space-y-5">

                    <!-- Page Details -->
                    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                        <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
                            <i class="fas fa-info-circle text-blue-600"></i>
                            <h2 class="font-semibold text-gray-700">Page Details</h2>
                        </div>
                        <div class="p-5 space-y-4">
                            <!-- Title -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1.5">Title <span class="text-red-500">*</span></label>
                                <input type="text" name="title" id="titleInput"
                                    value="<?= htmlspecialchars($input['title']) ?>"
                                    class="form-input <?= isset($errors['title']) ? 'has-error' : '' ?>"
                                    placeholder="Enter page title" autofocus>
                                <?php if (isset($errors['title'])): ?><div class="error-msg"><i class="fas fa-exclamation-circle"></i><?= $errors['title'] ?></div><?php endif; ?>
                            </div>
                            <!-- Slug -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1.5">Slug <span class="text-red-500">*</span></label>
                                <div class="flex items-center">
                                    <span class="text-gray-400 text-sm font-mono bg-gray-100 border border-gray-300 px-3 py-2 rounded-l-lg border-r-0 whitespace-nowrap">communeglobal.com/</span>
                                    <input type="text" name="slug" id="slugInput"
                                        value="<?= htmlspecialchars($input['slug']) ?>"
                                        class="form-input rounded-l-none <?= isset($errors['slug']) ? 'has-error' : '' ?>"
                                        placeholder="page-slug">
                                </div>
                                <?php if (isset($errors['slug'])): ?><div class="error-msg"><i class="fas fa-exclamation-circle"></i><?= $errors['slug'] ?></div><?php endif; ?>
                                <p class="text-xs text-gray-400 mt-1">Auto-generated from title.</p>
                            </div>
                            <!-- Overview -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1.5">Overview <span class="text-gray-400 font-normal">(short summary)</span></label>
                                <textarea name="overview" rows="3" class="form-input resize-none"
                                    placeholder="Brief description of this page…"><?= htmlspecialchars($input['overview']) ?></textarea>
                            </div>
                        </div>
                    </div>

                    <!-- Rich Text Editor -->
                    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                        <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
                            <i class="fas fa-edit text-blue-600"></i>
                            <h2 class="font-semibold text-gray-700">Page Content</h2>
                            <span class="text-xs text-gray-400 ml-auto">Rich text editor</span>
                        </div>
                        <div class="p-5">
                            <textarea name="description" id="descriptionEditor"><?= htmlspecialchars($input['description']) ?></textarea>
                        </div>
                    </div>

                    <!-- ▼ SEO FIELDS (shared partial) -->
                    <?php include __DIR__ . '/include/seo_fields.php'; ?>
                    <?php include __DIR__ . '/include/seo_analysis.php'; ?>

                </div>

                <!-- RIGHT (1/3) -->
                <div class="space-y-5">

                    <!-- Publish -->
                    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                        <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
                            <i class="fas fa-paper-plane text-blue-600"></i>
                            <h2 class="font-semibold text-gray-700">Publish</h2>
                        </div>
                        <div class="p-5 space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1.5">Status</label>
                                <select name="status" class="form-input">
                                    <option value="draft"     <?= $input['status']==='draft'     ?'selected':'' ?>>📝 Draft</option>
                                    <option value="published" <?= $input['status']==='published' ?'selected':'' ?>>✅ Published</option>
                                    <option value="archived"  <?= $input['status']==='archived'  ?'selected':'' ?>>📦 Archived</option>
                                </select>
                            </div>
                            <div class="space-y-2">
                                <button type="submit" name="save_page"
                                    class="w-full bg-blue-600 hover:bg-blue-700 text-white py-2.5 rounded-lg font-semibold flex items-center justify-center gap-2 shadow transition">
                                    <i class="fas fa-save"></i> Save Page
                                </button>
                                <a href="pages.php" class="w-full block text-center border border-gray-300 hover:bg-gray-50 text-gray-600 py-2.5 rounded-lg text-sm font-medium">Cancel</a>
                            </div>
                        </div>
                    </div>

                    <!-- URL Preview -->
                    <div class="bg-blue-50 border border-blue-200 rounded-xl p-4">
                        <div class="text-xs font-semibold text-blue-700 uppercase tracking-wide mb-2"><i class="fas fa-link mr-1"></i>URL Preview</div>
                        <code class="text-blue-700 text-xs break-all">communeglobal.com/<span id="slugPreview" class="font-semibold"><?= htmlspecialchars($input['slug'] ?: 'page-slug') ?></span></code>
                    </div>

                    <!-- SEO Score card -->
                    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                        <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
                            <i class="fas fa-chart-pie text-green-600"></i>
                            <h2 class="font-semibold text-gray-700">SEO Readiness</h2>
                        </div>
                        <div class="p-5">
                            <div class="text-3xl font-bold text-center mb-1" id="seoScore">—</div>
                            <div class="text-xs text-gray-500 text-center mb-3">/ 100</div>
                            <div class="h-2 bg-gray-200 rounded-full overflow-hidden">
                                <div id="seoScoreBar" class="h-full bg-green-500 rounded-full transition-all" style="width:0%"></div>
                            </div>
                            <ul class="mt-3 space-y-1.5 text-xs" id="seoChecklist"></ul>
                        </div>
                    </div>

                    <!-- Tips -->
                    <div class="bg-gray-50 border border-gray-200 rounded-xl p-4">
                        <div class="text-xs font-semibold text-gray-600 uppercase tracking-wide mb-3"><i class="fas fa-lightbulb mr-1 text-yellow-500"></i>Tips</div>
                        <ul class="text-xs text-gray-500 space-y-2">
                            <li class="flex items-start gap-2"><i class="fas fa-dot-circle text-blue-400 mt-0.5"></i>Slug auto-generates from title</li>
                            <li class="flex items-start gap-2"><i class="fas fa-dot-circle text-blue-400 mt-0.5"></i>Fill SEO panel for Google visibility</li>
                            <li class="flex items-start gap-2"><i class="fas fa-dot-circle text-blue-400 mt-0.5"></i>Add FAQs to boost "People Also Ask"</li>
                            <li class="flex items-start gap-2"><i class="fas fa-dot-circle text-blue-400 mt-0.5"></i>AI Summary helps Perplexity/ChatGPT cite you</li>
                        </ul>
                    </div>
                </div>
            </div>
            </form>
        </main>
    </div>

<script>
tinymce.init({
    selector: '#descriptionEditor', height: 380, skin: 'oxide',
    plugins: ['advlist','autolink','lists','link','image','charmap','preview','anchor','searchreplace','visualblocks','code','fullscreen','insertdatetime','media','table','help','wordcount'],
    toolbar: 'undo redo | blocks | bold italic underline | forecolor backcolor | alignleft aligncenter alignright | bullist numlist | link image table | code fullscreen',
    menubar: 'file edit view insert format tools table', branding: false, promotion: false,
    setup: function(ed){ ed.on('change', function(){ ed.save(); }); }
});

// Auto-slug
const titleInput = document.getElementById('titleInput');
const slugInput  = document.getElementById('slugInput');
const slugPreview = document.getElementById('slugPreview');
let slugTouched = false;
function toSlug(s){ return s.toLowerCase().replace(/[^\w\s-]/g,'').replace(/[\s_]+/g,'-').replace(/^-+|-+$/g,''); }
titleInput.addEventListener('input', function() {
    if (!slugTouched) { const s=toSlug(this.value); slugInput.value=s; slugPreview.textContent=s||'page-slug'; }
});
slugInput.addEventListener('input', function(){ slugTouched=true; slugPreview.textContent=this.value||'page-slug'; });

// SEO Score
function calcSeoScore() {
    const checks = [
        { label: 'Meta Title',        done: !!document.getElementById('metaTitleInput')?.value?.trim() },
        { label: 'Meta Description',  done: !!document.getElementById('metaDescInput')?.value?.trim() },
        { label: 'Meta Keywords',     done: !!document.getElementById('metaKwInput')?.value?.trim() },
        { label: 'Feature Image',     done: !!document.getElementById('featureImageInput')?.value?.trim() },
        { label: 'OG Title',          done: !!document.getElementById('ogTitleInput')?.value?.trim() },
        { label: 'OG Description',    done: !!document.getElementById('ogDescInput')?.value?.trim() },
        { label: 'Twitter Title',     done: !!document.getElementById('twTitleInput')?.value?.trim() },
        { label: 'Schema Markup',     done: !!document.getElementById('schemaEditor')?.value?.trim() },
        { label: 'AI Summary',        done: !!document.getElementById('aiSummaryInput')?.value?.trim() },
        { label: 'FAQs Added',        done: document.querySelectorAll('.faq-q').length > 0 && !!document.querySelector('.faq-q')?.value?.trim() },
    ];
    const score = Math.round((checks.filter(c=>c.done).length / checks.length) * 100);
    const el = document.getElementById('seoScore');
    const bar = document.getElementById('seoScoreBar');
    const list = document.getElementById('seoChecklist');
    if (el) el.textContent = score;
    if (bar) { bar.style.width=score+'%'; bar.className='h-full rounded-full transition-all '+(score>=80?'bg-green-500':score>=50?'bg-yellow-500':'bg-red-500'); }
    if (list) {
        list.innerHTML = checks.map(c=>`<li class="flex items-center gap-1.5 ${c.done?'text-green-600':'text-gray-400'}">
            <i class="fas ${c.done?'fa-check-circle':'fa-circle'} text-xs"></i>${c.label}
        </li>`).join('');
    }
}
setInterval(calcSeoScore, 2000);
calcSeoScore();

// Sidebar
function toggleMobileSidebar(){ document.getElementById('sidebar').classList.toggle('mobile-open'); }
let sidebarCollapsed=false;
function toggleSidebar(){
    sidebarCollapsed=!sidebarCollapsed;
    document.getElementById('sidebar').classList.toggle('collapsed',sidebarCollapsed);
    document.getElementById('content').classList.toggle('collapsed-sidebar',sidebarCollapsed);
}
document.getElementById('darkModeToggle').addEventListener('click', function(){
    document.body.classList.toggle('dark');
    this.querySelector('i').classList.toggle('fa-moon');
    this.querySelector('i').classList.toggle('fa-sun');
    localStorage.setItem('darkMode', document.body.classList.contains('dark')?'enabled':'disabled');
});
if(localStorage.getItem('darkMode')==='enabled'){
    document.body.classList.add('dark');
    document.getElementById('darkModeToggle').querySelector('i').classList.replace('fa-moon','fa-sun');
}
</script>
</body>
</html>