<?php
require_once __DIR__ . '/includes/header.php';

// If cart is empty, redirect to shop
if (!isset($_SESSION['cart']) || empty($_SESSION['cart'])) {
    header("Location: shop.php");
    exit;
}

$cart_items = [];
$subtotal = 0;

// Fetch all product details for items in the cart
$placeholders = implode(',', array_fill(0, count($_SESSION['cart']), '?'));
try {
    $stmt = $pdo->prepare("SELECT id, name, price, image FROM products WHERE id IN ($placeholders)");
    $stmt->execute(array_keys($_SESSION['cart']));
    $db_items = $stmt->fetchAll();
    
    foreach ($db_items as $item) {
        $pid = $item['id'];
        $qty = $_SESSION['cart'][$pid];
        $item_total = $item['price'] * $qty;
        $subtotal += $item_total;
        
        $selected_size = isset($_SESSION['cart_details'][$pid]['size']) ? $_SESSION['cart_details'][$pid]['size'] : 'M';
        $selected_color = isset($_SESSION['cart_details'][$pid]['color']) ? $_SESSION['cart_details'][$pid]['color'] : 'Midnight Black';
        
        $cart_items[] = [
            'id' => $pid,
            'name' => $item['name'],
            'price' => $item['price'],
            'image' => $item['image'],
            'quantity' => $qty,
            'size' => $selected_size,
            'color' => $selected_color,
            'total' => $item_total
        ];
    }
} catch (Exception $e) {
    // Database error
}

$shipping = ($subtotal > 20000 || $subtotal == 0) ? 0 : 450;
$grand_total = $subtotal + $shipping;

$error = '';

// Process Checkout Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = isset($_POST['full_name']) ? trim($_POST['full_name']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $address = isset($_POST['address']) ? trim($_POST['address']) : '';
    $city = isset($_POST['city']) ? trim($_POST['city']) : '';
    $payment_method = isset($_POST['payment_method']) ? trim($_POST['payment_method']) : '';

    if (empty($full_name) || empty($email) || empty($phone) || empty($address) || empty($city) || empty($payment_method)) {
        $error = 'Please fill out all billing details and select your payment method.';
    } else {
        try {
            $pdo->beginTransaction();

            // 1. Create or Find User
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            $user = $stmt->fetch();

            if ($user) {
                $user_id = $user['id'];
            } else {
                // Register a new customer entry automatically
                $dummy_password = password_hash('GuestPass@123', PASSWORD_DEFAULT);
                $full_address = $address . ', ' . $city;
                
                $stmt = $pdo->prepare("INSERT INTO users (full_name, email, password, address) VALUES (?, ?, ?, ?)");
                $stmt->execute([$full_name, $email, $dummy_password, $full_address]);
                $user_id = $pdo->lastInsertId();
            }

            // 2. Insert Order
            $stmt = $pdo->prepare("INSERT INTO orders (user_id, total_amount, payment_method, status) VALUES (?, ?, ?, 'pending')");
            $stmt->execute([$user_id, $grand_total, $payment_method]);
            $order_id = $pdo->lastInsertId();

            // 3. Insert Order Items
            $stmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, quantity, price, color, size) VALUES (?, ?, ?, ?, ?, ?)");
            foreach ($cart_items as $item) {
                $stmt->execute([$order_id, $item['id'], $item['quantity'], $item['price'], $item['color'], $item['size']]);
            }

            $pdo->commit();

            // Clear Cart Session
            unset($_SESSION['cart']);
            unset($_SESSION['cart_details']);

            // Redirect to Success
            header("Location: order_success.php?order_id=" . $order_id);
            exit;

        } catch (Exception $e) {
            $pdo->rollBack();
            $error = 'Database transaction failed: ' . $e->getMessage();
        }
    }
}
?>

<!-- Banner -->
<section class="py-4 bg-black border-bottom border-dark">
    <div class="container text-center">
        <h1 class="text-white fw-bold mb-0">Secure Atelier Checkout</h1>
        <p class="text-warning small text-uppercase fw-bold mb-0 mt-1" style="letter-spacing: 2px;">Complimentary Global Concierge</p>
    </div>
</section>

