<?php
include 'admin-header.php';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Delete slide
    if (isset($_POST['delete_slide'])) {
        $id = intval($_POST['id']);
        $stmt = $conn->prepare("DELETE FROM carousel_slides WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        header("Location: manage-carousel.php"); exit;
    }

    // Add or Edit slide
    $id = intval($_POST['id'] ?? 0);
    $title = $_POST['title'];
    $caption = $_POST['caption'];
    $display_order = intval($_POST['display_order']);
    $image_url = $_POST['current_image'] ?? '';

    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $target_dir = "../uploads/";
        $target_file = $target_dir . "carousel-" . uniqid() . basename($_FILES["image"]["name"]);
        if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
            $image_url = str_replace('../', '', $target_file);
        }
    }

    if ($id > 0) { // Update
        $stmt = $conn->prepare("UPDATE carousel_slides SET title=?, caption=?, display_order=?, image_url=? WHERE id=?");
        $stmt->bind_param("ssisi", $title, $caption, $display_order, $image_url, $id);
    } else { // Insert
        $stmt = $conn->prepare("INSERT INTO carousel_slides (title, caption, display_order, image_url) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("ssis", $title, $caption, $display_order, $image_url);
    }
    $stmt->execute();
    header("Location: manage-carousel.php"); exit;
}

$edit_slide = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM carousel_slides WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $edit_slide = $stmt->get_result()->fetch_assoc();
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><?php echo $edit_slide ? 'Edit Slide' : 'Add New Slide'; ?></h1>
</div>

<div class="card">
    <div class="card-body">
        <form method="POST" action="manage-carousel.php" enctype="multipart/form-data">
            <input type="hidden" name="id" value="<?php echo $edit_slide['id'] ?? ''; ?>">
            <div class="mb-3"><label class="form-label">Title</label><input type="text" class="form-control" name="title" value="<?php echo htmlspecialchars($edit_slide['title'] ?? ''); ?>" required></div>
            <div class="mb-3"><label class="form-label">Caption</label><input type="text" class="form-control" name="caption" value="<?php echo htmlspecialchars($edit_slide['caption'] ?? ''); ?>" required></div>
            <div class="mb-3"><label class="form-label">Display Order</label><input type="number" class="form-control" name="display_order" value="<?php echo $edit_slide['display_order'] ?? 0; ?>" required></div>
            <div class="mb-3">
                <label class="form-label">Image</label><input type="file" class="form-control" name="image" <?php echo $edit_slide ? '' : 'required'; ?>>
                <?php if (isset($edit_slide['image_url'])): ?><small class="form-text text-muted">Current: <?php echo htmlspecialchars($edit_slide['image_url']); ?></small><input type="hidden" name="current_image" value="<?php echo $edit_slide['image_url']; ?>"><?php endif; ?>
            </div>
            <button type="submit" class="btn btn-primary"><?php echo $edit_slide ? 'Update Slide' : 'Add Slide'; ?></button>
            <?php if ($edit_slide): ?><a href="manage-carousel.php" class="btn btn-secondary">Cancel</a><?php endif; ?>
        </form>
    </div>
</div>

<h2 class="mt-5">Manage Carousel Slides</h2>
<div class="table-responsive">
    <table class="table table-striped">
        <thead><tr><th>Image</th><th>Title</th><th>Order</th><th>Actions</th></tr></thead>
        <tbody>
        <?php
        $result = $conn->query("SELECT * FROM carousel_slides ORDER BY display_order ASC");
        while($row = $result->fetch_assoc()):
        ?>
        <tr>
            <td><img src="../<?php echo htmlspecialchars($row['image_url']); ?>" height="50"></td>
            <td><?php echo htmlspecialchars($row['title']); ?></td>
            <td><?php echo $row['display_order']; ?></td>
            <td>
                <a href="?edit=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-primary">Edit</a>
                <form method="POST" class="d-inline" onsubmit="return confirm('Delete?');"><input type="hidden" name="id" value="<?php echo $row['id']; ?>"><button type="submit" name="delete_slide" class="btn btn-sm btn-outline-danger">Delete</button></form>
            </td>
        </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
</div>

<?php include 'admin-footer.php'; ?>
