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

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

$uploadDir = "assets/images/"; // Create this folder

/* -------------------------
   DELETE REVIEW
---------------------------*/
if (isset($_GET['delete_id'])) {

    $id = intval($_GET['delete_id']);

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

    $stmt = $conn->prepare("DELETE FROM reviews WHERE id=?");
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) $success = "Review deleted successfully!";
    else $error = "Failed to delete review: " . $stmt->error;
}

/* -------------------------
   ADD REVIEW
---------------------------*/
if (isset($_POST['add_review'])) {

    $title = $_POST['title'];
    $description = $_POST['description'];

    if ($_FILES['image']['error'] == 0) {

        $imageName = time() . "_" . basename($_FILES['image']['name']);
        $target = $uploadDir . $imageName;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {

            $stmt = $conn->prepare("INSERT INTO reviews (title, image, description) VALUES (?, ?, ?)");
            $stmt->bind_param("sss", $title, $imageName, $description);

            if ($stmt->execute()) $success = "Review added successfully!";
            else $error = "Failed to add review: " . $stmt->error;

        } else {
            $error = "Image upload failed!";
        }

    } else {
        $error = "Please select an image!";
    }
}

/* -------------------------
   UPDATE REVIEW
---------------------------*/
if (isset($_POST['update_review'])) {

    $id = intval($_POST['update_id']);
    $title = $_POST['title'];
    $description = $_POST['description'];
    $oldImage = $_POST['old_image'];

    $finalImage = $oldImage;

    if ($_FILES['image']['error'] == 0) {

        $newImage = time() . "_" . basename($_FILES['image']['name']);
        $target = $uploadDir . $newImage;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {

            // Delete old image
            if (file_exists($uploadDir . $oldImage)) {
                unlink($uploadDir . $oldImage);
            }

            $finalImage = $newImage;
        }
    }

    $stmt = $conn->prepare("UPDATE reviews SET title=?, image=?, description=? WHERE id=?");
    $stmt->bind_param("sssi", $title, $finalImage, $description, $id);

    if ($stmt->execute()) $success = "Review updated successfully!";
    else $error = "Failed to update review: " . $stmt->error;
}

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

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

        <h3 class="mb-4 fw-bold">Manage Reviews</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 Review</div>
            <div class="card-body">

                <form method="POST" enctype="multipart/form-data">
                    
                    <div class="mb-3">
                        <label>Review Title</label>
                        <input type="text" name="title" class="form-control" required>
                    </div>

                    <div class="mb-3">
                        <label>Review Image</label>
                        <input type="file" name="image" class="form-control" accept="image/*" required>
                    </div>

                    <div class="mb-3">
                        <label>Description</label>
                        <textarea name="description" class="form-control" rows="4" required></textarea>
                    </div>

                    <button type="submit" name="add_review" class="btn btn-primary">Add Review</button>

                </form>

            </div>
        </div>

        <!-- TABLE -->
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Title</th>
                    <th>Image</th>
                    <th>Description</th>
                    <th>Created</th>
                    <th>Actions</th>
                </tr>
            </thead>

            <tbody>
            <?php $i=1; while($row = $data->fetch_assoc()): ?>
                <tr>
                    <td><?= $i++ ?></td>
                    <td><?= htmlspecialchars($row['title']) ?></td>
                    <td><img src="<?= $uploadDir . $row['image'] ?>" width="70"></td>
                    <td><?= htmlspecialchars(substr($row['description'], 0, 60)) ?>...</td>
                    <td><?= $row['created_at'] ?></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 review?')" 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 Review #<?= $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 mb-3">
                                        <label>Review Title</label>
                                        <input type="text" name="title" class="form-control" value="<?= $row['title'] ?>" required>
                                    </div>

                                    <div class="form-group mb-3">
                                        <label>Review Image</label>
                                        <input type="file" name="image" class="form-control">
                                        <img src="<?= $uploadDir . $row['image'] ?>" width="80" class="mt-2">
                                    </div>

                                    <div class="form-group">
                                        <label>Description</label>
                                        <textarea name="description" class="form-control" rows="4" required><?= $row['description'] ?></textarea>
                                    </div>

                                </div>

                                <div class="modal-footer">
                                    <button type="submit" name="update_review" 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>

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