<!-- Checkout Section -->
<section class="py-5" style="background-color: var(--bg-dark); min-height: 70vh;">
    <div class="container">
        
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger border-danger bg-dark text-danger rounded mb-4" role="alert">
                <i class="fa-solid fa-circle-exclamation me-2"></i> <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <form action="checkout.php" method="POST" id="checkout-form">
            <div class="row g-4">
                
                <!-- Left: Billing & Payment -->
                <div class="col-lg-7">
                    <!-- Billing Details -->
                    <div class="card bg-black border-secondary text-white p-4 rounded-4 mb-4" style="border-color: rgba(255,255,255,0.08) !important;">
                        <h4 class="fw-bold mb-4" style="font-family: var(--font-heading); color: var(--accent-gold);"><i class="fa-solid fa-user-tie me-2"></i> Guest Concierge & Delivery</h4>
                        
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="full_name" class="form-label text-muted small text-uppercase fw-bold">Full Name</label>
                                <input type="text" class="form-control bg-dark border-secondary text-white" id="full_name" name="full_name" required placeholder="Lady Seraphina">
                            </div>
                            <div class="col-md-6">
                                <label for="email" class="form-label text-muted small text-uppercase fw-bold">Email Address</label>
                                <input type="email" class="form-control bg-dark border-secondary text-white" id="email" name="email" required placeholder="seraphina@luxury.com">
                            </div>
                            <div class="col-12">
                                <label for="phone" class="form-label text-muted small text-uppercase fw-bold">Phone Hotline</label>
                                <input type="tel" class="form-control bg-dark border-secondary text-white" id="phone" name="phone" required placeholder="+94 77 123 4567">
                            </div>
                            <div class="col-12">
                                <label for="address" class="form-label text-muted small text-uppercase fw-bold">Delivery Address</label>
                                <input type="text" class="form-control bg-dark border-secondary text-white" id="address" name="address" required placeholder="Flat 4B, Cinnamon Towers, Flower Road">
                            </div>
                            <div class="col-md-6">
                                <label for="city" class="form-label text-muted small text-uppercase fw-bold">City</label>
                                <input type="text" class="form-control bg-dark border-secondary text-white" id="city" name="city" required placeholder="Colombo">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label text-muted small text-uppercase fw-bold">Postal Code</label>
                                <input type="text" class="form-control bg-dark border-secondary text-white" placeholder="00700">
                            </div>
                        </div>
                    </div>

                    <!-- Payment Gateways Integration -->
                    <div class="card bg-black border-secondary text-white p-4 rounded-4" style="border-color: rgba(255,255,255,0.08) !important;">
                        <h4 class="fw-bold mb-4" style="font-family: var(--font-heading); color: var(--accent-gold);"><i class="fa-solid fa-credit-card me-2"></i> Accepted Payment Gateways</h4>
                        
                        <p class="text-muted small mb-3">Select your preferred secure payment channel. All data processed is fully encrypted.</p>
                        
                        <div class="d-flex flex-column gap-3">
                            <!-- COD -->
                            <div class="payment-method-item p-3 border border-secondary rounded-3" style="cursor: pointer; background: rgba(255,255,255,0.02);" onclick="selectPayment('COD')">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div class="d-flex align-items-center gap-3">
                                        <input class="form-check-input" type="radio" name="payment_method" id="pay_cod" value="COD" required checked>
                                        <label class="form-check-label fw-bold" for="pay_cod">Cash On Delivery (COD)</label>
                                    </div>
                                    <span class="badge bg-dark border border-secondary text-white">COD</span>
                                </div>
                                <div class="payment-details-panel mt-3 d-block" id="panel-COD">
                                    <p class="text-muted small mb-0">Pay with physical cash upon white-glove home delivery. Please prepare exact amount.</p>
                                </div>
                            </div>

                            <!-- PayHere -->
                            <div class="payment-method-item p-3 border border-secondary rounded-3" style="cursor: pointer; background: rgba(255,255,255,0.02);" onclick="selectPayment('PayHere')">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div class="d-flex align-items-center gap-3">
                                        <input class="form-check-input" type="radio" name="payment_method" id="pay_payhere" value="PayHere">
                                        <label class="form-check-label fw-bold" for="pay_payhere">PayHere Gateway</label>
                                    </div>
                                    <span class="badge bg-dark border border-secondary text-warning">PayHere</span>
                                </div>
                                <div class="payment-details-panel mt-3 d-none" id="panel-PayHere">
                                    <p class="text-muted small mb-0">Direct checkout using PayHere payment processing gateway. Supports Visa, MasterCard, and AMEX cardholders in Sri Lanka.</p>
                                </div>
                            </div>

                            <!-- Bank Transfer -->
                            <div class="payment-method-item p-3 border border-secondary rounded-3" style="cursor: pointer; background: rgba(255,255,255,0.02);" onclick="selectPayment('Bank Transfer')">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div class="d-flex align-items-center gap-3">
                                        <input class="form-check-input" type="radio" name="payment_method" id="pay_bank" value="Bank Transfer">
                                        <label class="form-check-label fw-bold" for="pay_bank">Bank Wire Transfer</label>
                                    </div>
                                    <span class="badge bg-dark border border-secondary text-info"><i class="fa-solid fa-building-columns me-1"></i> Bank</span>
                                </div>
                                <div class="payment-details-panel mt-3 d-none" id="panel-BankTransfer">
                                    <div class="p-3 bg-dark border border-secondary rounded small">
                                        <h6 class="text-warning fw-bold mb-2">MARTLUX Corporate Vault Details:</h6>
                                        <div class="d-flex justify-content-between mb-1"><span>Bank:</span><strong class="text-white">Commercial Bank of Ceylon</strong></div>
                                        <div class="d-flex justify-content-between mb-1"><span>Account Name:</span><strong class="text-white">MARTLUX PVT LTD</strong></div>
                                        <div class="d-flex justify-content-between mb-1"><span>Account Number:</span><strong class="text-white">1009-8432-1192</strong></div>
                                        <div class="d-flex justify-content-between"><span>Branch:</span><strong class="text-white">Colombo Elite Branch</strong></div>
                                    </div>
                                    <p class="text-muted small mt-2 mb-0">Please wire funds and email receipts to <strong class="text-white">concierge@martlux.com</strong> or contact our concierge hotline at <strong class="text-warning">0777 103 470</strong> to trigger immediate shipping.</p>
                                </div>
                            </div>

                            <!-- Koko -->
                            <div class="payment-method-item p-3 border border-secondary rounded-3" style="cursor: pointer; background: rgba(255,255,255,0.02);" onclick="selectPayment('Koko')">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div class="d-flex align-items-center gap-3">
                                        <input class="form-check-input" type="radio" name="payment_method" id="pay_koko" value="Koko">
                                        <label class="form-check-label fw-bold" for="pay_koko">Koko Pay (Installments)</label>
                                    </div>
                                    <span class="badge bg-dark border border-secondary text-success fw-bold">koko</span>
                                </div>
                                <div class="payment-details-panel mt-3 d-none" id="panel-Koko">
                                    <p class="text-muted small mb-0">Split the total bill into <strong class="text-warning">3 equal interest-free installments</strong> of <strong class="text-white">LKR <?php echo number_format($grand_total / 3, 2); ?></strong> using Koko app.</p>
                                </div>
                            </div>

                            <!-- Mint Pay -->
                            <div class="payment-method-item p-3 border border-secondary rounded-3" style="cursor: pointer; background: rgba(255,255,255,0.02);" onclick="selectPayment('Mint Pay')">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div class="d-flex align-items-center gap-3">
                                        <input class="form-check-input" type="radio" name="payment_method" id="pay_mint" value="Mint Pay">
                                        <label class="form-check-label fw-bold" for="pay_mint">Mintpay Buy Now Pay Later</label>
                                    </div>
                                    <span class="badge bg-dark border border-secondary text-danger fw-bold">mintpay</span>
                                </div>
                                <div class="payment-details-panel mt-3 d-none" id="panel-MintPay">
                                    <p class="text-muted small mb-0">Get it now and split in <strong class="text-warning">3 easy installments</strong> of <strong class="text-white">LKR <?php echo number_format($grand_total / 3, 2); ?></strong> with debit or credit cards via Mintpay.</p>
                                </div>
                            </div>

                            <!-- GPay -->
                            <div class="payment-method-item p-3 border border-secondary rounded-3" style="cursor: pointer; background: rgba(255,255,255,0.02);" onclick="selectPayment('GPay')">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div class="d-flex align-items-center gap-3">
                                        <input class="form-check-input" type="radio" name="payment_method" id="pay_gpay" value="GPay">
                                        <label class="form-check-label fw-bold" for="pay_gpay">Google Pay (GPay)</label>
                                    </div>
                                    <span class="badge bg-dark border border-secondary text-primary"><i class="fa-brands fa-google-pay fs-5"></i></span>
                                </div>
                                <div class="payment-details-panel mt-3 d-none" id="panel-GPay">
                                    <p class="text-muted small mb-0">Use your Google Wallet for seamless, secure single-tap payment integration.</p>
                                </div>
                            </div>

                            <!-- PayPal -->
                            <div class="payment-method-item p-3 border border-secondary rounded-3" style="cursor: pointer; background: rgba(255,255,255,0.02);" onclick="selectPayment('PayPal')">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div class="d-flex align-items-center gap-3">
                                        <input class="form-check-input" type="radio" name="payment_method" id="pay_paypal" value="PayPal">
                                        <label class="form-check-label fw-bold" for="pay_paypal">PayPal Secure Gateway</label>
                                    </div>
                                    <span class="badge bg-dark border border-secondary text-primary"><i class="fa-brands fa-paypal me-1"></i>PayPal</span>
                                </div>
                                <div class="payment-details-panel mt-3 d-none" id="panel-PayPal">
                                    <p class="text-muted small mb-0">Check out instantly and securely using your global PayPal balance or linked international bank accounts.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Right: Order Summary -->
                <div class="col-lg-5">
                    <div class="card bg-black border-secondary text-white p-4 rounded-4 position-sticky" style="border-color: rgba(255,255,255,0.08) !important; top: 110px;">
                        <h4 class="fw-bold mb-4" style="font-family: var(--font-heading); color: var(--accent-gold);"><i class="fa-solid fa-receipt me-2"></i> Bag Summary</h4>
                        
                        <!-- Items list -->
                        <div class="d-flex flex-column gap-3 mb-4 max-height-300" style="overflow-y: auto; max-height: 280px; padding-right: 10px;">
                            <?php foreach ($cart_items as $item): ?>
                                <div class="d-flex justify-content-between align-items-center">
                                    <div class="d-flex align-items-center gap-3">
                                        <img src="assets/images/<?php echo htmlspecialchars($item['image']); ?>" alt="<?php echo htmlspecialchars($item['name']); ?>" class="rounded" style="width: 50px; height: 50px; object-fit: cover; border: 1px solid rgba(255,255,255,0.1);">
                                        <div>
                                            <span class="fw-bold small d-block"><?php echo htmlspecialchars($item['name']); ?></span>
                                            <span class="text-muted small">Qty: <?php echo $item['quantity']; ?></span>
                                        </div>
                                    </div>
                                    <span class="small fw-semibold">LKR <?php echo number_format($item['total'], 2); ?></span>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <hr class="border-secondary opacity-25 mb-3">

                        <!-- Subtotal -->
                        <div class="d-flex justify-content-between mb-2 small text-muted">
                            <span>Subtotal</span>
                            <span>LKR <?php echo number_format($subtotal, 2); ?></span>
                        </div>
                        
                        <!-- Shipping -->
                        <div class="d-flex justify-content-between mb-4 small text-muted">
                            <span>Bespoke Shipping</span>
                            <span>
                                <?php if ($shipping == 0): ?>
                                    <span class="text-warning">Complimentary</span>
                                <?php else: ?>
                                    LKR <?php echo number_format($shipping, 2); ?>
                                <?php endif; ?>
                            </span>
                        </div>

                        <hr class="border-secondary opacity-25 mb-4">
                        
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <span class="fw-bold">Total Couture Amount</span>
                            <span class="text-warning fw-bold fs-4">LKR <?php echo number_format($grand_total, 2); ?></span>
                        </div>

                        <!-- CTA button -->
                        <button type="submit" class="btn btn-warning py-3 text-black w-100 rounded-pill fw-bold text-uppercase fs-7 shadow" style="letter-spacing: 1px;">
                            Place Luxury Order <i class="fa-solid fa-lock ms-2"></i>
                        </button>
                        
                        <div class="text-center mt-3 text-muted small">
                            <i class="fa-solid fa-shield-halved text-warning me-1"></i> SSL Encrypted & PCI Compliant
                        </div>
                    </div>
                </div>

            </div>
        </form>
    </div>
