<?php
ob_start(); // Prevent headers already sent 
$page_title = '提交订单';
require_once 'includes/header.php';

// Handle direct purchase from product.php
$direct_id = $_GET['direct_id'] ?? null;
$direct_product = null;
if ($direct_id) {
    $stmt = db()->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$direct_id]);
    $direct_product = $stmt->fetch();
}

$redirect_url = '';

// Handle POST request to create order
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $db = db();
    $payment_method = $_POST['payment_method'] ?? 'USDT (TRC20)';
    $cart_data = json_decode($_POST['cart_data'], true);
    
    if (!empty($cart_data)) {
        // Calculate total
        $total = 0;
        foreach ($cart_data as $item) {
            $total += $item['price'] * $item['qty'];
        }
        
        // Generate order number
        $order_no = 'HR' . date('YmdHis') . rand(100, 999);
        
        // Create order
        $stmt = $db->prepare("INSERT INTO orders (order_no, total_amount, payment_method, contact_info, status) VALUES (?, ?, ?, '', 'pending')");
        $stmt->execute([$order_no, $total, $payment_method]);
        $order_id = $db->lastInsertId();
        
        // Create order items
        foreach ($cart_data as $item) {
            $stmt = $db->prepare("INSERT INTO order_items (order_id, product_id, quantity, price_usdt) VALUES (?, ?, ?, ?)");
            $stmt->execute([$order_id, $item['id'], $item['qty'], $item['price']]);
        }

        // Send Telegram notification
        if (function_exists('sendTelegramMessage')) {
            $msg = "🔔 *New Order Created*\n\n";
            $msg .= "Order No: `{$order_no}`\n";
            $msg .= "Total Amount: `{$total} USDT`\n";
            $msg .= "Status: Pending Payment";
            sendTelegramMessage($msg);
        }
        
        $redirect_url = "payment.php?order_no=" . $order_no;
        header("Location: " . $redirect_url);
        exit;
    }
}
?>

<main class="py-3 py-lg-5">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-6 p-2 p-lg-0">
                <div class="glass-card p-4 p-lg-5 bg-white shadow-sm">
                    <h4 class="fw-bold text-dark mb-4"><i class="bi bi-file-earmark-text text-primary me-2"></i> 确认订单信息</h4>
                    
                    <form id="checkout-form" method="POST">
                        <input type="hidden" name="cart_data" id="cart-data-input">
                        
                        <div class="mb-4">
                            <label class="form-label text-dark fw-bold small">支付方式</label>
                            <div class="row g-2">
                                <div class="col-12">
                                    <div class="payment-option p-3 rounded-4 border border-primary bg-primary bg-opacity-10 d-flex align-items-center gap-3">
                                        <i class="bi bi-currency-bitcoin fs-3 text-primary"></i>
                                        <div>
                                            <div class="text-dark fw-bold">USDT (TRC20)</div>
                                            <div class="text-muted small" style="font-size: 0.7rem;">推荐使用，区块链自动确认</div>
                                        </div>
                                        <i class="bi bi-check-circle-fill ms-auto text-primary fs-5"></i>
                                    </div>
                                    <input type="hidden" name="payment_method" value="USDT (TRC20)">
                                </div>
                            </div>
                        </div>

                        <div class="order-summary-box mb-4 p-3 bg-light rounded-4">
                            <h6 class="text-dark fw-bold mb-3 small">订单详情</h6>
                            <div id="checkout-items-list">
                                <!-- JS Populated -->
                            </div>
                            <hr class="my-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="text-dark fw-bold small">应付总额</span>
                                <span class="fs-4 fw-bold text-primary" id="checkout-total">0.00 USDT</span>
                            </div>
                        </div>

                        <button type="submit" id="submit-btn" class="btn btn-primary btn-lg w-100 py-3 rounded-pill shadow-lg fw-bold">
                            确认下单并去支付 <i class="bi bi-arrow-right ms-2"></i>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
document.addEventListener('DOMContentLoaded', function() {
    <?php if ($redirect_url): ?>
        window.location.href = '<?php echo $redirect_url; ?>';
        return;
    <?php endif; ?>

    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    
    <?php if ($direct_product): ?>
        if (cart.length === 0) {
            cart = [{
                id: <?php echo $direct_product['id']; ?>,
                name: "<?php echo addslashes($direct_product['name']); ?>",
                price: <?php echo $direct_product['price_usdt']; ?>,
                image: "<?php echo $direct_product['image_url']; ?>",
                qty: 1
            }];
        }
    <?php endif; ?>

    if (cart.length === 0) {
        window.location.href = 'index.php';
        return;
    }
    
    document.getElementById('cart-data-input').value = JSON.stringify(cart);
    
    let html = '';
    let total = 0;
    cart.forEach(item => {
        const subtotal = item.price * item.qty;
        total += subtotal;
        html += `
            <div class="d-flex justify-content-between text-muted mb-2 small">
                <span class="text-truncate me-2" style="max-width: 70%; text-align: left;">${item.name} x${item.qty}</span>
                <span class="text-dark fw-bold">${subtotal.toFixed(2)}</span>
            </div>
        `;
    });
    
    document.getElementById('checkout-items-list').innerHTML = html;
    document.getElementById('checkout-total').textContent = total.toFixed(2) + ' USDT';

    // Handle button state on click
    document.getElementById('checkout-form').addEventListener('submit', function() {
        const btn = document.getElementById('submit-btn');
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> 正在创建订单...';
    });
});
</script>

<?php 
require_once 'includes/footer.php'; 
ob_end_flush();
?>