<?php
header('Content-Type: application/json');

// --- 1. INCLUDE DATABASE CONNECTION ---
// This file provides the $conn (MySQLi) object
require_once 'db_connect.php'; 

$reviewId = isset($_POST['review_id']) ? (int)$_POST['review_id'] : 0;
$status = isset($_POST['status']) ? $_POST['status'] : '';

$response = ['status' => 'error', 'message' => 'Invalid request.'];

if ($reviewId > 0 && !empty($status)) {
    // Define which statuses are allowed for security
    $allowed_statuses = ['published', 'deleted', 'pending'];
    
    if (in_array($status, $allowed_statuses)) {
        // --- 2. PREPARE AND EXECUTE UPDATE ---
        $stmt = $conn->prepare("UPDATE reviews SET status = ? WHERE id = ?");
        $stmt->bind_param("si", $status, $reviewId);

        if ($stmt->execute()) {
            // Check if any row was actually changed
            if ($stmt->affected_rows > 0) {
                $response = ['status' => 'success', 'message' => 'Review status updated successfully.'];
            } else {
                $response['message'] = 'Review not found or status already matches.';
            }
        } else {
            $response['message'] = 'Failed to execute query.';
        }
        $stmt->close();
    } else {
        $response['message'] = 'Invalid status provided.';
    }
}

// --- 3. OUTPUT AND CLOSE ---
echo json_encode($response);
$conn->close();
?>