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

// Security: Ensure user is an admin and ID is provided.
if(!isset($_SESSION['admin']) || !isset($_GET['id'])){
    header("Location: login.php");
    exit();
}

$id = (int)$_GET['id'];

if ($id > 0) {
    // First, get the image filename to delete the file from the server
    $select_stmt = mysqli_prepare($conn, "SELECT image FROM reviews WHERE id=?");
    mysqli_stmt_bind_param($select_stmt, "i", $id);
    mysqli_stmt_execute($select_stmt);
    $result = mysqli_stmt_get_result($select_stmt);
    if($row = mysqli_fetch_assoc($result)){
        if (!empty($row['image'])) {
            $image_path = "uploads/" . $row['image'];
            if(file_exists($image_path)){
                unlink($image_path); // Delete the file
            }
        }
    }
    mysqli_stmt_close($select_stmt);

    // Now delete the record from the database using a prepared statement
    $stmt = mysqli_prepare($conn, "DELETE FROM reviews WHERE id=?");
    mysqli_stmt_bind_param($stmt, "i", $id);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
}

// Redirect to the correct view page
header("Location: view_review.php");
exit();