<?php
session_start();
require_once 'db/config.php';

// Ensure user is logged in
if (!isset($_SESSION['user_id'])) {
    // Not logged in
    http_response_code(403);
    exit("You must be logged in to submit a review.");
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    // Not a POST request
    http_response_code(405);
    exit("Invalid request method.");
}

$db = db();
$user_id = $_SESSION['user_id'];

// Get POST data
$order_id = isset($_POST['order_id']) ? (int)$_POST['order_id'] : 0;
$restaurant_id = isset($_POST['restaurant_id']) ? (int)$_POST['restaurant_id'] : 0;
$rating = isset($_POST['rating']) ? (int)$_POST['rating'] : 0;
$review = isset($_POST['review']) ? trim($_POST['review']) : '';

// --- Server-side validation ---

// 1. Basic validation
if ($order_id <= 0 || $restaurant_id <= 0 || $rating < 1 || $rating > 5) {
    $_SESSION['error_message'] = "Invalid data provided. Please try again.";
    header("Location: leave_review.php?order_id=" . $order_id);
    exit();
}

// 2. Security and integrity validation
$stmt = $db->prepare("SELECT id, status FROM orders WHERE id = ? AND user_id = ? AND restaurant_id = ?");
$stmt->execute([$order_id, $user_id, $restaurant_id]);
$order = $stmt->fetch();

if (!$order) {
    $_SESSION['error_message'] = "You cannot review this order.";
    header("Location: order_history.php");
    exit();
} elseif ($order['status'] !== 'Delivered') {
    $_SESSION['error_message'] = "You can only review delivered orders.";
    header("Location: leave_review.php?order_id=" . $order_id);
    exit();
}

// 3. Check if a review already exists
$stmt_rating = $db->prepare("SELECT id FROM ratings WHERE order_id = ?");
$stmt_rating->execute([$order_id]);
if ($stmt_rating->fetch()) {
    $_SESSION['error_message'] = "You have already reviewed this order.";
    header("Location: order_history.php");
    exit();
}

// --- All checks passed, insert into database ---
try {
    $stmt_insert = $db->prepare(
        "INSERT INTO ratings (order_id, restaurant_id, user_id, rating, review) VALUES (?, ?, ?, ?, ?)"
    );
    $stmt_insert->execute([$order_id, $restaurant_id, $user_id, $rating, $review]);

    $_SESSION['success_message'] = "Thank you for your review!";
    header("Location: order_history.php");
    exit();

} catch (PDOException $e) {
    // Log error properly in a real application
    // error_log($e->getMessage()); 
    $_SESSION['error_message'] = "A database error occurred. Please try again later.";
    header("Location: leave_review.php?order_id=" . $order_id);
    exit();
}
