<?php
/**
 * CMS - Page Editor
 * Create and edit static pages
 */

require_once '../config/config.php';
requireLogin();
requireAdmin();

$pageTitle = 'Edit Page';
$success = '';
$error = '';

$db = getDB();

// Get page ID if editing
$pageId = $_GET['id'] ?? null;
$page = null;

if ($pageId) {
    $stmt = $db->prepare("SELECT * FROM cms_pages WHERE id = ?");
    $stmt->execute([$pageId]);
    $page = $stmt->fetch();
    
    if (!$page) {
        redirect('cms-pages.php');
    }
    $pageTitle = 'Edit Page: ' . $page['title'];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    try {
        $title = sanitize($_POST['title'] ?? '');
        $slug = sanitize($_POST['slug'] ?? '');
        $content = $_POST['content'] ?? ''; // Don't sanitize HTML content
        $status = sanitize($_POST['status'] ?? 'draft');
        $language = sanitize($_POST['language'] ?? 'en');
        
        // SEO fields
        $metaTitle = sanitize($_POST['meta_title'] ?? '');
        $metaDescription = sanitize($_POST['meta_description'] ?? '');
        $metaKeywords = sanitize($_POST['meta_keywords'] ?? '');
        $ogTitle = sanitize($_POST['og_title'] ?? '');
        $ogDescription = sanitize($_POST['og_description'] ?? '');
        $ogImage = sanitize($_POST['og_image'] ?? '');
        $twitterCard = sanitize($_POST['twitter_card'] ?? 'summary');
        $canonicalUrl = sanitize($_POST['canonical_url'] ?? '');
        $robots = sanitize($_POST['robots'] ?? 'index,follow');
        
        // Generate slug if empty
        if (empty($slug)) {
            $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
        }
        
        // Validate required fields
        if (empty($title) || empty($slug)) {
            throw new Exception('Title and slug are required.');
        }
        
        if ($pageId) {
            // Update existing page
            $stmt = $db->prepare("
                UPDATE cms_pages SET
                    title = ?,
                    slug = ?,
                    content = ?,
                    meta_title = ?,
                    meta_description = ?,
                    meta_keywords = ?,
                    og_title = ?,
                    og_description = ?,
                    og_image = ?,
                    twitter_card = ?,
                    canonical_url = ?,
                    robots = ?,
                    status = ?,
                    language = ?
                WHERE id = ?
            ");
            $stmt->execute([
                $title, $slug, $content,
                $metaTitle, $metaDescription, $metaKeywords,
                $ogTitle, $ogDescription, $ogImage,
                $twitterCard, $canonicalUrl, $robots,
                $status, $language, $pageId
            ]);
            
            logActivity('cms_page_updated', 'cms_pages', $pageId);
            $success = 'Page updated successfully!';
            
        } else {
            // Create new page
            $stmt = $db->prepare("
                INSERT INTO cms_pages (
                    title, slug, content,
                    meta_title, meta_description, meta_keywords,
                    og_title, og_description, og_image,
                    twitter_card, canonical_url, robots,
                    status, language, created_by
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $title, $slug, $content,
                $metaTitle, $metaDescription, $metaKeywords,
                $ogTitle, $ogDescription, $ogImage,
                $twitterCard, $canonicalUrl, $robots,
                $status, $language, $_SESSION['user_id']
            ]);
            
            $pageId = $db->lastInsertId();
            logActivity('cms_page_created', 'cms_pages', $pageId);
            $success = 'Page created successfully!';
            
            // Reload page data
            $stmt = $db->prepare("SELECT * FROM cms_pages WHERE id = ?");
            $stmt->execute([$pageId]);
            $page = $stmt->fetch();
        }
        
    } catch (Exception $e) {
        error_log("Page save error: " . $e->getMessage());
        $error = $e->getMessage();
    }
}

include '../templates/header.php';
?>

<!-- TinyMCE CDN -->
<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <div class="col-md-3 col-lg-2 px-0">
            <?php include 'sidebar.php'; ?>
        </div>
        
        <!-- Main Content -->
        <div class="col-md-9 col-lg-10">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>
                    <i class="fas fa-file-alt"></i> 
                    <?php echo $pageId ? 'Edit Page' : 'Add New Page'; ?>
                </h2>
                <a href="cms-pages.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Back to Pages
                </a>
            </div>
            
            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="fas fa-check-circle"></i> <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-circle"></i> <?php echo e($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <form method="POST" class="needs-validation" novalidate>
                <?php echo csrfField(); ?>
                
                <div class="row">
                    <!-- Main Content Column -->
                    <div class="col-lg-8">
                        <!-- Basic Information -->
                        <div class="card shadow mb-4">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0"><i class="fas fa-edit"></i> Page Content</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">Page Title *</label>
                                    <input type="text" class="form-control" name="title" 
                                           value="<?php echo e($page['title'] ?? ''); ?>" 
                                           required id="pageTitle">
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Slug (URL) *</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><?php echo SITE_URL; ?>/page/</span>
                                        <input type="text" class="form-control" name="slug" 
                                               value="<?php echo e($page['slug'] ?? ''); ?>" 
                                               required id="pageSlug">
                                    </div>
                                    <small class="text-muted">Leave empty to auto-generate from title</small>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Content</label>
                                    <textarea name="content" id="pageContent" class="form-control" rows="20"><?php echo $page['content'] ?? ''; ?></textarea>
                                </div>
                            </div>
                        </div>
                        
                        <!-- SEO Settings -->
                        <div class="card shadow mb-4">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0"><i class="fas fa-search"></i> SEO Settings</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">Meta Title</label>
                                    <input type="text" class="form-control" name="meta_title" 
                                           value="<?php echo e($page['meta_title'] ?? ''); ?>" 
                                           maxlength="60">
                                    <small class="text-muted">Recommended: 50-60 characters</small>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Meta Description</label>
                                    <textarea class="form-control" name="meta_description" 
                                              rows="3" maxlength="160"><?php echo e($page['meta_description'] ?? ''); ?></textarea>
                                    <small class="text-muted">Recommended: 150-160 characters</small>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Meta Keywords</label>
                                    <input type="text" class="form-control" name="meta_keywords" 
                                           value="<?php echo e($page['meta_keywords'] ?? ''); ?>" 
                                           placeholder="keyword1, keyword2, keyword3">
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Canonical URL</label>
                                    <input type="url" class="form-control" name="canonical_url" 
                                           value="<?php echo e($page['canonical_url'] ?? ''); ?>">
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Robots Meta Tag</label>
                                    <select class="form-select" name="robots">
                                        <option value="index,follow" <?php echo ($page['robots'] ?? 'index,follow') === 'index,follow' ? 'selected' : ''; ?>>Index, Follow</option>
                                        <option value="noindex,follow" <?php echo ($page['robots'] ?? '') === 'noindex,follow' ? 'selected' : ''; ?>>No Index, Follow</option>
                                        <option value="index,nofollow" <?php echo ($page['robots'] ?? '') === 'index,nofollow' ? 'selected' : ''; ?>>Index, No Follow</option>
                                        <option value="noindex,nofollow" <?php echo ($page['robots'] ?? '') === 'noindex,nofollow' ? 'selected' : ''; ?>>No Index, No Follow</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Open Graph / Social Media -->
                        <div class="card shadow mb-4">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0"><i class="fab fa-facebook"></i> Social Media (Open Graph)</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">OG Title</label>
                                    <input type="text" class="form-control" name="og_title" 
                                           value="<?php echo e($page['og_title'] ?? ''); ?>">
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">OG Description</label>
                                    <textarea class="form-control" name="og_description" 
                                              rows="2"><?php echo e($page['og_description'] ?? ''); ?></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">OG Image URL</label>
                                    <input type="url" class="form-control" name="og_image" 
                                           value="<?php echo e($page['og_image'] ?? ''); ?>">
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Twitter Card Type</label>
                                    <select class="form-select" name="twitter_card">
                                        <option value="summary" <?php echo ($page['twitter_card'] ?? 'summary') === 'summary' ? 'selected' : ''; ?>>Summary</option>
                                        <option value="summary_large_image" <?php echo ($page['twitter_card'] ?? '') === 'summary_large_image' ? 'selected' : ''; ?>>Summary Large Image</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Sidebar Column -->
                    <div class="col-lg-4">
                        <!-- Publish Settings -->
                        <div class="card shadow mb-4">
                            <div class="card-header bg-warning">
                                <h5 class="mb-0"><i class="fas fa-cog"></i> Publish Settings</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">Status</label>
                                    <select class="form-select" name="status" required>
                                        <option value="draft" <?php echo ($page['status'] ?? 'draft') === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                        <option value="published" <?php echo ($page['status'] ?? '') === 'published' ? 'selected' : ''; ?>>Published</option>
                                    </select>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Language</label>
                                    <select class="form-select" name="language" required>
                                        <option value="en" <?php echo ($page['language'] ?? 'en') === 'en' ? 'selected' : ''; ?>>English</option>
                                        <option value="ar" <?php echo ($page['language'] ?? '') === 'ar' ? 'selected' : ''; ?>>Arabic</option>
                                    </select>
                                </div>
                                
                                <?php if ($page): ?>
                                    <div class="mb-3">
                                        <label class="form-label">Created</label>
                                        <p class="form-control-plaintext">
                                            <?php echo date('M d, Y H:i', strtotime($page['created_at'])); ?>
                                        </p>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Last Updated</label>
                                        <p class="form-control-plaintext">
                                            <?php echo date('M d, Y H:i', strtotime($page['updated_at'])); ?>
                                        </p>
                                    </div>
                                <?php endif; ?>
                                
                                <hr>
                                
                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save"></i> <?php echo $pageId ? 'Update Page' : 'Create Page'; ?>
                                    </button>
                                    
                                    <?php if ($page && $page['status'] === 'published'): ?>
                                        <a href="../public/page.php?slug=<?php echo e($page['slug']); ?>" 
                                           class="btn btn-outline-info" target="_blank">
                                            <i class="fas fa-eye"></i> View Page
                                        </a>
                                    <?php endif; ?>
                                    
                                    <a href="cms-pages.php" class="btn btn-outline-secondary">
                                        <i class="fas fa-times"></i> Cancel
                                    </a>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Help -->
                        <div class="card shadow">
                            <div class="card-header bg-light">
                                <h5 class="mb-0"><i class="fas fa-question-circle"></i> Help</h5>
                            </div>
                            <div class="card-body">
                                <p class="small"><strong>Title:</strong> The main heading of your page.</p>
                                <p class="small"><strong>Slug:</strong> The URL-friendly version of the title.</p>
                                <p class="small"><strong>Content:</strong> The main content of your page. Use the rich text editor to format.</p>
                                <p class="small"><strong>SEO:</strong> Optimize your page for search engines.</p>
                                <p class="small mb-0"><strong>Status:</strong> Draft pages are not visible to the public.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Initialize TinyMCE
tinymce.init({
    selector: '#pageContent',
    height: 500,
    menubar: true,
    plugins: [
        'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
        'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
        'insertdatetime', 'media', 'table', 'help', 'wordcount'
    ],
    toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | code',
    content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; font-size: 14px; }'
});

// Auto-generate slug from title
document.getElementById('pageTitle').addEventListener('blur', function() {
    const slugField = document.getElementById('pageSlug');
    if (!slugField.value) {
        const slug = this.value
            .toLowerCase()
            .trim()
            .replace(/[^a-z0-9-]+/g, '-')
            .replace(/^-+|-+$/g, '');
        slugField.value = slug;
    }
});
</script>

<?php include '../templates/footer.php'; ?>