</section>

<!-- Payment Selector Script -->
<script>
function selectPayment(method) {
    // 1. Uncheck all other radio inputs, check the selected one
    const radios = document.getElementsByName('payment_method');
    for (let i = 0; i < radios.length; i++) {
        if (radios[i].value === method) {
            radios[i].checked = true;
        }
    }

    // 2. Hide all panels
    const panels = document.querySelectorAll('.payment-details-panel');
    panels.forEach(p => {
        p.classList.remove('d-block');
        p.classList.add('d-none');
    });

    // 3. Highlight/Select item border
    const items = document.querySelectorAll('.payment-method-item');
    items.forEach(item => {
        item.style.borderColor = 'rgba(255, 255, 255, 0.15)';
        item.style.background = 'rgba(255, 255, 255, 0.02)';
    });

    // 4. Find selected item and show panel
    let targetPanelId = '';
    if (method === 'COD') targetPanelId = 'panel-COD';
    else if (method === 'PayHere') targetPanelId = 'panel-PayHere';
    else if (method === 'Bank Transfer') targetPanelId = 'panel-BankTransfer';
    else if (method === 'Koko') targetPanelId = 'panel-Koko';
    else if (method === 'Mint Pay') targetPanelId = 'panel-MintPay';
    else if (method === 'GPay') targetPanelId = 'panel-GPay';
    else if (method === 'PayPal') targetPanelId = 'panel-PayPal';

    const selectedPanel = document.getElementById(targetPanelId);
    if (selectedPanel) {
        selectedPanel.classList.remove('d-none');
        selectedPanel.classList.add('d-block');
    }

    // Highlight outer block
    const radio = document.querySelector(`input[value="${method}"]`);
    const parentBlock = radio.closest('.payment-method-item');
    parentBlock.style.borderColor = '#DCC7A3';
    parentBlock.style.background = 'rgba(220, 199, 163, 0.03)';
}

// Attach initial trigger on DOM ready
document.addEventListener('DOMContentLoaded', () => {
    selectPayment('COD');
});
</script>

<?php
require_once __DIR__ . '/includes/footer.php';
?>
