<?php
// process-buy-now.php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/functions.php';

header('Content-Type: application/json');

// Check if user is logged in
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Please login to place order']);
    exit;
}

// Get form data
$name = sanitize($_POST['name'] ?? '');
$mobile_no = sanitize($_POST['mobile_no'] ?? '');
$address = sanitize($_POST['address'] ?? '');
$note = sanitize($_POST['note'] ?? '');
$shipping_charge = floatval($_POST['shipping_charge'] ?? 0);
$subtotal = floatval($_POST['subtotal'] ?? 0);
$discount = floatval($_POST['discount'] ?? 0);
$total = floatval($_POST['total'] ?? 0);
$user_id = intval($_POST['user_id'] ?? 0);
$product_id = intval($_POST['product_id'] ?? 0);
$quantity = intval($_POST['quantity'] ?? 1);
$coupon_code = $_POST['coupon'] ?? null;
$coupon_discount = floatval($_POST['coupon_amount'] ?? 0);

// Collect variants - FIXED: Properly collect all variant data
$variants = [];
foreach ($_POST as $key => $value) {
    // Check if key starts with 'variant' (case insensitive)
    if (stripos($key, 'variant') === 0) {
        // Extract the attribute name (remove 'variant' prefix)
        $attr_name = substr($key, 7); // Remove 'variant' from the beginning
        // If attr_name is empty, use 'Size' as default
        if (empty($attr_name)) {
            $attr_name = 'Size';
        }
        $variants[$attr_name] = sanitize($value);
    }
}

// Debug - log variants
error_log('Variants received: ' . print_r($variants, true));

// Validate
if (empty($name)) {
    echo json_encode(['success' => false, 'message' => 'Name is required']);
    exit;
}

if (empty($mobile_no) || strlen($mobile_no) < 11) {
    echo json_encode(['success' => false, 'message' => 'Valid mobile number is required']);
    exit;
}

if (empty($address)) {
    echo json_encode(['success' => false, 'message' => 'Address is required']);
    exit;
}

if ($product_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Product not found']);
    exit;
}

// Get product details
$product = getProduct($pdo, $product_id);
if (!$product) {
    echo json_encode(['success' => false, 'message' => 'Product not found']);
    exit;
}

try {
    $pdo->beginTransaction();
    
    $invoice_no = generateInvoiceNo();
    
    // Insert order
    $stmt = $pdo->prepare("INSERT INTO orders (
        invoice_no, user_id, name, phone, email, address, city, subcity, note,
        subtotal, shipping_charge, discount, total, payment_method, 
        payment_status, order_status, coupon_code, coupon_discount
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    $stmt->execute([
        $invoice_no,
        $user_id,
        $name,
        $mobile_no,
        $_SESSION['user_email'] ?? null,
        $address,
        null, // city
        null, // subcity
        $note,
        $subtotal,
        $shipping_charge,
        $discount,
        $total,
        'cod',
        'pending',
        'pending',
        $coupon_code,
        $coupon_discount
    ]);
    
    $order_id = $pdo->lastInsertId();
    
    // Insert order item with variants
    $price = $product['sale_price'] ?: $product['price'];
    $attributes_json = !empty($variants) ? json_encode($variants) : null;
    
    $stmt = $pdo->prepare("INSERT INTO order_items (
        order_id, product_id, product_name, product_code, attributes, quantity, price, total
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    
    $stmt->execute([
        $order_id,
        $product_id,
        $product['name'],
        $product['product_code'] ?? null,
        $attributes_json,
        $quantity,
        $price,
        $price * $quantity
    ]);
    
    $pdo->commit();
    
    echo json_encode([
        'success' => true,
        'invoice_no' => $invoice_no,
        'message' => 'Order placed successfully',
        'order_id' => $order_id,
        'variants' => $variants // Return variants for debugging
    ]);
    
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode([
        'success' => false,
        'message' => 'Failed to place order: ' . $e->getMessage()
    ]);
}
?>