<?php
include 'auth.php';
include 'db.php';
include 'adminhead.php';
include 'sidebar.php';

$success = "";
$error = "";

/* -------------------------
   ADD GALLERY ITEM
---------------------------*/
if (isset($_POST['add_gallery'])) {
    $title = $_POST['title'];
    $category = $_POST['category'];

    if (!empty($_FILES['image']['name'])) {
        $image = time() . "_" . $_FILES['image']['name'];
        $tmp = $_FILES['image']['tmp_name'];
        $path = "assets/images/" . $image;

        if (move_uploaded_file($tmp, $path)) {
            $stmt = $conn->prepare("INSERT INTO gallery(title,image,category) VALUES (?,?,?)");
            $stmt->bind_param("sss", $title, $image, $category);

            $success = $stmt->execute() ? "Gallery item added successfully!" : "Failed to add item.";
        } else {
            $error = "Image upload failed.";
        }
    } else {
        $error = "Please select an image.";
    }
}

/* -------------------------
   DELETE GALLERY ITEM
---------------------------*/
if (isset($_GET['delete_id'])) {
    $id = intval($_GET['delete_id']);

    $file = $conn->query("SELECT image FROM gallery WHERE id=$id")->fetch_assoc();
    if ($file['image'] && file_exists("assets/images/" . $file['image'])) {
        unlink("assets/images/" . $file['image']);
    }

    $stmt = $conn->prepare("DELETE FROM gallery WHERE id=?");
    $stmt->bind_param("i", $id);
    $success = $stmt->execute() ? "Gallery item deleted successfully!" : "Failed to delete item.";
}

/* -------------------------
   UPDATE GALLERY ITEM
---------------------------*/
if (isset($_POST['update_gallery'])) {
    $id = intval($_POST['update_id']);
    $title = $_POST['title'];
    $category = $_POST['category'];

    // Handle image upload
    $old_image = $_POST['old_image'];
    $new_image = $old_image;

    if (!empty($_FILES['image']['name'])) {
        $new_image = time() . "_" . $_FILES['image']['name'];
        move_uploaded_file($_FILES['image']['tmp_name'], "assets/images/" . $new_image);
        if ($old_image && file_exists("assets/images/" . $old_image)) {
            unlink("assets/images/" . $old_image);
        }
    }

    $stmt = $conn->prepare("UPDATE gallery SET title=?, category=?, image=? WHERE id=?");
    $stmt->bind_param("sssi", $title, $category, $new_image, $id);

    $success = $stmt->execute() ? "Gallery item updated successfully!" : "Failed to update item.";
}

/* -------------------------
   FETCH ALL GALLERY ITEMS
---------------------------*/
$data = $conn->query("SELECT * FROM gallery ORDER BY id DESC");
?>

<div class="page-wrapper">
    <div class="container-fluid">

        <h3 class="mb-4 fw-bold">Manage Gallery</h3>

        <?php if ($success): ?>
            <div class="alert alert-success"><?= $success ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger"><?= $error ?></div>
        <?php endif; ?>

        <!-- ADD FORM -->
        <div class="card mb-4">
            <div class="card-header">Add New Gallery Item</div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data" class="row">

                    <div class="col-md-4 mb-3">
                        <label>Title</label>
                        <input type="text" name="title" class="form-control" required>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Category</label>
                        <select class="form-control" name="category" required>
                            <option value="">Select</option>
                            <option value="product">Product Showcase</option>
                            <option value="projects">Client Projects</option>
                        </select>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Image</label>
                        <input type="file" name="image" class="form-control" required>
                    </div>

                    <div class="col-12">
                        <button type="submit" name="add_gallery" class="btn btn-primary">Add Gallery Item</button>
                    </div>

                </form>
            </div>
        </div>

        <!-- GALLERY TABLE -->
        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead class="thead-dark">
                    <tr>
                        <th>#</th>
                        <th>Preview</th>
                        <th>Title</th>
                        <th>Category</th>
                        <th width="160px">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $i = 1; while($row = $data->fetch_assoc()): ?>
                        <tr>
                            <td><?= $i++ ?></td>
                            <td><img src="assets/images/<?= $row['image'] ?>" height="60"></td>
                            <td><?= htmlspecialchars($row['title']) ?></td>
                            <td><?= ucfirst($row['category']) ?></td>
                            <td>
                                <button class="btn btn-warning btn-sm" data-toggle="modal" data-target="#edit<?= $row['id'] ?>">Edit</button>
                                <a href="?delete_id=<?= $row['id'] ?>" onclick="return confirm('Delete this gallery item?')" class="btn btn-danger btn-sm">Delete</a>
                            </td>
                        </tr>

                        <!-- EDIT MODAL -->
                        <div class="modal fade" id="edit<?= $row['id'] ?>" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content">

                                    <form method="POST" enctype="multipart/form-data">
                                        <div class="modal-header">
                                            <h5>Edit Gallery Item #<?= $row['id'] ?></h5>
                                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                                        </div>

                                        <div class="modal-body">
                                            <input type="hidden" name="update_id" value="<?= $row['id'] ?>">
                                            <input type="hidden" name="old_image" value="<?= $row['image'] ?>">

                                            <div class="form-group">
                                                <label>Title</label>
                                                <input type="text" class="form-control" name="title" value="<?= htmlspecialchars($row['title']) ?>" required>
                                            </div>

                                            <div class="form-group">
                                                <label>Category</label>
                                                <select class="form-control" name="category" required>
                                                    <option value="product" <?= $row['category']=='product'?'selected':'' ?>>Product Showcase</option>
                                                    <option value="projects" <?= $row['category']=='projects'?'selected':'' ?>>Client Projects</option>
                                                </select>
                                            </div>

                                            <div class="form-group">
                                                <label>Image</label>
                                                <input type="file" name="image" class="form-control mb-2">
                                                <img src="assets/images/<?= $row['image'] ?>" height="80">
                                            </div>
                                        </div>

                                        <div class="modal-footer">
                                            <button type="submit" name="update_gallery" class="btn btn-success">Save Changes</button>
                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                        </div>
                                    </form>

                                </div>
                            </div>
                        </div>

                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>

    </div>
</div>

<?php include 'adminfoot.php'; ?>
