<?php
ob_start();
include 'includes.php';
include 'connection.php';
session_start();

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

// Pagination setup
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 12;
$offset = ($page - 1) * $per_page;

// 1. Bulk Delete Logic (New)
if (isset($_POST['bulk_delete']) && isset($_POST['selected_items']) && !empty($_POST['selected_items'])) {
    $selectedIds = $_POST['selected_items'];
    foreach ($selectedIds as $id) {
        $id = (int)$id;
        // Fetch image to delete from folder
        $res = $conn->query("SELECT image FROM gallery WHERE id=$id");
        if ($res->num_rows > 0) {
            $row = $res->fetch_assoc();
            if (file_exists("../" . $row['image'])) {
                unlink("../" . $row['image']);
            }
        }
        // Delete from database
        $conn->query("DELETE FROM gallery WHERE id=$id");
    }
    header("Location: manage_gallery.php?page=" . $page);
    exit;
}

// 2. Single Delete Logic
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $res = $conn->query("SELECT image FROM gallery WHERE id=$id");
    if ($res->num_rows > 0) {
        $row = $res->fetch_assoc();
        if (file_exists("../" . $row['image'])) unlink("../" . $row['image']);
    }
    $conn->query("DELETE FROM gallery WHERE id=$id");
    header("Location: manage_gallery.php?page=" . $page);
    exit;
}

// Toggle Status Logic
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $conn->query("UPDATE gallery SET status = 1-status WHERE id=$id");
    header("Location: manage_gallery.php?page=" . $page);
    exit;
}

// Add Logic
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['bulk_delete'])) {
    $targetDir = "../assets/gallery/";
    if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

    if (!empty($_FILES['image']['name'])) {
        $fileName = time() . "_" . basename($_FILES['image']['name']);
        $targetFile = $targetDir . $fileName;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {
            $dbPath = "assets/gallery/" . $fileName;
            $conn->query("INSERT INTO gallery (image, status) VALUES ('$dbPath', 1)");
        }
    }
    header("Location: manage_gallery.php");
    exit;
}

// Get paginated results
$total_query = $conn->query("SELECT COUNT(*) as total FROM gallery");
$total = $total_query->fetch_assoc()['total'];
$total_pages = ceil($total / $per_page);

$result = $conn->query("SELECT * FROM gallery ORDER BY id DESC LIMIT $per_page OFFSET $offset");
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Manage Gallery</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body {
            background-image: url('../assets/images/footer-bg.png');
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
            margin: 0;
            padding: 0;
            font-family: sans-serif;
        }

        .spac-content {
            padding: 15px;
            min-height: 100vh;
            background-image: url('../assets/images/footer-bg.png');
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
        }

        .spac-management-container {
            max-width: 1200px;
            margin: auto;
        }

        .spac-management-title {
            font-size: 1.3rem;
            margin-bottom: 15px;
            color: white;
        }

        /* Simple Upload Form Styling */
        .spac-upload-form {
            background: rgba(255, 255, 255, 0.9);
            padding: 20px;
            border-radius: 8px;
            display: flex;
            gap: 15px;
            align-items: center;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .spac-input {
            border: 1px solid #ccc;
            padding: 8px;
            border-radius: 4px;
            flex-grow: 1;
        }

        .spac-upload-btn {
            padding: 9px 25px;
            background: brown;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
            transition: 0.3s;
        }

        .spac-upload-btn:hover {
            background: #8b0000;
        }

        /* Gallery Grid Layout */
        .spac-gallery-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
        }

        .spac-gallery-item {
            position: relative;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            transition: 0.3s;
        }

        .spac-gallery-item:hover {
            transform: translateY(-5px);
        }

        .spac-gallery-item img {
            width: 100%;
            height: 120px;
            object-fit: cover;
            display: block;
        }

        /* Checkbox Overlay Styling */
        .spac-checkbox-overlay {
            position: absolute;
            top: 5px;
            left: 5px;
            z-index: 10;
        }

        .spac-checkbox-overlay input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }

        .spac-item-actions {
            display: flex;
            justify-content: space-between;
            padding: 8px;
            background: #f9f9f9;
        }

        .spac-btn {
            width: 32px;
            height: 32px;
            border-radius: 4px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: white;
            text-decoration: none;
            font-size: 0.9rem;
            border: none;
            cursor: pointer;
        }

        .spac-toggle-btn {
            background-color: #17a2b8;
        }

        .spac-delete-btn {
            background-color: #dc3545;
        }

        /* Bulk Delete Button Styling */
        .bulk-actions {
            margin-bottom: 15px;
            text-align: right;
        }

        .bulk-delete-btn {
            padding: 8px 20px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
        }

        .bulk-delete-btn:hover {
            background: #c82333;
        }

        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 5px;
        }

        .pagination a,
        .pagination span {
            padding: 8px 12px;
            background: white;
            color: brown;
            text-decoration: none;
            border-radius: 4px;
            border: 1px solid #ddd;
        }

        .pagination a:hover {
            background: brown;
            color: white;
        }

        .pagination .current {
            background: brown;
            color: white;
            font-weight: bold;
        }

        .pagination .disabled {
            color: #ccc;
            pointer-events: none;
        }
    </style>
