<?php
// FINAL SCRIPT: add_review.php

// Start output buffering to prevent any stray output from breaking the JSON response.
ob_start();// Set up error logging for production.
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Include the database connection script.
require 'db_connect.php';

// Set the header to indicate the response is JSON.
header('Content-Type: application/json');

$response = [];

// 1. Validate the database connection object.
if (!isset($conn) || !($conn instanceof mysqli) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: Database connection failed.';
    ob_clean(); // Clean the buffer before sending the final JSON
    echo json_encode($response);
    exit;
}

// 2. Validate the incoming data from the app.
$required_fields = ['product_id', 'user_id', 'rating', 'comment'];
foreach ($required_fields as $field) {
    if (!isset($_POST[$field])) {
        http_response_code(400); // Bad Request
        $response['status'] = 'error';
        $response['message'] = "Required field '{$field}' is missing.";
        ob_clean();
        echo json_encode($response);
        exit;
    }
}

// 3. Assign and sanitize data from the POST request.
$productId = intval($_POST['product_id']);
$userId = intval($_POST['user_id']);
$rating = floatval($_POST['rating']);
$comment = trim($_POST['comment']);

if (empty($productId) || empty($userId) || empty($rating) || empty($comment)) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = 'All fields are required and cannot be empty.';
    ob_clean();
    echo json_encode($response);
    exit;
}

try {
    // 4. Fetch the reviewer's name from the 'users' table for data integrity.
    $user_sql = "SELECT name FROM users WHERE id = ?";
    $stmt_user = $conn->prepare($user_sql);
    $stmt_user->bind_param("i", $userId);
    $stmt_user->execute();
    $result_user = $stmt_user->get_result();
    $user = $result_user->fetch_assoc();
    
    if (!$user) {
        throw new Exception("User with ID {$userId} not found.");
    }
    $reviewerName = $user['name'];
    $stmt_user->close();

    // 5. Prepare and execute the INSERT statement.
    // The 'status' column will automatically default to 'Pending'.
    $sql = "INSERT INTO reviews (product_id, user_id, reviewer_name, rating, comment) VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iisds", $productId, $userId, $reviewerName, $rating, $comment);

    if ($stmt->execute()) {
        $response['status'] = 'success';
        $response['message'] = 'Review submitted successfully and is awaiting approval.';
    } else {
        throw new Exception('Failed to save the review to the database.');
    }
    $stmt->close();

} catch (Exception $e) {
    // Handle any errors that occurred during the process.
    http_response_code(500); // Internal Server Error
    $response['status'] = 'error';
    $response['message'] = 'Server Error: ' . $e->getMessage();
}

// 6. Send the final JSON response.
ob_clean();
echo json_encode($response);
$conn->close();
exit;
?>