<?php
session_start();
require 'config/db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $product_id = $_POST['product_id'];
    $user_name = htmlspecialchars(trim($_POST['user_name']));
    $rating = $_POST['rating'];
    $comment = htmlspecialchars(trim($_POST['comment']));

    // --- IMAGE UPLOAD LOGIC ---
    $image_path = NULL;
    if (!empty($_FILES['review_image']['name'])) {
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];
        $ext = strtolower(pathinfo($_FILES['review_image']['name'], PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed) && $_FILES['review_image']['size'] <= 5242880) { // 5MB Limit
            $target_dir = "uploads/reviews/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
            
            $filename = time() . "_" . rand(100,999) . "." . $ext;
            if (move_uploaded_file($_FILES['review_image']['tmp_name'], $target_dir . $filename)) {
                $image_path = $target_dir . $filename;
            }
        }
    }

    if (!empty($user_name) && !empty($comment)) {
        $stmt = $pdo->prepare("INSERT INTO reviews (product_id, user_name, rating, comment, image) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$product_id, $user_name, $rating, $comment, $image_path]);
        header("Location: /product.php?id=$product_id&msg=review_submitted");
    } else {
        header("Location: /product.php?id=$product_id&error=missing_fields");
    }
} else {
    header("Location: /index.php");
}
?>