<?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 {
    $productId = $_GET['productId'] ?? $_GET['product_id'] ?? null;
    $limit = $_GET['limit'] ?? 10;
    $offset = $_GET['offset'] ?? 0;

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

    // Get approved reviews for the product
    $stmt = $db->prepare("
        SELECT 
            r.*,
            u.name as user_name,
            u.email as user_email
        FROM reviews r
        JOIN users u ON r.user_id = u.id
        WHERE r.product_id = :product_id AND r.is_approved = 1
        ORDER BY r.created_at DESC
        LIMIT :limit OFFSET :offset
    ");
    $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
    $stmt->bindValue(':limit', (int)$limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
    $stmt->execute();
    
    $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get media for each review
    foreach ($reviews as &$review) {
        $mediaStmt = $db->prepare("
            SELECT media_type, file_name, file_path, position
            FROM review_media 
            WHERE review_id = :review_id 
            ORDER BY position ASC
        ");
        $mediaStmt->bindParam(':review_id', $review['id'], PDO::PARAM_STR);
        $mediaStmt->execute();
        
        $review['media'] = $mediaStmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Get review statistics
    $statsStmt = $db->prepare("
        SELECT 
            COUNT(*) as total_reviews,
            AVG(rating) as average_rating,
            SUM(CASE WHEN rating = 5 THEN 1 ELSE 0 END) as five_star,
            SUM(CASE WHEN rating = 4 THEN 1 ELSE 0 END) as four_star,
            SUM(CASE WHEN rating = 3 THEN 1 ELSE 0 END) as three_star,
            SUM(CASE WHEN rating = 2 THEN 1 ELSE 0 END) as two_star,
            SUM(CASE WHEN rating = 1 THEN 1 ELSE 0 END) as one_star
        FROM reviews 
        WHERE product_id = :product_id AND is_approved = 1
    ");
    $statsStmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
    $statsStmt->execute();
    
    $stats = $statsStmt->fetch(PDO::FETCH_ASSOC);

    http_response_code(200);
    echo json_encode([
        'success' => true,
        'reviews' => $reviews,
        'stats' => $stats
    ]);

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