<?php
session_start();
require_once __DIR__ . '/helpers/currency_helper.php';
require __DIR__ . '/db_config.php';

// Check if user is logged in
if (empty($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? '';
$email = '';

// Get user email from database
$stmt = $conn->prepare("SELECT email FROM users WHERE id = ?");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result && $result->num_rows > 0) {
    $user = $result->fetch_assoc();
    $email = $user['email'];
}
$stmt->close();

// Get cart from session
$cart = $_SESSION['cart'] ?? [];
$cartItems = [];
$totalPrice = 0;

// Load products and build cart display
if (!empty($cart)) {
    if (file_exists(__DIR__ . '/data/products.json')) {
        $list = json_decode(file_get_contents(__DIR__ . '/data/products.json'), true) ?? [];
        // re-index products by id to match how cart stores keys
        $products = [];
        foreach ($list as $pr) {
            if (isset($pr['id'])) $products[(int)$pr['id']] = $pr;
        }
        foreach ($cart as $cartKey => $item) {
            // Handle new cart structure with composite keys (id_size)
            if (is_array($item) && isset($item['id'])) {
                $pid = (int)$item['id'];
                $qty = (int)($item['qty'] ?? 1);
                $size = $item['size'] ?? '';
            } else {
                // Fallback for old structure
                $pid = (int)$cartKey;
                $qty = (int)$item;
                $size = '';
            }
            
            $product = $products[$pid] ?? null;
            if ($product && is_numeric($product['price'])) {
                $subtotal = $product['price'] * $qty;
                $cartItems[] = [
                    'id' => $pid,
                    'title' => $product['title'] ?? $product['name'] ?? 'Product',
                    'price' => $product['price'],
                    'quantity' => $qty,
                    'size' => $size,
                    'subtotal' => $subtotal
                ];
                $totalPrice += $subtotal;
            }
        }
    }
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Checkout</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="css/responsive-system.css">
    <style>
        .checkout-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 32px;
            max-width: 1100px;
            margin: 0 auto;
        }
        
        @media (max-width: 768px) {
            .checkout-container {
                grid-template-columns: 1fr;
                gap: 24px;
            }
        }
        
        .checkout-section {
            background: #fff;
            padding: 24px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .checkout-section h2 {
            font-size: 18px;
            margin-bottom: 16px;
            border-bottom: 2px solid #667eea;
            padding-bottom: 8px;
        }
        
        .form-group {
            margin-bottom: 16px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            color: #333;
            font-size: 14px;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            font-family: inherit;
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }
        
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .cart-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #eee;
        }
        
        .cart-item:last-child {
            border-bottom: none;
        }
        
        .cart-item-name {
            flex: 1;
            font-weight: 500;
        }
        
        .cart-item-qty {
            color: #666;
            font-size: 14px;
            margin: 0 12px;
        }
        
        .cart-item-price {
            font-weight: 600;
            color: #667eea;
            min-width: 80px;
            text-align: right;
        }
        
        .order-summary {
            background: #f5f5f5;
            padding: 16px;
            border-radius: 4px;
            margin-top: 16px;
        }
        
        .summary-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .summary-row.total {
            border-top: 2px solid #ddd;
            padding-top: 8px;
            font-size: 16px;
            font-weight: 600;
            color: #333;
        }
        
        .btn-place-order {
            width: 100%;
            background: #667eea;
            color: #fff;
            padding: 12px;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin-top: 24px;
            transition: background 0.2s;
        }
        
        .btn-place-order:hover {
            background: #5568d3;
        }
        
        .btn-place-order:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .message {
            padding: 12px;
            border-radius: 4px;
            margin-bottom: 16px;
            font-size: 14px;
        }
        
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
<?php include __DIR__ . '/header.php'; ?>

<main class="container" style="margin: 24px auto;">
    <div style="margin-bottom: 32px;">
        <h1 style="font-size: 32px; margin-bottom: 8px;">Checkout</h1>
        <p style="color: #666;">Complete your purchase</p>
    </div>

    <div class="checkout-container">
        <!-- Cart Summary -->
        <div>
            <div class="checkout-section">
                <h2>📦 Order Summary</h2>
                <?php if (empty($cartItems)): ?>
                    <p style="color: #999; text-align: center; padding: 24px 0;">Your cart is empty</p>
                    <a href="shop.php" class="btn" style="display: block; text-align: center;">Continue Shopping</a>
                <?php else: ?>
                    <div style="margin-bottom: 16px;">
                        <?php foreach ($cartItems as $item): ?>
                        <div class="cart-item">
                            <span class="cart-item-name"><?php echo htmlspecialchars($item['title']); ?></span>
                            <span class="cart-item-qty">x<?php echo $item['quantity']; ?></span>
                            <span class="cart-item-price"><?php echo htmlspecialchars(format_currency((float)$item['subtotal'])); ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="order-summary">
                        <div class="summary-row">
                            <span>Subtotal:</span>
                            <span><?php echo htmlspecialchars(format_currency((float)$totalPrice)); ?></span>
                        </div>
                        <div class="summary-row">
                            <span>Shipping:</span>
                            <span>Free</span>
                        </div>
                        <div class="summary-row">
                            <span>Tax:</span>
                            <span><?php echo htmlspecialchars(format_currency(0.0)); ?></span>
                        </div>
                        <div class="summary-row total">
                            <span>Total:</span>
                            <span><?php echo htmlspecialchars(format_currency((float)$totalPrice)); ?></span>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Checkout Form -->
        <div>
            <div class="checkout-section">
                <h2>📍 Shipping Details</h2>
                
                <div id="message"></div>
                
                <form id="checkoutForm">
                    <div class="form-group">
                        <label>Full Name</label>
                        <input type="text" name="fullname" value="<?php echo htmlspecialchars($username); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" name="email" value="<?php echo htmlspecialchars($email); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Shipping Address</label>
                        <textarea name="address" placeholder="Street address, city, state, zip code" required></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>Payment Method</label>
                        <select name="payment" required>
                            <option value="">-- Select Payment Method --</option>
                            <option value="credit_card">Credit Card</option>
                            <option value="paypal">PayPal</option>
                            <option value="bank_transfer">Bank Transfer</option>
                            <option value="cash_on_delivery">Cash on Delivery</option>
                        </select>
                    </div>
                    
                    <?php if (!empty($cartItems)): ?>
                    <button type="submit" class="btn-place-order">Place Order</button>
                    <?php else: ?>
                    <button type="submit" class="btn-place-order" disabled>Cart is Empty</button>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>
</main>

<?php include __DIR__ . '/footer.php'; ?>

<script>
document.getElementById('checkoutForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const submitBtn = document.querySelector('.btn-place-order');
    submitBtn.disabled = true;
    const origBtnText = submitBtn.textContent;
    submitBtn.textContent = 'Placing order...';

    const fullname = document.querySelector('[name="fullname"]').value.trim();
    const email = document.querySelector('[name="email"]').value.trim();
    const address = document.querySelector('[name="address"]').value.trim();
    const payment = document.querySelector('[name="payment"]').value.trim();
    
    console.log('Form data:', { fullname, email, address, payment });
    
    if (!fullname) {
        showMessage('Please enter your full name', 'error');
        return;
    }
    if (!email) {
        showMessage('Please enter your email', 'error');
        return;
    }
    if (!address) {
        showMessage('Please enter your shipping address', 'error');
        return;
    }
    if (!payment) {
        showMessage('Please select a payment method', 'error');
        return;
    }
    
    try {
        const response = await fetch('api_place_order.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                user_id: <?php echo $user_id; ?>,
                user_email: email,
                user_name: fullname,
                shipping_address: address,
                payment_method: payment,
                cart: <?php echo json_encode($cartItems); ?>
            })
        });
        
        // Read response as text first to avoid consuming the body twice
        const raw = await response.text();
        let data;
        // strip UTF-8 BOM if present and trim
        const cleaned = raw.replace(/^\uFEFF/, '').trim();
        try {
            data = JSON.parse(cleaned);
            console.log('api_place_order response parsed:', data);
        } catch (parseErr) {
            // If parsing failed, attempt to detect a success message in the raw body
            console.warn('Invalid JSON response from server, trying fallback detection');
            console.error('Raw response:', raw);
            // Common success marker
            if ((raw || '').indexOf('Order placed successfully') !== -1 || (raw || '').indexOf('"success":true') !== -1) {
                // try to extract order_id from JSON-like substring
                const m = raw.match(/order_id\s*[:=]\s*"?(\d+)"?/i) || raw.match(/"order_id"\s*:\s*(\d+)/i);
                const foundOrderId = m ? m[1] : '';
                // show success message and redirect after short delay
                showMessage('Order placed successfully! Order ID: #' + (foundOrderId || ''), 'success');
                // clear cart server-side (don't block UI)
                fetch('api_clear_cart.php', { method: 'POST' }).catch(()=>{});
                // show continue shopping button
                const btn = document.querySelector('.btn-place-order');
                if (btn) {
                    btn.disabled = true;
                    btn.textContent = 'Order placed — Continue shopping';
                }
                setTimeout(()=>{
                    if (foundOrderId) window.location.href = 'order_confirmation.php?order_id=' + foundOrderId;
                    else window.location.href = 'order_confirmation.php';
                }, 3000);
                return;
            }

            showMessage('Server returned invalid JSON: ' + raw, 'error');
            // re-enable button
            const btnErr = document.querySelector('.btn-place-order');
            if (btnErr) { btnErr.disabled = false; btnErr.textContent = 'Place Order'; }
            return;
        }

        if (data.success) {
            showMessage('Order placed successfully! Order ID: #' + data.order_id, 'success');
            // Disable button and change text to show order was placed
            submitBtn.disabled = true;
            submitBtn.textContent = 'Order placed — Continue shopping';
            console.log('Order successful, ID:', data.order_id);
            
            // Clear cart server-side (fire-and-forget)
            fetch('api_clear_cart.php', { method: 'POST' }).catch(err => {
                console.warn('Cart clear failed (non-blocking):', err);
            });
            
            // Wait 3 seconds so user sees the success message, then redirect
            setTimeout(() => {
                window.location.href = 'order_confirmation.php?order_id=' + data.order_id;
            }, 3000);
            return;
        } else {
            showMessage('Error: ' + (data.message || 'Failed to place order'), 'error');
            submitBtn.disabled = false;
            submitBtn.textContent = origBtnText;
        }
    } catch (error) {
        showMessage('Error: ' + error.message, 'error');
        submitBtn.disabled = false;
        submitBtn.textContent = origBtnText;
    }
});

function showMessage(msg, type) {
    const messageDiv = document.getElementById('message');
    messageDiv.innerHTML = '<div class="message ' + type + '">' + msg + '</div>';
    messageDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
</script>
</body>
</html>