</head>

<body>
    <div class="spac-content">
        <div class="spac-management-container">
            <h1 class="spac-management-title">Manage Gallery</h1>

            <!-- Simple Upload Form -->
            <form class="spac-upload-form" method="POST" enctype="multipart/form-data">
                <input type="file" name="image" class="spac-input" accept="image/*" required>
                <button type="submit" class="spac-upload-btn"><i class="fas fa-upload"></i> Upload Image</button>
            </form>

            <!-- Bulk Delete Form -->
            <form method="POST" id="bulkForm">
                <input type="hidden" name="bulk_delete" value="1">

                <div class="bulk-actions">
                    <button type="button" class="bulk-delete-btn" onclick="performBulkDelete()">
                        <i class="fas fa-trash-alt"></i> Delete Selected
                    </button>
                </div>

                <!-- Gallery Grid -->
                <div class="spac-gallery-grid">
                    <?php
                    while ($row = $result->fetch_assoc()):
                    ?>
                        <div class="spac-gallery-item">
                            <!-- Checkbox -->
                            <div class="spac-checkbox-overlay">
                                <input type="checkbox" name="selected_items[]" value="<?= $row['id'] ?>" class="item-checkbox">
                            </div>

                            <img src="../<?= htmlspecialchars($row['image']) ?>" onerror="this.src='https://via.placeholder.com/150'">
                            <div class="spac-item-actions">
                                <a href="?page=<?= $page ?>&toggle=<?= $row['id'] ?>" class="spac-btn spac-toggle-btn" title="Toggle Status">
                                    <i class="fas fa-<?= $row['status'] ? 'eye' : 'eye-slash' ?>"></i>
                                </a>
                                <a href="?page=<?= $page ?>&delete=<?= $row['id'] ?>" onclick="return confirm('Delete this image?')" class="spac-btn spac-delete-btn" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </div>
                        </div>
                    <?php endwhile; ?>
                </div>
            </form>

            <?php if ($total_pages > 1): ?>
                <div class="pagination">
                    <?php if ($page > 1): ?>
                        <a href="?page=1">First</a>
                        <a href="?page=<?= $page - 1 ?>">Prev</a>
                    <?php else: ?>
                        <span class="disabled">First</span>
                        <span class="disabled">Prev</span>
                    <?php endif; ?>

                    <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                        <?php if ($i == $page): ?>
                            <span class="current"><?= $i ?></span>
                        <?php else: ?>
                            <a href="?page=<?= $i ?>"><?= $i ?></a>
                        <?php endif; ?>
                    <?php endfor; ?>

                    <?php if ($page < $total_pages): ?>
                        <a href="?page=<?= $page + 1 ?>">Next</a>
                        <a href="?page=<?= $total_pages ?>">Last</a>
                    <?php else: ?>
                        <span class="disabled">Next</span>
                        <span class="disabled">Last</span>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div><br><br><br><br>

    <script>
        function performBulkDelete() {
            const checkboxes = document.querySelectorAll('.item-checkbox:checked');
            if (checkboxes.length === 0) {
                alert('Please select at least one image to delete.');
                return;
            }

            if (confirm('Are you sure you want to delete ' + checkboxes.length + ' selected images?')) {
                document.getElementById('bulkForm').submit();
            }
        }
    </script>
</body>

</html>
<?php ob_end_flush(); ?>