<?php
require_once __DIR__ . '/../db/config.php';
require_once 'header.php';

$db = db();
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['pages']) && is_array($_POST['pages'])) {
        foreach ($_POST['pages'] as $page_id => $page_data) {
            $title = $page_data['title'] ?? '';
            $content = $page_data['content'] ?? '';

            $stmt = $db->prepare("UPDATE pages SET page_title = :title, content = :content WHERE id = :id");
            $stmt->bindValue(':title', $title);
            $stmt->bindValue(':content', $content);
            $stmt->bindValue(':id', $page_id, PDO::PARAM_INT);
            $stmt->execute();
        }
        $message = '<div class="alert alert-success">Pages updated successfully!</div>';
    }
}

$stmt = $db->query("SELECT * FROM pages ORDER BY id");
$pages = $stmt->fetchAll();

?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Manage Pages</h1>
    <?php echo $message; ?>
    <form method="POST" action="pages.php">
        <?php foreach ($pages as $page): ?>
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Edit <?php echo htmlspecialchars($page['page_title']); ?></h6>
                </div>
                <div class="card-body">
                    <input type="hidden" name="pages[<?php echo $page['id']; ?>][id]" value="<?php echo $page['id']; ?>">
                    <div class="form-group">
                        <label for="page_title_<?php echo $page['id']; ?>">Page Title</label>
                        <input type="text" class="form-control" id="page_title_<?php echo $page['id']; ?>" name="pages[<?php echo $page['id']; ?>][title]" value="<?php echo htmlspecialchars($page['page_title']); ?>">
                    </div>
                    <div class="form-group">
                        <label for="page_content_<?php echo $page['id']; ?>">Content</label>
                        <textarea class="form-control" id="page_content_<?php echo $page['id']; ?>" name="pages[<?php echo $page['id']; ?>][content]" rows="10"><?php echo htmlspecialchars($page['content']); ?></textarea>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
        <button type="submit" class="btn btn-primary">Save Changes</button>
    </form>
</div>

<?php require_once 'footer.php'; ?>
