<?php
// Check if user is logged in
require_once '../includes/config.php';
require_once '../includes/functions.php';
if (!isLoggedIn()) {
    $_SESSION['redirect_after_login'] = SITE_URL . '/cart/checkout.php';
    redirect(SITE_URL . '/auth/login.php');
}

require_once '../includes/header.php';

// Get user info
$user = getUserById($pdo, $_SESSION['user_id']);

// Get cart items
$cart_items = [];
$cart_total = 0;

if (isset($_SESSION['user_id'])) {
    $cart_items = getCartItems($pdo, $_SESSION['user_id']);
    $cart_total = calculateCartTotal($cart_items);
} else {
    // Fallback to localStorage data
    $local_cart = json_decode($_COOKIE['cart'] ?? '[]', true);
    if ($local_cart) {
        foreach ($local_cart as $item) {
            $product = getProductById($pdo, $item['id']);
            if ($product) {
                $cart_items[] = [
                    'name' => $product['name'],
                    'price' => $product['price'],
                    'quantity' => $item['quantity'],
                    'image' => $product['image']
                ];
                $cart_total += $product['price'] * $item['quantity'];
            }
        }
    }
}

// Process checkout
$message = '';
$order_id = 0;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $shipping_address = sanitizeInput($_POST['shipping_address']);
    $payment_method = sanitizeInput($_POST['payment_method']);
    $payment_details = '';
    
    // Handle payment method specific details
    switch ($payment_method) {
        case 'cash_on_delivery':
            $payment_details = 'Cash on Delivery';
            break;
        case 'bank_transfer':
            $payment_details = 'Bank Transfer - ' . sanitizeInput($_POST['bank_name']);
            break;
        case 'mobile_payment':
            $payment_details = 'Mobile Payment - ' . sanitizeInput($_POST['mobile_network']) . ' - ' . sanitizeInput($_POST['mobile_number']);
            break;
        case 'credit_card':
            $payment_details = 'Credit Card';
            break;
        default:
            $payment_details = 'Payment method not specified';
    }
    
    if (empty($shipping_address)) {
        $message = '<div class="message error">Please enter a shipping address.</div>';
    } elseif (empty($payment_method)) {
        $message = '<div class="message error">Please select a payment method.</div>';
    } else {
        try {
            $order_id = createOrder($pdo, $_SESSION['user_id'], $cart_total, $shipping_address);
            
            // Save payment method to order (you might want to create a separate payments table)
            $stmt = $pdo->prepare("UPDATE orders SET payment_method = ? WHERE id = ?");
            $stmt->execute([$payment_details, $order_id]);
            
            // Send order confirmation email
            require_once '../includes/email_functions.php';
            sendOrderConfirmationEmail($pdo, $order_id);
            
            $message = '<div class="message success">Order placed successfully! Order ID: ' . $order_id . ' <a href="' . SITE_URL . '/invoice.php?id=' . $order_id . '" target="_blank" class="btn btn-small btn-outline" style="margin-left: 10px;">View Invoice</a></div>';
            
            // Clear localStorage cart
            echo '<script>localStorage.removeItem("cart");</script>';
        } catch (Exception $e) {
            $message = '<div class="message error">Error placing order. Please try again.</div>';
        }
    }
}
?>

