<?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 {
    $data = json_decode(file_get_contents("php://input"), true);

    $productId = $data['productId'] ?? $data['product_id'] ?? null;
    $quantity = isset($data['quantity']) ? (int)$data['quantity'] : 1;
    $userId = $data['userId'] ?? $data['user_id'] ?? null;
    $variant = $data['variant'] ?? null;
    $finalPrice = $data['final_price'] ?? null;

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

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

    // Check if product exists and has sufficient stock
    $stmt = $db->prepare("SELECT id, name, base_price, stock FROM products WHERE id = :product_id AND is_active = 1");
    $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
    $stmt->execute();
    $product = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$product) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Product not found or inactive']);
        exit;
    }

    // Check stock based on variant selection
    $availableStock = $product['stock']; // Default to product stock
    $stockContext = 'Product';
    
    if ($variant && isset($variant['id'])) {
        // If variant is selected, check variant stock
        try {
            $stmt = $db->prepare("SELECT stock FROM product_variants WHERE id = :variant_id");
            $stmt->bindParam(':variant_id', $variant['id'], PDO::PARAM_STR);
            $stmt->execute();
            $variantData = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($variantData) {
                $availableStock = $variantData['stock'];
                $stockContext = "Variant '{$variant['variant_name']}'";
            }
        } catch (PDOException $e) {
            // If variant table doesn't exist or error, use variant stock from payload
            if (isset($variant['stock'])) {
                $availableStock = $variant['stock'];
                $stockContext = "Variant '{$variant['variant_name']}'";
            }
        }
    }

    // Debug logging
    error_log("Buy Now Debug - Product ID: $productId, Quantity: $quantity, User ID: $userId");
    if ($variant) {
        error_log("Buy Now Debug - Variant: " . json_encode($variant));
    }
    error_log("Buy Now Debug - Stock validation: Context: $stockContext, Available: $availableStock, Requested: $quantity");

    // Validate stock
    if ($availableStock < $quantity) {
        error_log("Buy Now Debug - Stock validation FAILED");
        http_response_code(400);
        echo json_encode([
            'success' => false, 
            'message' => "{$stockContext} has insufficient stock. Available: {$availableStock}, Requested: {$quantity}"
        ]);
        exit;
    }
    
    error_log("Buy Now Debug - Stock validation PASSED");

    // Clear existing cart for this user (Buy Now replaces cart)
    $stmt = $db->prepare("DELETE FROM cart_items WHERE user_id = :user_id");
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
    $stmt->execute();

    // Add the product to cart with variant and custom price
    $itemPrice = $finalPrice ?? $product['base_price'];
    $variantJson = $variant ? json_encode($variant) : null;
    $variantId = $variant ? $variant['id'] : null;
    
    // Check which columns exist and insert accordingly
    try {
        $stmt = $db->prepare("SHOW COLUMNS FROM cart_items LIKE 'variant_data'");
        $stmt->execute();
        $hasVariantData = $stmt->rowCount() > 0;
        
        $stmt = $db->prepare("SHOW COLUMNS FROM cart_items LIKE 'price'");
        $stmt->execute();
        $hasPrice = $stmt->rowCount() > 0;
        
        if ($hasVariantData && $hasPrice) {
            // Use variant_data and price columns
            $stmt = $db->prepare("INSERT INTO cart_items (user_id, product_id, quantity, price, variant_data) VALUES (:user_id, :product_id, :quantity, :price, :variant_data)");
            $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
            $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
            $stmt->bindParam(':quantity', $quantity);
            $stmt->bindParam(':price', $itemPrice);
            $stmt->bindParam(':variant_data', $variantJson);
            $stmt->execute();
        } else if ($hasPrice) {
            // Use variant_id and price columns
            $stmt = $db->prepare("INSERT INTO cart_items (user_id, product_id, variant_id, quantity, price) VALUES (:user_id, :product_id, :variant_id, :quantity, :price)");
            $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
            $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
            $stmt->bindParam(':variant_id', $variantId, PDO::PARAM_STR);
            $stmt->bindParam(':quantity', $quantity);
            $stmt->bindParam(':price', $itemPrice);
            $stmt->execute();
        } else {
            // Basic insert with variant_id only
            $stmt = $db->prepare("INSERT INTO cart_items (user_id, product_id, variant_id, quantity) VALUES (:user_id, :product_id, :variant_id, :quantity)");
            $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
            $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
            $stmt->bindParam(':variant_id', $variantId, PDO::PARAM_STR);
            $stmt->bindParam(':quantity', $quantity);
            $stmt->execute();
        }
        
        error_log("Buy Now Debug - Successfully added to cart");
        
    } catch (PDOException $e) {
        error_log("Buy Now Debug - Database error: " . $e->getMessage());
        // Final fallback to basic insert
        $stmt = $db->prepare("INSERT INTO cart_items (user_id, product_id, quantity) VALUES (:user_id, :product_id, :quantity)");
        $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
        $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
        $stmt->bindParam(':quantity', $quantity);
        $stmt->execute();
    }

    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'Product added to cart for immediate checkout',
        'redirect_to_checkout' => true
    ]);

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