<?php
/**
 * GET /api/reviews/eligible.php?product_id=123
 * A buyer can review a product only once the seller has confirmed the sale
 * (order_items.status = 'fulfilled') - not merely checked out. Before that,
 * they haven't actually received the item yet (it might still be pending
 * pickup, or the seller might cancel it), so there's nothing to review.
 */

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

$userId = require_login();

$productId = (int) ($_GET['product_id'] ?? 0);
if ($productId <= 0) {
    send_error('A valid product_id is required.', 422);
}

$pdo = Database::connect();

$stmt = $pdo->prepare('
    SELECT 1 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"
    LIMIT 1
');
$stmt->execute([$productId, $userId]);
$purchased = (bool) $stmt->fetch();

$stmt = $pdo->prepare('SELECT id, rating, comment FROM product_reviews WHERE product_id = ? AND reviewer_id = ?');
$stmt->execute([$productId, $userId]);
$existing = $stmt->fetch();

send_json(true, 'OK', [
    'purchased' => $purchased,
    'eligible' => $purchased,
    'existing_review' => $existing ?: null,
]);
