<?php
define('SECURE_ACCESS', true);

$pageTitle = "CMS Pages Manager";
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

requireAdmin();

$currentUser = getCurrentUser();

$error = '';
$success = '';

// Handle actions (list, add, edit, delete)
$action = $_GET['action'] ?? 'list';
$editPage = null;

if ($action === 'edit' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = $pdo->prepare("SELECT * FROM cms_pages WHERE id = ?");
    $stmt->execute([$id]);
    $editPage = $stmt->fetch();
    if (!$editPage) {
        $_SESSION['flash_error'] = "Page not found.";
        header("Location: cms");
        exit();
    }
}

// Handle Form Submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = "Security check failed (CSRF). Please try again.";
    } else {
        $form_action = $_POST['form_action'] ?? '';
        
        if ($form_action === 'save') {
            $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
            $title = trim($_POST['title'] ?? '');
            $slug = trim(strtolower($_POST['slug'] ?? ''));
            $content = trim($_POST['content'] ?? '');
            
            // Clean slug (letters, numbers, hyphens only)
            $slug = preg_replace('/[^a-z0-9\-]/', '', $slug);
            
            if (empty($title) || empty($slug) || empty($content)) {
                $error = "All fields are required.";
            } else {
                try {
                    if ($id > 0) {
                        // Check if slug is taken by another page
                        $stmt = $pdo->prepare("SELECT COUNT(*) FROM cms_pages WHERE slug = ? AND id != ?");
                        $stmt->execute([$slug, $id]);
                        if ($stmt->fetchColumn() > 0) {
                            $error = "Slug is already taken.";
                        } else {
                            // Update
                            $stmt = $pdo->prepare("UPDATE cms_pages SET title = ?, slug = ?, content = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                            $stmt->execute([$title, $slug, $content, $id]);
                            $_SESSION['flash_success'] = "Page updated successfully!";
                            header("Location: cms");
                            exit();
                        }
                    } else {
                        // Check if slug is taken
                        $stmt = $pdo->prepare("SELECT COUNT(*) FROM cms_pages WHERE slug = ?");
                        $stmt->execute([$slug]);
                        if ($stmt->fetchColumn() > 0) {
                            $error = "Slug is already taken.";
                        } else {
                            // Insert new page
                            $stmt = $pdo->prepare("INSERT INTO cms_pages (title, slug, content) VALUES (?, ?, ?)");
                            $stmt->execute([$title, $slug, $content]);
                            $_SESSION['flash_success'] = "Page created successfully!";
                            header("Location: cms");
                            exit();
                        }
                    }
                } catch (PDOException $e) {
                    $error = "Database error: " . $e->getMessage();
                }
            }
        }
    }
}

// Handle Delete Action
if ($action === 'delete' && isset($_GET['id'])) {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
    } else {
        $id = (int)$_GET['id'];
        try {
            // Retrieve page details
            $stmt = $pdo->prepare("SELECT slug FROM cms_pages WHERE id = ?");
            $stmt->execute([$id]);
            $delPageSlug = $stmt->fetchColumn();
            
            if ($delPageSlug === 'privacy' || $delPageSlug === 'terms') {
                $_SESSION['flash_error'] = "System page cannot be deleted.";
            } else {
                $stmt = $pdo->prepare("DELETE FROM cms_pages WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_success'] = "Page deleted successfully!";
            }
        } catch (PDOException $e) {
            $_SESSION['flash_error'] = "Failed to delete page: " . $e->getMessage();
        }
    }
    header("Location: cms");
    exit();
}

