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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $productId = (int)($_POST['product_id'] ?? 0);
    $rating = (int)($_POST['rating'] ?? 5);
    $title = trim($_POST['title'] ?? '');
    $comment = trim($_POST['comment'] ?? '');
    
    if ($rating < 1 || $rating > 5) $rating = 5;
    
    $db->prepare("INSERT INTO reviews (product_id, user_id, rating, title, comment) VALUES (?, ?, ?, ?, ?)")
        ->execute([$productId, $userId, $rating, $title, $comment]);
    
    flash('success', 'Review submitted! It will be visible after approval.');
    header('Location: ../product.php?slug=' . $_POST['slug']);
    exit;
}