<div class="container">
    <div class="section-title">
        <h2>Checkout</h2>
    </div>
    
    <?php echo $message; ?>
    
    <div class="checkout-content">
        <div class="checkout-form">
            <h3>Shipping Information</h3>
            <form method="POST" action="" id="checkoutForm">
                <div class="form-group">
                    <label for="name">Full Name</label>
                    <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($user['username']); ?>" readonly>
                </div>
                
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" readonly>
                </div>
                
                <div class="form-group">
                    <label for="shipping_address">Shipping Address</label>
                    <textarea id="shipping_address" name="shipping_address" rows="4" required></textarea>
                </div>
                
                <div class="form-group">
                    <label for="payment_method">Payment Method</label>
                    <select id="payment_method" name="payment_method" class="form-control" required>
                        <option value="">Select Payment Method</option>
                        <option value="cash_on_delivery">Cash on Delivery (الدفع عند الاستلام)</option>
                        <option value="bank_transfer">Bank Transfer (تحويل بنكي)</option>
                        <option value="mobile_payment">Mobile Payment (دفع عبر الهاتف)</option>
                        <option value="credit_card">Credit Card (بطاقة ائتمان)</option>
                    </select>
                </div>
                
                <!-- Bank Transfer Details -->
                <div id="bankTransferDetails" class="payment-details" style="display: none;">
                    <div class="form-group">
                        <label for="bank_name">Bank Name</label>
                        <select id="bank_name" name="bank_name" class="form-control">
                            <option value="">Select Bank</option>
                            <option value="Libya Central Bank">Libya Central Bank (البنك المركزي الليبي)</option>
                            <option value="National Commercial Bank">National Commercial Bank (البنك التجاري الوطني)</option>
                            <option value="Agricultural Bank">Agricultural Bank (البنك الزراعي)</option>
                            <option value="Development Bank">Development Bank (بنك التنمية)</option>
                            <option value="Foreign Bank">Foreign Bank (البنك الخارجي)</option>
                            <option value="Housing Bank">Housing Bank (بنك الإسكان)</option>
                            <option value="Investment Bank">Investment Bank (البنك الاستثماري)</option>
                            <option value="United Bank">United Bank (البنك المتحدة)</option>
                            <option value="Savings Bank">Savings Bank (بنك التوفير)</option>
                        </select>
                    </div>
                </div>
                
                <!-- Mobile Payment Details -->
                <div id="mobilePaymentDetails" class="payment-details" style="display: none;">
                    <div class="form-group">
                        <label for="mobile_network">Mobile Network</label>
                        <select id="mobile_network" name="mobile_network" class="form-control">
                            <option value="">Select Network</option>
                            <option value="Libyana">Libyana (ليبيانا)</option>
                            <option value="Madar">Madar (مدار)</option>
                            <option value="Al-Jeel Phone">Al-Jeel Phone (جيل فون)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="mobile_number">Mobile Number</label>
                        <input type="tel" id="mobile_number" name="mobile_number" class="form-control" placeholder="e.g., 091-XXXXXXX">
                    </div>
                </div>
                
                <!-- Credit Card Details -->
                <div id="creditCardDetails" class="payment-details" style="display: none;">
                    <div class="form-group">
                        <label for="card_number">Card Number</label>
                        <input type="text" id="card_number" name="card_number" class="form-control" placeholder="XXXX-XXXX-XXXX-XXXX">
                    </div>
                    <div class="form-group">
                        <label for="card_expiry">Expiry Date</label>
                        <input type="text" id="card_expiry" name="card_expiry" class="form-control" placeholder="MM/YY">
                    </div>
                    <div class="form-group">
                        <label for="card_cvv">CVV</label>
                        <input type="text" id="card_cvv" name="card_cvv" class="form-control" placeholder="XXX">
                    </div>
                </div>
                
                <button type="submit" class="btn btn-primary btn-large btn-block">Place Order</button>
            </form>
        </div>
        
        <div class="order-summary">
            <h3>Order Summary</h3>
            
            <?php if (count($cart_items) > 0): ?>
                <?php foreach ($cart_items as $item): ?>
                    <div class="order-item">
                        <span><?php echo htmlspecialchars($item['name']); ?> (x<?php echo $item['quantity']; ?>)</span>
                        <span>$<?php echo number_format($item['price'] * $item['quantity'], 2); ?></span>
                    </div>
                <?php endforeach; ?>
                
                <div class="order-total">
                    <span>Total</span>
                    <span>$<?php echo number_format($cart_total, 2); ?></span>
                </div>
            <?php else: ?>
                <p>Your cart is empty.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Payment method selection logic
document.addEventListener('DOMContentLoaded', function() {
    const paymentMethodSelect = document.getElementById('payment_method');
    const bankTransferDetails = document.getElementById('bankTransferDetails');
    const mobilePaymentDetails = document.getElementById('mobilePaymentDetails');
    const creditCardDetails = document.getElementById('creditCardDetails');
    
    paymentMethodSelect.addEventListener('change', function() {
        // Hide all payment details
        bankTransferDetails.style.display = 'none';
        mobilePaymentDetails.style.display = 'none';
        creditCardDetails.style.display = 'none';
        
        // Show selected payment details
        switch(this.value) {
            case 'bank_transfer':
                bankTransferDetails.style.display = 'block';
                break;
            case 'mobile_payment':
                mobilePaymentDetails.style.display = 'block';
                break;
            case 'credit_card':
                creditCardDetails.style.display = 'block';
                break;
        }
    });
    
    // Form validation
    const checkoutForm = document.getElementById('checkoutForm');
    checkoutForm.addEventListener('submit', function(e) {
        const paymentMethod = paymentMethodSelect.value;
        
        // Validate payment method specific fields
        if (paymentMethod === 'bank_transfer' && !document.getElementById('bank_name').value) {
            e.preventDefault();
            alert('Please select a bank for bank transfer.');
            return;
        }
        
        if (paymentMethod === 'mobile_payment') {
            const mobileNetwork = document.getElementById('mobile_network').value;
            const mobileNumber = document.getElementById('mobile_number').value;
            
            if (!mobileNetwork) {
                e.preventDefault();
                alert('Please select a mobile network for mobile payment.');
                return;
            }
            
            if (!mobileNumber) {
                e.preventDefault();
                alert('Please enter your mobile number for mobile payment.');
                return;
            }
        }
        
        if (paymentMethod === 'credit_card') {
            const cardNumber = document.getElementById('card_number').value;
            const cardExpiry = document.getElementById('card_expiry').value;
            const cardCvv = document.getElementById('card_cvv').value;
            
            if (!cardNumber || !cardExpiry || !cardCvv) {
                e.preventDefault();
                alert('Please fill in all credit card details.');
                return;
            }
        }
    });
});
</script>

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