// Fetch all pages
try {
    $pages = $pdo->query("SELECT * FROM cms_pages ORDER BY slug ASC")->fetchAll();
} catch (PDOException $e) {
    $pages = [];
    $error = "Failed to load pages list: " . $e->getMessage();
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="container-fluid px-md-5 py-4">
    <!-- Header -->
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
        <div>
            <h1 class="h2 fw-bold text-dark mb-1"><i class="bi bi-file-earmark-richtext text-primary me-2"></i>CMS Pages Manager</h1>
            <p class="text-secondary mb-0">Create and modify dynamic custom pages and standard system policies.</p>
        </div>
        <?php if ($action === 'list'): ?>
            <div>
                <a href="cms?action=add" class="btn btn-primary px-4 py-2.5 fw-bold shadow-sm">
                    <i class="bi bi-file-earmark-plus me-1"></i> Create Custom Page
                </a>
            </div>
        <?php else: ?>
            <div>
                <a href="cms" class="btn btn-outline-secondary px-4 py-2.5 fw-bold">
                    <i class="bi bi-arrow-left me-1"></i> Back to Pages List
                </a>
            </div>
        <?php endif; ?>
    </div>

    <!-- Error/Success Alerts -->
    <?php if (!empty($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm mb-4" role="alert">
            <i class="bi bi-x-circle-fill me-2"></i><?php echo htmlspecialchars($error); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if ($action === 'list'): ?>
        <!-- Pages List Table -->
        <div class="card border-0 shadow-sm rounded-3">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0" style="font-size: 0.9rem;">
                        <thead class="table-light text-secondary font-monospace" style="font-size: 0.78rem;">
                            <tr>
                                <th class="ps-4">Page Title</th>
                                <th>URL Slug</th>
                                <th>Preview Link</th>
                                <th>Last Updated</th>
                                <th class="text-end pe-4">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($pages)): ?>
                                <tr>
                                    <td colspan="5" class="text-center py-5 text-muted">
                                        <i class="bi bi-file-earmark-lock fs-2 mb-2"></i>
                                        <p class="mb-0">No CMS pages configured in the database.</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($pages as $p): ?>
                                    <tr>
                                        <td class="ps-4">
                                            <span class="fw-bold text-dark"><?php echo htmlspecialchars($p['title']); ?></span>
                                            <?php if ($p['slug'] === 'privacy' || $p['slug'] === 'terms'): ?>
                                                <span class="badge bg-secondary bg-opacity-10 text-secondary ms-1">System Policy</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <code class="text-secondary bg-light px-2 py-1 rounded small">/<?php echo htmlspecialchars($p['slug']); ?></code>
                                        </td>
                                        <td>
                                            <?php if ($p['slug'] === 'privacy'): ?>
                                                <a href="../privacy" target="_blank" class="text-decoration-none small text-primary"><i class="bi bi-box-arrow-up-right me-1"></i>privacy.php</a>
                                            <?php elseif ($p['slug'] === 'terms'): ?>
                                                <a href="../terms" target="_blank" class="text-decoration-none small text-primary"><i class="bi bi-box-arrow-up-right me-1"></i>terms.php</a>
                                            <?php else: ?>
                                                <a href="../page?slug=<?php echo htmlspecialchars($p['slug']); ?>" target="_blank" class="text-decoration-none small text-primary"><i class="bi bi-box-arrow-up-right me-1"></i>page?slug=<?php echo htmlspecialchars($p['slug']); ?></a>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-secondary small"><?php echo date('M d, Y H:i', strtotime($p['updated_at'])); ?></td>
                                        <td class="text-end pe-4">
                                            <a href="cms?action=edit&id=<?php echo $p['id']; ?>" class="btn btn-sm btn-outline-primary me-1 fw-bold">
                                                <i class="bi bi-pencil me-1"></i> Edit
                                            </a>
                                            <?php if ($p['slug'] !== 'privacy' && $p['slug'] !== 'terms'): ?>
                                                <a href="cms?action=delete&id=<?php echo $p['id']; ?>&csrf_token=<?php echo getCSRFToken(); ?>" 
                                                   class="btn btn-sm btn-outline-danger fw-bold"
                                                   onclick="return confirm('Are you sure you want to delete this custom page?');">
                                                    <i class="bi bi-trash"></i>
                                                </a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php elseif ($action === 'add' || $action === 'edit'): ?>
        <!-- Add / Edit Page Form -->
        <div class="card border-0 shadow-sm rounded-3">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold">
                    <?php echo $action === 'edit' ? 'Edit Page Details' : 'Create Custom CMS Page'; ?>
                </h5>
            </div>
            <div class="card-body p-4">
                <form method="POST" action="cms?action=<?php echo $action; ?><?php echo $editPage ? '&id='.$editPage['id'] : ''; ?>">
                    <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                    <input type="hidden" name="form_action" value="save">
                    <?php if ($editPage): ?>
                        <input type="hidden" name="id" value="<?php echo $editPage['id']; ?>">
                    <?php endif; ?>

                    <div class="row g-3">
                        <div class="col-12 col-md-6">
                            <label for="title" class="form-label fw-semibold text-dark">Page Title *</label>
                            <input type="text" class="form-control py-2" id="title" name="title" required placeholder="Ex: About Our Team" value="<?php echo htmlspecialchars($editPage['title'] ?? ''); ?>">
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="slug" class="form-label fw-semibold text-dark">URL Slug *</label>
                            <input type="text" class="form-control py-2" id="slug" name="slug" required placeholder="Ex: about-us" value="<?php echo htmlspecialchars($editPage['slug'] ?? ''); ?>" <?php echo ($editPage && ($editPage['slug'] === 'privacy' || $editPage['slug'] === 'terms')) ? 'readonly' : ''; ?>>
                            <div class="form-text small">Only lowercase letters, numbers, and hyphens. Space will be slugified automatically.</div>
                        </div>
                        <div class="col-12">
                            <label for="content" class="form-label fw-semibold text-dark">HTML Content *</label>
                            <textarea class="form-control font-monospace" id="content" name="content" rows="16" required placeholder="<h3>Heading</h3><p>Enter HTML or plain text content here...</p>"><?php echo htmlspecialchars($editPage['content'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="mt-4 pt-3 border-top d-flex gap-2">
                        <button type="submit" class="btn btn-primary px-4 py-2.5 fw-bold shadow-sm">
                            <i class="bi bi-cloud-arrow-up me-1"></i> Save CMS Page
                        </button>
                        <a href="cms" class="btn btn-outline-secondary px-4 py-2.5 fw-bold">Cancel</a>
                    </div>
                </form>
            </div>
        </div>

        <script>
            // Automatic dynamic slugifier
            const titleInput = document.getElementById('title');
            const slugInput = document.getElementById('slug');
            
            if (titleInput && slugInput && !slugInput.readOnly) {
                titleInput.addEventListener('input', function() {
                    const titleVal = titleInput.value;
                    slugInput.value = titleVal
                        .toLowerCase()
                        .replace(/[^a-z0-9\s-]/g, '') // remove special characters
                        .trim()
                        .replace(/\s+/g, '-'); // replace spaces with hyphens
                });
            }
        </script>
    <?php endif; ?>
</div>

<?php
require_once __DIR__ . '/../../includes/footer.php';
?>
