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

$customer_id = $_POST['customer_id'] ?? '';
$menu_item_id = $_POST['menu_item_id'] ?? '';
$rating = $_POST['rating'] ?? '';
$review = $_POST['review'] ?? '';

if (!$customer_id || !$menu_item_id || !$rating || !$review) {
    echo json_encode(['success' => false, 'message' => 'All fields are required.']);
    exit;
}

// Optionally, check if this user already reviewed this dish
$stmt = $conn->prepare("SELECT id FROM reviews WHERE customer_id = ? AND menu_item_id = ?");
$stmt->bind_param("si", $customer_id, $menu_item_id);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    // Update existing review
    $stmt->close();
    $stmt = $conn->prepare("UPDATE reviews SET rating = ?, review = ?, created_at = NOW() WHERE customer_id = ? AND menu_item_id = ?");
    $stmt->bind_param("dssi", $rating, $review, $customer_id, $menu_item_id);
    $success = $stmt->execute();
} else {
    // Insert new review
    $stmt->close();
    $stmt = $conn->prepare("INSERT INTO reviews (customer_id, menu_item_id, rating, review, created_at) VALUES (?, ?, ?, ?, NOW())");
    $stmt->bind_param("sids", $customer_id, $menu_item_id, $rating, $review);
    $success = $stmt->execute();
}
$stmt->close();

echo json_encode(['success' => $success]);
