<?php
/**
 * CMS - Pages Management
 * Manage static pages (About, Contact, Terms, Privacy, etc.)
 */

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

$pageTitle = 'Pages Management';
$success = '';
$error = '';

$db = getDB();

// Handle delete action
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    validateCSRF();
    
    try {
        $stmt = $db->prepare("DELETE FROM cms_pages WHERE id = ?");
        $stmt->execute([$_GET['id']]);
        
        logActivity('cms_page_deleted', 'cms_pages', $_GET['id']);
        $success = 'Page deleted successfully!';
    } catch (Exception $e) {
        error_log("Page deletion error: " . $e->getMessage());
        $error = 'Failed to delete page.';
    }
}

// Handle status toggle
if (isset($_GET['action']) && $_GET['action'] === 'toggle_status' && isset($_GET['id'])) {
    validateCSRF();
    
    try {
        $stmt = $db->prepare("UPDATE cms_pages SET status = IF(status = 'published', 'draft', 'published') WHERE id = ?");
        $stmt->execute([$_GET['id']]);
        
        logActivity('cms_page_status_toggled', 'cms_pages', $_GET['id']);
        $success = 'Page status updated successfully!';
    } catch (Exception $e) {
        error_log("Page status toggle error: " . $e->getMessage());
        $error = 'Failed to update page status.';
    }
}

// Get all pages
$stmt = $db->prepare("
    SELECT p.*, u.first_name, u.last_name 
    FROM cms_pages p
    LEFT JOIN users u ON p.created_by = u.id
    ORDER BY p.created_at DESC
");
$stmt->execute();
$pages = $stmt->fetchAll();

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

<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">
            <?php include 'header-bar.php'; ?>
            
            <?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; ?>
            
            <div class="card shadow">
                <div class="card-header bg-white">
                    <div class="row align-items-center">
                        <div class="col">
                            <h5 class="mb-0">All Pages</h5>
                        </div>
                        <div class="col-auto">
                            <input type="text" id="searchPages" class="form-control" placeholder="Search pages...">
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Title</th>
                                    <th>Slug</th>
                                    <th>Status</th>
                                    <th>Language</th>
                                    <th>Author</th>
                                    <th>Created</th>
                                    <th>Updated</th>
                                    <th class="text-end">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($pages)): ?>
                                    <tr>
                                        <td colspan="8" class="text-center py-4">
                                            <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                                            <p class="text-muted">No pages found. Create your first page!</p>
                                            <a href="cms-pages-edit.php" class="btn btn-primary">
                                                <i class="fas fa-plus"></i> Add New Page
                                            </a>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($pages as $page): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo e($page['title']); ?></strong>
                                                <?php if ($page['meta_title']): ?>
                                                    <br><small class="text-muted">SEO: <?php echo e($page['meta_title']); ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <code><?php echo e($page['slug']); ?></code>
                                            </td>
                                            <td>
                                                <?php if ($page['status'] === 'published'): ?>
                                                    <span class="badge bg-success">Published</span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary">Draft</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-info"><?php echo strtoupper($page['language']); ?></span>
                                            </td>
                                            <td>
                                                <?php echo e($page['first_name'] . ' ' . $page['last_name']); ?>
                                            </td>
                                            <td>
                                                <small><?php echo date('M d, Y', strtotime($page['created_at'])); ?></small>
                                            </td>
                                            <td>
                                                <small><?php echo date('M d, Y', strtotime($page['updated_at'])); ?></small>
                                            </td>
                                            <td class="text-end">
                                                <div class="btn-group btn-group-sm">
                                                    <a href="../public/page.php?slug=<?php echo e($page['slug']); ?>" 
                                                       class="btn btn-outline-info" target="_blank" 
                                                       title="View Page">
                                                        <i class="fas fa-eye"></i>
                                                    </a>
                                                    <a href="cms-pages-edit.php?id=<?php echo $page['id']; ?>" 
                                                       class="btn btn-outline-primary" 
                                                       title="Edit Page">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <a href="?action=toggle_status&id=<?php echo $page['id']; ?>&csrf_token=<?php echo $_SESSION['csrf_token']; ?>" 
                                                       class="btn btn-outline-warning" 
                                                       title="Toggle Status"
                                                       onclick="return confirm('Toggle page status?');">
                                                        <i class="fas fa-toggle-on"></i>
                                                    </a>
                                                    <a href="?action=delete&id=<?php echo $page['id']; ?>&csrf_token=<?php echo $_SESSION['csrf_token']; ?>" 
                                                       class="btn btn-outline-danger" 
                                                       title="Delete Page"
                                                       onclick="return confirm('Are you sure you want to delete this page?');">
                                                        <i class="fas fa-trash"></i>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Quick Stats -->
            <div class="row mt-4">
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h3 class="text-primary"><?php echo count($pages); ?></h3>
                            <p class="text-muted mb-0">Total Pages</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h3 class="text-success">
                                <?php echo count(array_filter($pages, fn($p) => $p['status'] === 'published')); ?>
                            </h3>
                            <p class="text-muted mb-0">Published</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h3 class="text-secondary">
                                <?php echo count(array_filter($pages, fn($p) => $p['status'] === 'draft')); ?>
                            </h3>
                            <p class="text-muted mb-0">Drafts</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h3 class="text-info">
                                <?php echo count(array_unique(array_column($pages, 'language'))); ?>
                            </h3>
                            <p class="text-muted mb-0">Languages</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Search functionality
document.getElementById('searchPages').addEventListener('keyup', function() {
    const searchTerm = this.value.toLowerCase();
    const rows = document.querySelectorAll('tbody tr');
    
    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchTerm) ? '' : 'none';
    });
});
</script>

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