<?php
/**
 * POST /api/reviews/create.php
 * Body (JSON): { product_id, rating (1-5), comment? }
 * Verified server-side against actual purchase history - never trust the
 * client's word that they bought something. Submitting again updates the
 * existing review (one review per product per person).
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

only_post_allowed();
$userId = require_login();

$input = get_json_input();
$productId = (int) ($input['product_id'] ?? 0);
$rating = (int) ($input['rating'] ?? 0);
$comment = trim($input['comment'] ?? '');

if ($productId <= 0) {
    send_error('A valid product_id is required.', 422);
}
if ($rating < 1 || $rating > 5) {
    send_error('Rating must be between 1 and 5.', 422);
}

$pdo = Database::connect();

// Find a fulfilled (seller-confirmed) purchase of this product by this
// buyer - required for review eligibility, and gives us the order_id to
// attach the review to. A pending or cancelled order doesn't count - the
// buyer hasn't actually received the item in either case.
$stmt = $pdo->prepare('
    SELECT o.id FROM order_items oi
    JOIN orders o ON o.id = oi.order_id
    WHERE oi.product_id = ? AND o.buyer_id = ? AND oi.status = "fulfilled"
    ORDER BY o.created_at DESC
    LIMIT 1
');
$stmt->execute([$productId, $userId]);
$orderId = $stmt->fetchColumn();

if (!$orderId) {
    send_error('You can only review products you have purchased.', 403);
}

$stmt = $pdo->prepare('
    INSERT INTO product_reviews (product_id, reviewer_id, order_id, rating, comment)
    VALUES (?, ?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE rating = VALUES(rating), comment = VALUES(comment)
');
$stmt->execute([$productId, $userId, $orderId, $rating, $comment ?: null]);

send_json(true, 'Review saved. Thanks for the feedback!', [], 201);
