<?php
require_once '../config/cors.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    $userId = $_GET['userId'] ?? $_GET['user_id'] ?? null;
    $productId = $_GET['productId'] ?? $_GET['product_id'] ?? null;

    if (!$userId || $userId === 'guest') {
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'can_review' => false,
            'message' => 'Please login to write reviews'
        ]);
        exit;
    }

    if (!$productId) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Product ID is required']);
        exit;
    }

    // Check if user has purchased and received this product
    $stmt = $db->prepare("
        SELECT 
            o.id as order_id,
            o.status,
            oi.product_id,
            r.id as existing_review_id
        FROM orders o
        JOIN order_items oi ON o.id = oi.order_id
        LEFT JOIN reviews r ON (r.user_id = o.user_id AND r.product_id = oi.product_id AND r.order_id = o.id)
        WHERE o.user_id = :user_id 
        AND oi.product_id = :product_id
        AND o.status = 'delivered'
        ORDER BY o.created_at DESC
    ");
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
    $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
    $stmt->execute();
    
    $purchases = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($purchases)) {
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'can_review' => false,
            'message' => 'You can only review products you have purchased and received'
        ]);
        exit;
    }

    // Find an order that hasn't been reviewed yet
    $availableOrder = null;
    foreach ($purchases as $purchase) {
        if (!$purchase['existing_review_id']) {
            $availableOrder = $purchase;
            break;
        }
    }

    if (!$availableOrder) {
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'can_review' => false,
            'message' => 'You have already reviewed this product'
        ]);
        exit;
    }

    http_response_code(200);
    echo json_encode([
        'success' => true,
        'can_review' => true,
        'order_id' => $availableOrder['order_id'],
        'message' => 'You can write a review for this product'
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal Server Error: ' . $e->getMessage()
    ]);
}
?>