<?php
require('connection.inc.php');
require('security.php');

if (!isset($_SESSION['user_id'])) {
    $product_url_name = $_POST['product_url_name'] ?? 'products';
    header("Location: product-details.php/" . $product_url_name . "?review=not_logged_in");
    exit;
}

$user_id = $_SESSION['user_id'];
$product_id = intval($_POST['product_id'] ?? 0);
$product_url_name = $_POST['product_url_name'] ?? '';
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$rating = intval($_POST['rating']);
$message = trim($_POST['message']);

if ($rating < 1 || $rating > 5) {
    die("Invalid rating.");
}

$stmt = $conn->prepare("INSERT INTO product_reviews (product_id, user_id, rating, name, email, message) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("iiisss", $product_id, $user_id, $rating, $name, $email, $message);
$stmt->execute();
$stmt->close();

header("Location: product-details.php/" . $product_url_name . "?review=success");
exit;
?>
