<?php
/**
 * Tom's Java Jive - Submit Review API
 */

header('Content-Type: application/json');

require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['error' => 'Method not allowed'], 405);
}

if (!CustomerAuth::isLoggedIn()) {
    jsonResponse(['error' => 'Please log in to submit a review'], 401);
}

$customer = CustomerAuth::getFullUser();
$input = json_decode(file_get_contents('php://input'), true);

$productId = $input['product_id'] ?? '';
$rating = intval($input['rating'] ?? 0);
$title = trim($input['title'] ?? '');
$content = trim($input['content'] ?? '');

if (empty($productId) || $rating < 1 || $rating > 5 || empty($content)) {
    jsonResponse(['error' => 'Invalid input. Rating and review content are required.'], 400);
}

// Check if product exists
$product = db()->fetch("SELECT product_id FROM products WHERE product_id = :id", ['id' => $productId]);
if (!$product) {
    jsonResponse(['error' => 'Product not found'], 404);
}

// Check if already reviewed
$existingReview = db()->fetch(
    "SELECT review_id FROM reviews WHERE customer_id = :cid AND product_id = :pid",
    ['cid' => $customer['customer_id'], 'pid' => $productId]
);

if ($existingReview) {
    jsonResponse(['error' => 'You have already reviewed this product'], 400);
}

// Create review
$reviewId = generateId('rev_');

db()->insert('reviews', [
    'review_id' => $reviewId,
    'product_id' => $productId,
    'customer_id' => $customer['customer_id'],
    'customer_name' => $customer['name'] ?? explode('@', $customer['email'])[0],
    'customer_email' => $customer['email'],
    'rating' => $rating,
    'title' => $title,
    'comment' => $content,
    'is_approved' => 0 // Reviews require admin approval
]);

jsonResponse([
    'success' => true,
    'message' => 'Review submitted successfully. It will be visible after approval.',
    'review_id' => $reviewId
]);
