<?php
require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

// Get customer data
$full_name = trim($_POST['full_name'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$email = trim($_POST['email'] ?? '');
$address = trim($_POST['address'] ?? '');
$city = trim($_POST['city'] ?? '');
$state = trim($_POST['state'] ?? '');
$country = trim($_POST['country'] ?? '');

// Validate required fields
if (empty($full_name) || empty($phone) || empty($address) || empty($city) || empty($state) || empty($country)) {
    die("<script>alert('Please fill all required fields'); window.location.href='checkout.php';</script>");
}

try {
    $pdo->beginTransaction();
    
    // Create or get customer
    $stmt = $pdo->prepare("
        INSERT INTO customers (full_name, phone, email, address, city, state, country) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([$full_name, $phone, $email, $address, $city, $state, $country]);
    $customer_id = $pdo->lastInsertId();
    
    // Get cart items
    $cart_items = getCartItems($pdo);
    $cart_total = getCartTotal($pdo);
    
    if (empty($cart_items)) {
        throw new Exception("Cart is empty");
    }
    
    // Generate invoice number
    $invoice_number = 'INV-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
    
    // Get bank details
    $stmt = $pdo->query("SELECT * FROM bank_details WHERE is_active = TRUE LIMIT 1");
    $bank_details = $stmt->fetch();
    $bank_details_text = $bank_details ? json_encode($bank_details) : null;
    
    // Create order
    $stmt = $pdo->prepare("
        INSERT INTO orders (customer_id, total_amount, payment_status, delivery_address, delivery_city, delivery_state, delivery_country, bank_account_details, invoice_number) 
        VALUES (?, ?, 'pending', ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([$customer_id, $cart_total, $address, $city, $state, $country, $bank_details_text, $invoice_number]);
    $order_id = $pdo->lastInsertId();
    
    // Create order items and update stock
    $stmt = $pdo->prepare("INSERT INTO order_items (order_id, equipment_id, quantity, price_at_time) VALUES (?, ?, ?, ?)");
    $update_stock = $pdo->prepare("UPDATE equipment SET stock_quantity = stock_quantity - ? WHERE id = ?");
    
    foreach ($cart_items as $item) {
        $stmt->execute([$order_id, $item['equipment_id'], $item['quantity'], $item['price']]);
        $update_stock->execute([$item['quantity'], $item['equipment_id']]);
    }
    
    // Clear cart
    $stmt = $pdo->prepare("DELETE FROM cart_items WHERE cart_id = ?");
    $stmt->execute([$_SESSION['cart_id']]);
    
    $pdo->commit();
    
    // Redirect to invoice
    header("Location: invoice.php?order_id=$order_id");
    exit;
    
} catch(Exception $e) {
    $pdo->rollBack();
    die("<script>alert('Order failed: " . addslashes($e->getMessage()) . "'); window.location.href='checkout.php';</script>");
}
?>