<?php
session_start();
include_once("../config/db.php");

// Security: Ensure user is an admin before performing any action.
if(!isset($_SESSION['admin'])){
    header("Location: login.php");
    exit();
}
include 'admin_header.php';
$message = '';

if(isset($_POST['submit'])){

    $name = $_POST['name'];
    $place = $_POST['place'];
    $review = $_POST['review'];
    $new_filename = null;

    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'gif'];
        $filename = $_FILES['image']['name'];
        $filetype = pathinfo($filename, PATHINFO_EXTENSION);

        if (in_array(strtolower($filetype), $allowed)) {
            // Create a unique filename to prevent overwriting
            $new_filename = uniqid('', true) . '.' . $filetype;
            $upload_path = "uploads/" . $new_filename;

            if (!move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
                $message = "<div class='error'>Error: Could not move uploaded file.</div>";
                $new_filename = null; // Nullify filename on failure
            }
        } else {
            $message = "<div class='error'>Error: Invalid file type. Only JPG, JPEG, PNG, GIF are allowed.</div>";
        }
    }

    if (empty($message)) {
        // Use prepared statements to prevent SQL injection
        $sql = "INSERT INTO reviews(name, place, review, image) VALUES(?, ?, ?, ?)";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, "ssss", $name, $place, $review, $new_filename);
        
        if (mysqli_stmt_execute($stmt)) {
            $message = "<div class='success'>Review Added Successfully.</div>";
        } else {
            $message = "<div class='error'>Database error: Could not add review.</div>";
        }
    }
}
?>
<div class="page-header">
    <h1>Add New Review</h1>
    <a href="view_review.php" class="btn">Back to Reviews</a>
</div>

<div class="content-wrapper">
    <?php if(!empty($message)) echo $message; ?>

    <form method="POST" enctype="multipart/form-data">
        <div class="form-group">
            <label for="name">Customer Name</label>
            <input type="text" id="name" name="name" required>
        </div>
        <div class="form-group">
            <label for="place">Place</label>
            <input type="text" id="place" name="place" placeholder="e.g., City, Country">
        </div>
        <div class="form-group">
            <label for="review">Review</label>
            <textarea id="review" name="review" required></textarea>
        </div>
        <div class="form-group">
            <label for="image">Customer Image (Optional)</label>
            <input type="file" id="image" name="image">
        </div>
        <button type="submit" name="submit">Add Review</button>
    </form>
</div>
<?php include 'admin_footer.php'; ?>