<?php
/**
 * Admin Pages Management (CMS)
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Pages';

// Handle delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM pages WHERE id = ?");
        $stmt->execute([$id]);
        set_flash_message('Page deleted successfully!', 'success');
    } catch (PDOException $e) {
        set_flash_message('Failed to delete page.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Handle add/edit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        set_flash_message('Invalid request.', 'error');
    } else {
        $id = (int)($_POST['id'] ?? 0);
        $title = sanitize($_POST['title'] ?? '');
        $slug = slugify($_POST['slug'] ?? $title);
        $content = $_POST['content'] ?? '';
        $excerpt = sanitize($_POST['excerpt'] ?? '');
        $meta_title = sanitize($_POST['meta_title'] ?? '');
        $meta_description = sanitize($_POST['meta_description'] ?? '');
        $status = sanitize($_POST['status'] ?? 'draft');
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        if (empty($title)) {
            set_flash_message('Page title is required.', 'error');
        } else {
            try {
                if ($id) {
                    // Update
                    $stmt = $pdo->prepare("UPDATE pages SET title = ?, slug = ?, content = ?, excerpt = ?, meta_title = ?, meta_description = ?, status = ?, is_active = ?, updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$title, $slug, $content, $excerpt, $meta_title, $meta_description, $status, $is_active, $id]);
                    set_flash_message('Page updated successfully!', 'success');
                } else {
                    // Insert
                    $stmt = $pdo->prepare("INSERT INTO pages (title, slug, content, excerpt, meta_title, meta_description, status, is_active, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
                    $stmt->execute([$title, $slug, $content, $excerpt, $meta_title, $meta_description, $status, $is_active]);
                    set_flash_message('Page created successfully!', 'success');
                }
            } catch (PDOException $e) {
                if ($e->getCode() == 23000) {
                    set_flash_message('Page slug already exists.', 'error');
                } else {
                    set_flash_message('Failed to save page.', 'error');
                }
            }
        }
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Get pages
$pages = get_all_pages();

// Get page for edit
$edit_page = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM pages WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_page = $stmt->fetch();
}

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

<div class="admin-content">
    <div class="admin-header d-flex justify-content-between align-items-center">
        <h1><i class="fas fa-file-alt me-2"></i>Pages</h1>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#pageModal">
            <i class="fas fa-plus me-2"></i>Add Page
        </button>
    </div>
    
    <!-- Pages Table -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Slug</th>
                            <th>Status</th>
                            <th>Last Updated</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($pages as $page): ?>
                        <tr>
                            <td>
                                <strong><?php echo sanitize($page['title']); ?></strong>
                                <?php if ($page['excerpt']): ?>
                                <small class="d-block text-muted"><?php echo truncate($page['excerpt'], 50); ?></small>
                                <?php endif; ?>
                            </td>
                            <td><code><?php echo $page['slug']; ?></code></td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo match($page['status']) {
                                        'published' => 'success',
                                        'draft' => 'warning',
                                        default => 'secondary'
                                    };
                                ?>">
                                    <?php echo ucfirst($page['status']); ?>
                                </span>
                                <?php if (!$page['is_active']): ?>
                                <span class="badge bg-secondary">Inactive</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo format_date($page['updated_at']); ?></td>
                            <td>
                                <a href="<?php echo BASE_URL; ?>/page.php?slug=<?php echo $page['slug']; ?>" target="_blank" class="btn btn-sm btn-info" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="?edit=<?php echo $page['id']; ?>" class="btn btn-sm btn-primary" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="?delete=<?php echo $page['id']; ?>" class="btn btn-sm btn-danger confirm-delete" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Page Modal -->
<div class="modal fade" id="pageModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content bg-dark">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo $edit_page ? 'Edit Page' : 'Add Page'; ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <?php echo csrf_field(); ?>
                    
                    <?php if ($edit_page): ?>
                    <input type="hidden" name="id" value="<?php echo $edit_page['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="mb-3">
                        <label class="form-label">Title <span class="text-danger">*</span></label>
                        <input type="text" name="title" class="form-control" 
                               value="<?php echo $edit_page ? sanitize($edit_page['title']) : ''; ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Slug</label>
                        <input type="text" name="slug" class="form-control" 
                               value="<?php echo $edit_page ? sanitize($edit_page['slug']) : ''; ?>"
                               placeholder="auto-generated-from-title">
                        <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" class="form-control" rows="10"><?php echo $edit_page ? htmlspecialchars($edit_page['content']) : ''; ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Excerpt</label>
                        <textarea name="excerpt" class="form-control" rows="2"><?php echo $edit_page ? sanitize($edit_page['excerpt']) : ''; ?></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Meta Title</label>
                            <input type="text" name="meta_title" class="form-control" 
                                   value="<?php echo $edit_page ? sanitize($edit_page['meta_title']) : ''; ?>">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Meta Description</label>
                            <input type="text" name="meta_description" class="form-control" 
                                   value="<?php echo $edit_page ? sanitize($edit_page['meta_description']) : ''; ?>">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="draft" <?php echo ($edit_page && $edit_page['status'] === 'draft') ? 'selected' : ''; ?>>Draft</option>
                                <option value="published" <?php echo ($edit_page && $edit_page['status'] === 'published') ? 'selected' : ''; ?>>Published</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="is_active" id="is_active" 
                               <?php echo (!$edit_page || $edit_page['is_active']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_active">Active</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><?php echo $edit_page ? 'Update' : 'Add'; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php if ($edit_page): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var modal = new bootstrap.Modal(document.getElementById('pageModal'));
    modal.show();
});
</script>
<?php endif; ?>

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