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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Please login']);
    exit;
}

$name = sanitize($_POST['name'] ?? '');
$phone = sanitize($_POST['phone'] ?? '');
$email = sanitize($_POST['email'] ?? '');
$address = sanitize($_POST['address'] ?? '');
$city = sanitize($_POST['city'] ?? '');
$note = sanitize($_POST['note'] ?? '');
$subtotal = floatval($_POST['subtotal'] ?? 0);
$shipping_charge = floatval($_POST['shipping_charge'] ?? 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);

// Get cart items or single product
$cart_items = getCartItems();

// If product_id is provided, it's a direct buy-now order
if ($product_id > 0 && empty($cart_items)) {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? AND status = 1");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch();
    
    if ($product) {
        // Get variants
        $variants = [];
        foreach ($_POST as $key => $value) {
            if (strpos($key, 'variant') === 0) {
                $attr_name = str_replace('variant', '', $key);
                $variants[$attr_name] = $value;
            }
        }
        
        $price = $product['sale_price'] ?: $product['price'];
        
        // Add extra price for variants
        $stmt = $pdo->prepare("SELECT * FROM product_attributes WHERE product_id = ?");
        $stmt->execute([$product_id]);
        $attributes = $stmt->fetchAll();
        
        foreach ($attributes as $attr) {
            if (in_array($attr['attribute_value'], $variants)) {
                $price += $attr['extra_price'];
            }
        }
        
        $cart_items[] = [
            'product_id' => $product_id,
            'name' => $product['name'],
            'quantity' => $quantity,
            'price' => $price,
            'image' => $product['image'],
            'attributes' => $variants,
            'product_code' => $product['product_code']
        ];
    }
}

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

try {
    $order_data = [
        'user_id' => $user_id,
        'name' => $name,
        'phone' => $phone,
        'email' => $email,
        'address' => $address,
        'city' => $city,
        'note' => $note,
        'subtotal' => $subtotal,
        'shipping_charge' => $shipping_charge,
        'discount' => 0,
        'total' => $total,
        'payment_method' => 'cod',
        'items' => []
    ];
    
    foreach ($cart_items as $item) {
        $order_data['items'][] = [
            'product_id' => $item['product_id'],
            'name' => $item['name'],
            'product_code' => $item['product_code'] ?? null,
            'quantity' => $item['quantity'],
            'price' => $item['price'],
            'attributes' => $item['attributes'] ?? []
        ];
    }
    
    $invoice_no = createOrder($pdo, $order_data);
    
    // Clear cart if it was a cart order
    if (empty($_POST['product_id'])) {
        clearCart();
    }
    
    echo json_encode(['success' => true, 'invoice_no' => $invoice_no]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>