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

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

$method = $_SERVER['REQUEST_METHOD'];

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

try {
    // Handle both JSON and form data
    $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
    
    if (strpos($contentType, 'multipart/form-data') !== false) {
        // Form data with files
        $data = $_POST;
        $files = $_FILES;
    } else {
        // JSON data
        $data = json_decode(file_get_contents("php://input"), true);
        $files = [];
    }

    // Validate required fields
    $userId = $data['userId'] ?? $data['user_id'] ?? null;
    $productId = $data['productId'] ?? $data['product_id'] ?? null;
    $orderId = $data['orderId'] ?? $data['order_id'] ?? null;
    $rating = $data['rating'] ?? null;
    $title = $data['title'] ?? '';
    $reviewText = $data['reviewText'] ?? $data['review_text'] ?? '';

    if (!$userId || $userId === 'guest') {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'User must be logged in to write reviews']);
        exit;
    }

    if (!$productId || !$orderId || !$rating) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Product ID, Order ID, and Rating are required']);
        exit;
    }

    if ($rating < 1 || $rating > 5) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Rating must be between 1 and 5']);
        exit;
    }

    // Start transaction
    $db->beginTransaction();

    // Verify user has purchased this product in this order
    $stmt = $db->prepare("
        SELECT oi.id 
        FROM order_items oi
        JOIN orders o ON oi.order_id = o.id
        WHERE o.id = :order_id 
        AND o.user_id = :user_id 
        AND oi.product_id = :product_id
        AND o.status = 'delivered'
    ");
    $stmt->bindParam(':order_id', $orderId, PDO::PARAM_STR);
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
    $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
    $stmt->execute();
    
    if (!$stmt->fetch()) {
        $db->rollBack();
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'You can only review products you have purchased and received']);
        exit;
    }

    // Check if user already reviewed this product for this order
    $stmt = $db->prepare("
        SELECT id FROM reviews 
        WHERE user_id = :user_id AND product_id = :product_id AND order_id = :order_id
    ");
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
    $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
    $stmt->bindParam(':order_id', $orderId, PDO::PARAM_STR);
    $stmt->execute();
    
    if ($stmt->fetch()) {
        $db->rollBack();
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'You have already reviewed this product']);
        exit;
    }

    // Create review
    $reviewId = bin2hex(random_bytes(16));
    $stmt = $db->prepare("
        INSERT INTO reviews (
            id, product_id, user_id, order_id, rating, title, review_text, is_approved
        ) VALUES (
            :id, :product_id, :user_id, :order_id, :rating, :title, :review_text, FALSE
        )
    ");
    $stmt->bindParam(':id', $reviewId, PDO::PARAM_STR);
    $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
    $stmt->bindParam(':order_id', $orderId, PDO::PARAM_STR);
    $stmt->bindParam(':rating', $rating, PDO::PARAM_INT);
    $stmt->bindParam(':title', $title, PDO::PARAM_STR);
    $stmt->bindParam(':review_text', $reviewText, PDO::PARAM_STR);
    $stmt->execute();

    // Handle file uploads
    if (!empty($files['media'])) {
        $uploadDir = '../uploads/reviews/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $mediaFiles = $files['media'];
        $mediaCount = is_array($mediaFiles['name']) ? count($mediaFiles['name']) : 1;
        
        // Limit to 5 files
        if ($mediaCount > 5) {
            $db->rollBack();
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Maximum 5 media files allowed']);
            exit;
        }

        for ($i = 0; $i < $mediaCount; $i++) {
            $fileName = is_array($mediaFiles['name']) ? $mediaFiles['name'][$i] : $mediaFiles['name'];
            $fileTmpName = is_array($mediaFiles['tmp_name']) ? $mediaFiles['tmp_name'][$i] : $mediaFiles['tmp_name'];
            $fileSize = is_array($mediaFiles['size']) ? $mediaFiles['size'][$i] : $mediaFiles['size'];
            $fileType = is_array($mediaFiles['type']) ? $mediaFiles['type'][$i] : $mediaFiles['type'];

            // Validate file size (40MB max)
            if ($fileSize > 40 * 1024 * 1024) {
                $db->rollBack();
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'File size must be less than 40MB']);
                exit;
            }

            // Validate file type
            $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'video/mp4', 'video/avi', 'video/mov'];
            if (!in_array($fileType, $allowedTypes)) {
                $db->rollBack();
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Only images (JPG, PNG, GIF) and videos (MP4, AVI, MOV) are allowed']);
                exit;
            }

            // Generate unique filename
            $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
            $uniqueFileName = $reviewId . '_' . $i . '_' . time() . '.' . $fileExtension;
            $filePath = $uploadDir . $uniqueFileName;

            if (move_uploaded_file($fileTmpName, $filePath)) {
                // Determine media type
                $mediaType = strpos($fileType, 'image/') === 0 ? 'image' : 'video';

                // Insert media record
                $mediaId = bin2hex(random_bytes(16));
                $stmt = $db->prepare("
                    INSERT INTO review_media (
                        id, review_id, media_type, file_name, file_path, file_size, mime_type, position
                    ) VALUES (
                        :id, :review_id, :media_type, :file_name, :file_path, :file_size, :mime_type, :position
                    )
                ");
                $stmt->bindParam(':id', $mediaId, PDO::PARAM_STR);
                $stmt->bindParam(':review_id', $reviewId, PDO::PARAM_STR);
                $stmt->bindParam(':media_type', $mediaType, PDO::PARAM_STR);
                $stmt->bindParam(':file_name', $fileName, PDO::PARAM_STR);
                $stmt->bindParam(':file_path', $uniqueFileName, PDO::PARAM_STR);
                $stmt->bindParam(':file_size', $fileSize, PDO::PARAM_INT);
                $stmt->bindParam(':mime_type', $fileType, PDO::PARAM_STR);
                $stmt->bindParam(':position', $i, PDO::PARAM_INT);
                $stmt->execute();
            }
        }
    }

    // Commit transaction
    $db->commit();

    http_response_code(201);
    echo json_encode([
        'success' => true,
        'message' => 'Review submitted successfully! It will be visible after admin approval.',
        'review_id' => $reviewId
    ]);

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