<?php
require_once __DIR__ . '/config.php';
requireAdmin();
$pdo = getDB();
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$stmt = $pdo->prepare("SELECT * FROM pages WHERE id = ?");
$stmt->execute([$id]);
$page = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$page) { header('Location: pages.php'); exit; }
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sectionKey = $page['slug'];

    // Delete an image
    if (!empty($_POST['delete_image_id'])) {
        $deleteId = (int)$_POST['delete_image_id'];
        try {
            $stmt = $pdo->prepare("SELECT image FROM section_images WHERE id = ? AND section_key = ? LIMIT 1");
            $stmt->execute([$deleteId, $sectionKey]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($row && !empty($row['image'])) {
                $path = dirname(__DIR__) . '/uploads/pages/' . $row['image'];
                if (is_file($path)) @unlink($path);
            }
            $pdo->prepare("DELETE FROM section_images WHERE id = ? AND section_key = ?")->execute([$deleteId, $sectionKey]);
        } catch (Exception $e) { /* table missing */ }
        header('Location: page-edit.php?id=' . $id . '&saved=1');
        exit;
    }

    // Save image list (caption/sort/active)
    if (!empty($_POST['save_images']) && !empty($_POST['img_caption']) && is_array($_POST['img_caption'])) {
        try {
            $stmt = $pdo->prepare("UPDATE section_images SET caption=?, sort_order=?, is_active=? WHERE id=? AND section_key=?");
            foreach ($_POST['img_caption'] as $imgId => $captionRaw) {
                $imgId = (int)$imgId;
                $caption = trim((string)$captionRaw);
                $sort = isset($_POST['img_sort'][$imgId]) ? (int)$_POST['img_sort'][$imgId] : 0;
                $active = !empty($_POST['img_active'][$imgId]) ? 1 : 0;
                $stmt->execute([$caption, $sort, $active, $imgId, $sectionKey]);
            }
        } catch (Exception $e) { /* table missing */ }
        header('Location: page-edit.php?id=' . $id . '&saved=1');
        exit;
    }

    // Upload multiple images
    if (!empty($_FILES['page_images']['name']) && is_array($_FILES['page_images']['name'])) {
        $dir = dirname(__DIR__) . '/uploads/pages/';
        if (!is_dir($dir)) @mkdir($dir, 0755, true);
        try {
            $ins = $pdo->prepare("INSERT INTO section_images (section_key, image, caption, sort_order, is_active) VALUES (?,?,?,?,1)");
            foreach ($_FILES['page_images']['name'] as $idx => $orig) {
                if (empty($orig)) continue;
                $tmp = $_FILES['page_images']['tmp_name'][$idx] ?? '';
                if (!$tmp) continue;
                $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
                if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) continue;
                $name = $sectionKey . '_' . time() . '_' . $idx . '.' . $ext;
                if (move_uploaded_file($tmp, $dir . $name)) {
                    $ins->execute([$sectionKey, $name, '', 0]);
                }
            }
        } catch (Exception $e) { /* table missing */ }
        header('Location: page-edit.php?id=' . $id . '&saved=1');
        exit;
    }

    $title = trim($_POST['title'] ?? '');
    $content = $_POST['content'] ?? '';
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $pdo->prepare("UPDATE pages SET title=?, content=?, is_active=? WHERE id=?")->execute([$title, $content, $is_active, $id]);
    header('Location: pages.php');
    exit;
}
$sectionKey = $page['slug'];
$pageImages = [];
$imagesSupported = true;
try {
    $stmt = $pdo->prepare("SELECT id, image, caption, sort_order, is_active FROM section_images WHERE section_key = ? ORDER BY sort_order, id");
    $stmt->execute([$sectionKey]);
    $pageImages = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $pageImages = []; $imagesSupported = false; }
$pageTitle = 'Edit Page';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1>Edit: <?php echo htmlspecialchars($page['slug']); ?></h1>
    <?php if (isset($_GET['saved'])): ?><p class="success">Saved.</p><?php endif; ?>
    <form method="post" class="admin-form">
        <label>Title</label>
        <input type="text" name="title" required value="<?php echo htmlspecialchars($page['title']); ?>">
        <label>Content</label>
        <textarea name="content" rows="12"><?php echo htmlspecialchars($page['content']); ?></textarea>
        <label><input type="checkbox" name="is_active" value="1" <?php echo $page['is_active'] ? 'checked' : ''; ?>> Active</label>
        <button type="submit" class="btn">Save</button>
        <a href="pages.php" class="btn btn-secondary">Cancel</a>
    </form>

    <h2 style="margin-top:26px;">Page images (multiple)</h2>
    <?php if (!$imagesSupported): ?>
        <p class="error">Multi-image strip is not available. Please run `database/migrate_section_images.sql` in your database.</p>
    <?php endif; ?>
    <p class="muted">Upload one or more images for this page. They will show as a horizontal scroll strip at the top of the page.</p>
    <form method="post" enctype="multipart/form-data" class="admin-form">
        <label>Upload images</label>
        <input type="file" name="page_images[]" accept="image/*" multiple>
        <button type="submit" class="btn">Upload</button>
    </form>

    <?php if (!empty($pageImages)): ?>
        <form method="post" class="admin-form">
            <input type="hidden" name="save_images" value="1">
            <div style="overflow:auto; border:1px solid #e2e8f0; border-radius:12px; padding:12px;">
                <table class="admin-table" style="min-width:760px;">
                    <thead><tr><th>Preview</th><th>Caption</th><th>Sort</th><th>Active</th><th>Delete</th></tr></thead>
                    <tbody>
                    <?php foreach ($pageImages as $img): ?>
                        <tr>
                            <td style="width:150px;">
                                <?php if (!empty($img['image']) && is_file(dirname(__DIR__) . '/uploads/pages/' . $img['image'])): ?>
                                    <img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/pages/<?php echo htmlspecialchars($img['image']); ?>" alt="" style="max-width:130px; border-radius:10px;">
                                <?php endif; ?>
                            </td>
                            <td><input type="text" name="img_caption[<?php echo (int)$img['id']; ?>]" value="<?php echo htmlspecialchars($img['caption'] ?? ''); ?>" placeholder="Optional caption"></td>
                            <td style="width:90px;"><input type="number" name="img_sort[<?php echo (int)$img['id']; ?>]" value="<?php echo (int)$img['sort_order']; ?>" style="width:80px;"></td>
                            <td style="width:90px; text-align:center;"><input type="checkbox" name="img_active[<?php echo (int)$img['id']; ?>]" value="1" <?php echo !empty($img['is_active']) ? 'checked' : ''; ?>></td>
                            <td style="width:120px;">
                                <button type="submit" name="delete_image_id" value="<?php echo (int)$img['id']; ?>" class="btn btn-secondary" onclick="return confirm('Delete this image?');">Delete</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <button type="submit" class="btn" style="margin-top:10px;">Save list</button>
        </form>
    <?php endif; ?>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
