<?php
session_start();
require 'config/db.php';

// 1. Check if the form was actually submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // 2. Get Data from Form
    $product_id = $_POST['product_id'];
    $user_name = trim($_POST['user_name']);
    $rating = $_POST['rating'];
    $comment = trim($_POST['comment']);

    // 3. Basic Validation (Make sure fields aren't empty)
    if (empty($user_name) || empty($comment) || empty($product_id)) {
        // Error: Missing fields
        header("Location: product.php?id=$product_id&error=missing_fields");
        exit();
    }

    // 4. Security: Sanitize Inputs (Prevent XSS/HTML Injection)
    // This turns <script> into &lt;script&gt; so code doesn't run
    $user_name = htmlspecialchars($user_name);
    $comment = htmlspecialchars($comment);

    try {
        // 5. Insert into Database
        $stmt = $pdo->prepare("INSERT INTO reviews (product_id, user_name, rating, comment) VALUES (?, ?, ?, ?)");
        
        if ($stmt->execute([$product_id, $user_name, $rating, $comment])) {
            // Success! Redirect back to product page
            header("Location: /product/$product_id");
        } else {
            // Database failed
            header("Location: product.php?id=$product_id&error=db_error");
        }

    } catch (Exception $e) {
        // Catch any system errors
        header("Location: product.php?id=$product_id&error=system_error");
    }

} else {
    // If someone tries to open this file directly without submitting form
    header("Location: index.php");
    exit();
}
?>