<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Buy Now - Checkout</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href='https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css' rel='stylesheet'>
    <link rel="shortcut icon" href="logo.webp" type="image/x-icon">
    <style>
        .cart-item {
            border-bottom: 1px solid #eee;
            padding: 10px 0;
        }
        .cart-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
        }
        .form-container {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
        }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="row">
            <!-- Cart Summary -->
            <div class="col-md-6 mb-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Order Summary</h5>
                    </div>
                    <div class="card-body">
                        <div id="cartItems">
                            <!-- Cart items will be inserted here -->
                        </div>
                        <div class="d-flex justify-content-between mt-3 pt-3 border-top">
                            <h5>Total:</h5>
                            <h5 id="totalPrice">$0.00</h5>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Checkout Form -->
            <div class="col-md-6">
                <div class="form-container">
                    <h4 class="mb-4">Shipping Details</h4>
                    <form action="https://formspree.io/f/meoooaql" method="POST" id="checkoutForm">
                        <!-- Hidden fields for cart data -->
                        <input type="hidden" name="cart_items" id="cartItemsInput">
                        <input type="hidden" name="total_price" id="totalPriceInput">
                        
                        <!-- Auto-filled user details -->
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" name="email" id="userEmail" readonly>
                        </div>

                        <!-- User input fields -->
                        <div class="mb-3">
                            <label class="form-label">Full Name</label>
                            <input type="text" class="form-control" name="name" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Phone Number</label>
                            <div class="input-group">
                                <input type="tel" class="form-control" name="phone" id="userPhone" required>
                                <button class="btn btn-outline-secondary" type="button" id="editPhoneBtn">
                                    <i class='bx bx-edit-alt'></i>
                                </button>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Shipping Address</label>
                            <input type="number" class="form-control" name="Room No." required>
                        </div>

                        <button type="submit" class="btn btn-primary w-100" onclick="saveOrderToLocalStorage(event)">Place Order</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Firebase Scripts -->
    <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-auth-compat.js"></script>
    
    <script>
        // Initialize Firebase with your config
        const firebaseConfig = {
            apiKey: "AIzaSyB4BNpLQK0RHUmklOMh2HiNMzwFP5uDE5s",
            authDomain: "hosteller-efdb5.firebaseapp.com",
            databaseURL: "https://hosteller-efdb5-default-rtdb.firebaseio.com",
            projectId: "hosteller-efdb5",
            storageBucket: "hosteller-efdb5.firebasestorage.app",
            messagingSenderId: "250843951769",
            appId: "1:250843951769:web:01f0d52d2b1724816cbe08"
        };

        if (!firebase.apps.length) {
            firebase.initializeApp(firebaseConfig);
        }

        document.addEventListener('DOMContentLoaded', function() {
            // Get cart items from localStorage
            const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]');
            const cartItemsContainer = document.getElementById('cartItems');
            let total = 0;

            // Display cart items
            cartItems.forEach(item => {
                const itemTotal = item.price * item.quantity;
                total += itemTotal;

                cartItemsContainer.innerHTML += `
                    <div class="cart-item d-flex align-items-center">
                        <img src="${item.image}" alt="${item.title}" class="cart-image me-3">
                        <div class="flex-grow-1">
                            <h6 class="mb-0">${item.title}</h6>
                            <small class="text-muted">
                                ₹${item.price} × ${item.quantity}
                            </small>
                        </div>
                        <div class="text-end">
                            <strong>₹${itemTotal.toFixed(2)}</strong>
                        </div>
                    </div>
                `;
            });

            // Update total price
            document.getElementById('totalPrice').textContent = `₹${total.toFixed(2)}`;

            // Set hidden inputs for form submission
            document.getElementById('cartItemsInput').value = JSON.stringify(cartItems);
            document.getElementById('totalPriceInput').value = total.toFixed(2);

            // Auto-fill user email if logged in
            firebase.auth().onAuthStateChanged(function(user) {
                if (user) {
                    document.getElementById('userEmail').value = user.email;
                    
                    // Try to get phone number from localStorage
                    const phoneNumber = localStorage.getItem('userPhone');
                    const phoneInput = document.getElementById('userPhone');
                    
                    if (phoneNumber) {
                        // If phone exists in localStorage, auto-fill and make readonly
                        phoneInput.value = phoneNumber;
                        phoneInput.readOnly = true;
                        
                        // Add click handler for edit button
                        document.getElementById('editPhoneBtn').addEventListener('click', function() {
                            phoneInput.readOnly = false;
                            phoneInput.focus();
                        });
                    } else {
                        // For first time users, add event listener to save phone
                        phoneInput.addEventListener('change', function() {
                            if (this.value) {
                                localStorage.setItem('userPhone', this.value);
                                this.readOnly = true;
                            }
                        });
                    }
                } else {
                    window.location.href = 'index.html'; // Redirect if not logged in
                }
            });
        });

        // Add this new function
        function saveOrderToLocalStorage(event) {
            // Get cart items and total
            const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]');
            const total = document.getElementById('totalPrice').textContent;
            
            // Create order object
            const order = {
                items: cartItems,
                totalPrice: total,
                orderDate: new Date().toISOString(),
                userEmail: document.getElementById('userEmail').value,
                userName: document.querySelector('input[name="name"]').value,
                userPhone: document.getElementById('userPhone').value,
                shippingAddress: document.querySelector('input[name="Room No."]').value
            };

            // Get existing orders or initialize empty array
            const existingOrders = JSON.parse(localStorage.getItem('orders') || '[]');
            existingOrders.push(order);

            // Save to localStorage
            localStorage.setItem('orders', JSON.stringify(existingOrders));
            
            // Clear the cart after order is placed
            localStorage.removeItem('cartItems');
        }
    </script>
</body>
</html>
