<?php
require_once 'includes/config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';

// Check if user is logged in
if (!is_logged_in()) {
    header('Location: /login.php?redirect=' . urlencode($_SERVER['HTTP_REFERER']));
    exit;
}

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /');
    exit;
}

// Get form data
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
$rating = isset($_POST['rating']) ? intval($_POST['rating']) : 0;
$comment = isset($_POST['comment']) ? htmlspecialchars($_POST['comment']) : '';

// Validate form data
if ($product_id <= 0 || $rating < 1 || $rating > 5 || empty($comment)) {
    $_SESSION['review_error'] = 'Please provide a valid rating and comment.';
    header('Location: ' . $_SERVER['HTTP_REFERER']);
    exit;
}

// Check if product exists
$product = get_product($product_id);
if (!$product) {
    $_SESSION['review_error'] = 'Product not found.';
    header('Location: ' . $_SERVER['HTTP_REFERER']);
    exit;
}

// Check if user has already reviewed this product
$existing_review = get_row(
    "SELECT id FROM reviews WHERE product_id = ? AND user_id = ?",
    [$product_id, $_SESSION['user_id']]
);

if ($existing_review) {
    $_SESSION['review_error'] = 'You have already reviewed this product.';
    header('Location: ' . $_SERVER['HTTP_REFERER']);
    exit;
}

// Get user data
$user = get_row(
    "SELECT name, email FROM users WHERE id = ?",
    [$_SESSION['user_id']]
);

// Insert review
try {
    $conn->beginTransaction();
    
    // Insert review
    $stmt = $conn->prepare("
        INSERT INTO reviews (
            product_id, user_id, name, email, rating, comment, status
        ) VALUES (?, ?, ?, ?, ?, ?, 'pending')
    ");
    
    $stmt->execute([
        $product_id, $_SESSION['user_id'], $user['name'], $user['email'], $rating, $comment
    ]);
    
    // Update product rating
    $stmt = $conn->prepare("
        UPDATE products 
        SET rating_sum = rating_sum + ?, rating_count = rating_count + 1 
        WHERE id = ?
    ");
    
    $stmt->execute([$rating, $product_id]);
    
    $conn->commit();
    
    $_SESSION['review_success'] = 'Thank you for your review. It will be published after moderation.';
} catch (Exception $e) {
    $conn->rollBack();
    
    error_log('Review submission error: ' . $e->getMessage());
    $_SESSION['review_error'] = 'An error occurred while submitting your review. Please try again.';
}

// Redirect back to product page
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;