<?php
// FINAL SCRIPT: get_reviews.php

ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require 'db_connect.php';

header('Content-Type: application/json');
ob_clean();

$response = [];

// 1. Validate Connection
if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: Database connection failed.';
    echo json_encode($response);
    exit;
}

// 2. Validate Input
if (!isset($_GET['product_id']) || empty($_GET['product_id'])) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = 'Product ID is required.';
    echo json_encode($response);
    exit;
}

$productId = intval($_GET['product_id']);

try {
    // 3. THE FIX: Select only 'Published' reviews for the given product
    $sql = "SELECT reviewer_name, rating, comment, created_at FROM reviews WHERE product_id = ? AND status = 'Published' ORDER BY id DESC";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $productId);
    $stmt->execute();
    $result = $stmt->get_result();

    $reviews = [];
    while($row = $result->fetch_assoc()) {
        $reviews[] = $row;
    }

    // 4. Success: Send the JSON response (even if it's an empty array)
    echo json_encode($reviews);

} catch (Exception $e) {
    // 5. Failure
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'An error occurred while fetching reviews: ' . $e->getMessage();
    echo json_encode($response);
}

$conn->close();
exit;
?>