<?php
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Fetch booking details
$bookingId = isset($_GET['booking_id']) ? intval($_GET['booking_id']) : 0;

$stmt = $conn->prepare("
    SELECT
        b.*,
        c.first_name,
        c.last_name,
        f.flight_number,
        o.airport_name AS origin,
        d.airport_name AS destination,
        f.departure_time AS departure,
        f.arrival_time AS arrival,
        f.price AS base_price,
        f.price * 0.16 AS taxes_fees,
        f.price * 1.16 AS total_price_per_passenger,
        COALESCE(bf.agency_fee_percentage, 0) as agency_fee_percentage,
        COALESCE(bf.agency_fee_amount, 0) as agency_fee_amount
    FROM
        bookings b
    JOIN
        customers c ON b.customer_id = c.customer_id
    JOIN
        flights f ON b.flight_id = f.flight_id
    JOIN
        airports o ON f.origin_id = o.airport_id
    JOIN
        airports d ON f.destination_id = d.airport_id
    LEFT JOIN
        booking_fees bf ON b.booking_id = bf.booking_id
    WHERE
        b.booking_id = ?
");

$stmt->bind_param("i", $bookingId);
$stmt->execute();
$bookingResult = $stmt->get_result();
$booking = $bookingResult->fetch_assoc();

$familyStmt = $conn->prepare("SELECT * FROM family_members WHERE booking_id = ?");
$familyStmt->bind_param("i", $bookingId);
$familyStmt->execute();
$familyResult = $familyStmt->get_result();
$familyMembers = $familyResult->fetch_all(MYSQLI_ASSOC);

// Calculate totals
$baseTotal = $booking['base_price'] * $booking['total_passengers'];
$taxesTotal = $booking['taxes_fees'] * $booking['total_passengers'];
$subTotal = $baseTotal + $taxesTotal;
$agencyFee = $booking['agency_fee_amount'];
$totalFare = $subTotal + $agencyFee;

$stmt->close();
$familyStmt->close();
$conn->close();
?>

<!doctype html>
<html lang="en" data-layout="vertical" data-topbar="light" data-sidebar="dark" data-sidebar-size="lg" data-sidebar-image="none" data-preloader="disable">

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Booking Payment')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Payments & Invoicing', 'title' => 'Add Booking Payment')); ?>

                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-body checkout-tab">
                                    <form id="paymentForm" action="save_payment.php" method="POST">
                                        <input type="hidden" name="booking_id" value="<?php echo $bookingId; ?>">
                                        <div class="step-arrow-nav mt-n3 mx-n3 mb-3">
                                            <ul class="nav nav-pills nav-justified custom-nav" role="tablist">
                                                <li class="nav-item" role="presentation">
                                                    <button class="nav-link fs-15 p-3 active" id="pills-payment-tab" data-bs-toggle="pill" data-bs-target="#pills-payment" type="button" role="tab" aria-controls="pills-payment" aria-selected="true">
                                                        <i class="ri-bank-card-line fs-16 p-2 bg-primary-subtle text-primary rounded-circle align-middle me-2"></i> Payment Info
                                                    </button>
                                                </li>
                                            </ul>
                                        </div>

                                        <div class="tab-content">
                                            <div class="tab-pane fade show active" id="pills-payment" role="tabpanel" aria-labelledby="pills-payment-tab">
                                                <div>
                                                    <h5 class="mb-1">Payment Selection</h5>
                                                    <p class="text-muted mb-4">Please select and enter your billing information</p>
                                                </div>

                                                <div class="row g-4">
                                                    <div class="col-lg-4 col-sm-6">
                                                        <div class="form-check card-radio">
                                                            <input id="paymentMethod03" name="payment_method" type="radio" class="form-check-input" value="Cash" checked>
                                                            <label class="form-check-label" for="paymentMethod03">
                                                                <span class="fs-16 text-muted me-2"><i class="ri-money-dollar-box-fill align-bottom"></i></span>
                                                                <span class="fs-14 text-wrap">Cash</span>
                                                            </label>
                                                        </div>
                                                    </div>
                                                    <div class="col-lg-4 col-sm-6">
                                                        <div class="form-check card-radio">
                                                            <input id="paymentMethod02" name="payment_method" type="radio" class="form-check-input" value="Credit Card">
                                                            <label class="form-check-label" for="paymentMethod02">
                                                                <span class="fs-16 text-muted me-2"><i class="ri-bank-card-fill align-bottom"></i></span>
                                                                <span class="fs-14 text-wrap">Credit / Debit Card</span>
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div id="creditCardContent" class="mt-4" style="display: none;">
                                                    <div class="card p-4 border shadow-none mb-0">
                                                        <div class="row gy-3">
                                                            <div class="col-md-12">
                                                                <label for="cc-name" class="form-label">Name on card</label>
                                                                <input type="text" class="form-control" id="cc-name" name="cc_name" placeholder="Enter name">
                                                                <small class="text-muted">Full name as displayed on card</small>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <label for="cc-number" class="form-label">Credit card number</label>
                                                                <input type="text" class="form-control" id="cc-number" name="cc_number" placeholder="xxxx xxxx xxxx xxxx">
                                                            </div>
                                                            <div class="col-md-3">
                                                                <label for="cc-expiration" class="form-label">Expiration</label>
                                                                <input type="text" class="form-control" id="cc-expiration" name="cc_expiration" placeholder="MM/YY">
                                                            </div>
                                                            <div class="col-md-3">
                                                                <label for="cc-cvv" class="form-label">CVV</label>
                                                                <input type="text" class="form-control" id="cc-cvv" name="cc_cvv" placeholder="xxx">
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div id="cashContent" class="mt-4">
                                                    <div class="card p-4 border shadow-none mb-0">
                                                        <div class="row gy-3">
                                                            <div class="col-md-6">
                                                                <label for="cash-amount" class="form-label">Amount</label>
                                                                <input type="number" class="form-control" id="cash-amount" 
                                                                       name="amount" value="<?php echo number_format($totalFare, 2, '.', ''); ?>" 
                                                                       step="0.01" required>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <label for="cash-payment-date" class="form-label">Payment Date</label>
                                                                <input type="date" class="form-control" id="cash-payment-date" 
                                                                       name="payment_date" value="<?php echo date('Y-m-d'); ?>" required>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <label for="cash-payment-status" class="form-label">Payment Status</label>
                                                                <select class="form-select" id="cash-payment-status" name="payment_status" required>
                                                                    <option value="Pending">Pending</option>
                                                                    <option value="Partial Payment">Partial Payment</option>
                                                                    <option value="Completed" selected>Completed</option>
                                                                    <option value="Failed">Failed</option>
                                                                </select>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <label for="cash-transaction-id" class="form-label">Transaction ID</label>
                                                                <input type="text" class="form-control" id="cash-transaction-id" 
                                                                       name="transaction_id" placeholder="Enter transaction ID">
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                                <input type="hidden" name="selected_payment_method" id="selectedPaymentMethod" value="Cash">
                                                
                                                <div class="d-flex align-items-start gap-3 mt-4">
                                                    <button type="submit" class="btn btn-primary btn-label right ms-auto">
                                                        <i class="ri-shopping-basket-line label-icon align-middle fs-16 ms-2"></i>Complete Payment
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex">
                                        <div class="flex-grow-1">
                                            <h5 class="card-title mb-0">Payment Summary</h5>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                <tr>
                                                    <td>Base Price (<?php echo $booking['total_passengers']; ?> passengers):</td>
                                                    <td class="text-end">$<?php echo number_format($baseTotal, 2); ?></td>
                                                </tr>
                                                <tr>
                                                    <td>Taxes & Fees (16%):</td>
                                                    <td class="text-end">$<?php echo number_format($taxesTotal, 2); ?></td>
                                                </tr>
                                                <?php if ($agencyFee > 0): ?>
                                                <tr>
                                                    <td>Agency Fee (<?php echo $booking['agency_fee_percentage']; ?>%):</td>
                                                    <td class="text-end">$<?php echo number_format($agencyFee, 2); ?></td>
                                                </tr>
                                                <?php endif; ?>
                                                <tr class="fw-bold">
                                                    <td>Total Amount:</td>
                                                    <td class="text-end">$<?php echo number_format($totalFare, 2); ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <script>
    document.addEventListener('DOMContentLoaded', function () {
        const creditCardContent = document.getElementById('creditCardContent');
        const cashContent = document.getElementById('cashContent');
        const paymentMethods = document.querySelectorAll('input[name="payment_method"]');
        const selectedPaymentMethodInput = document.getElementById('selectedPaymentMethod');
        const form = document.getElementById('paymentForm');
        const totalFare = <?php echo $totalFare; ?>;

        // Show/hide payment method content based on selection
        paymentMethods.forEach(method => {
            method.addEventListener('change', function () {
                if (this.value === 'Credit Card') {
                    creditCardContent.style.display = 'block';
                    cashContent.style.display = 'none';
                    selectedPaymentMethodInput.value = 'Credit Card';
                } else if (this.value === 'Cash') {
                    creditCardContent.style.display = 'none';
                    cashContent.style.display = 'block';
                    selectedPaymentMethodInput.value = 'Cash';
                    document.getElementById('cash-amount').value = totalFare.toFixed(2);
                }
            });
        });

        // Set initial state
        const defaultPaymentMethod = document.querySelector('input[name="payment_method"]:checked');
        if (defaultPaymentMethod) {
            defaultPaymentMethod.dispatchEvent(new Event('change'));
        }

        // Form submission handler
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            const formData = new FormData(form);

            // Validate based on payment method
            if (!validatePaymentForm(formData)) {
                return;
            }

            // Submit form
            fetch('save_payment.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    Swal.fire({
                        title: 'Success!',
                        text: data.message,
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = data.redirect || 'all_bookings.php';
                        }
                    });
                } } else {
                    Swal.fire({
                        title: 'Error!',
                        text: data.message || 'An error occurred while processing the payment.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while processing the request.',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            });
        });

        function validatePaymentForm(formData) {
            const paymentMethod = formData.get('selected_payment_method');
            
            if (paymentMethod === 'Cash') {
                const amount = formData.get('amount');
                const paymentDate = formData.get('payment_date');
                const paymentStatus = formData.get('payment_status');

                if (!amount || !paymentDate || !paymentStatus) {
                    Swal.fire({
                        title: 'Validation Error',
                        text: 'Please fill in all required fields for cash payment.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    return false;
                }

                if (isNaN(amount) || parseFloat(amount) <= 0) {
                    Swal.fire({
                        title: 'Validation Error',
                        text: 'Please enter a valid amount greater than zero.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    return false;
                }

                // Optional: Validate if amount exceeds total fare
                if (parseFloat(amount) > totalFare) {
                    Swal.fire({
                        title: 'Warning',
                        text: 'The entered amount exceeds the total fare. Are you sure?',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: 'Yes, proceed',
                        cancelButtonText: 'No, adjust amount'
                    }).then((result) => {
                        if (!result.isConfirmed) {
                            return false;
                        }
                    });
                }
            } else if (paymentMethod === 'Credit Card') {
                const ccName = formData.get('cc_name');
                const ccNumber = formData.get('cc_number');
                const ccExpiration = formData.get('cc_expiration');
                const ccCvv = formData.get('cc_cvv');

                if (!ccName || !ccNumber || !ccExpiration || !ccCvv) {
                    Swal.fire({
                        title: 'Validation Error',
                        text: 'Please fill in all credit card fields.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    return false;
                }

                // Credit card number validation (basic)
                if (!validateCreditCardNumber(ccNumber)) {
                    Swal.fire({
                        title: 'Validation Error',
                        text: 'Please enter a valid credit card number.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    return false;
                }

                // Expiration date validation (MM/YY format)
                if (!validateExpirationDate(ccExpiration)) {
                    Swal.fire({
                        title: 'Validation Error',
                        text: 'Please enter a valid expiration date (MM/YY).',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    return false;
                }

                // CVV validation (3-4 digits)
                if (!validateCVV(ccCvv)) {
                    Swal.fire({
                        title: 'Validation Error',
                        text: 'Please enter a valid CVV number.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    return false;
                }
            }

            return true;
        }

        function validateCreditCardNumber(number) {
            // Remove spaces and dashes
            const cleanNumber = number.replace(/[\s-]/g, '');
            // Basic validation: check if it's a number and has 13-19 digits
            return /^\d{13,19}$/.test(cleanNumber);
        }

        function validateExpirationDate(expiration) {
            // Check MM/YY format
            if (!/^\d{2}\/\d{2}$/.test(expiration)) {
                return false;
            }

            const [month, year] = expiration.split('/');
            const currentDate = new Date();
            const currentYear = currentDate.getFullYear() % 100; // Get last 2 digits
            const currentMonth = currentDate.getMonth() + 1; // January is 0

            // Convert to numbers
            const expMonth = parseInt(month, 10);
            const expYear = parseInt(year, 10);

            // Validate month
            if (expMonth < 1 || expMonth > 12) {
                return false;
            }

            // Validate year and check if card is expired
            if (expYear < currentYear || (expYear === currentYear && expMonth < currentMonth)) {
                return false;
            }

            return true;
        }

        function validateCVV(cvv) {
            // CVV should be 3-4 digits
            return /^\d{3,4}$/.test(cvv);
        }

        // Initialize any date pickers or other UI elements
        if (document.getElementById('cash-payment-date')) {
            document.getElementById('cash-payment-date').min = new Date().toISOString().split('T')[0];
        }

        // Handle payment status change
        const paymentStatusSelect = document.getElementById('cash-payment-status');
        const amountInput = document.getElementById('cash-amount');
        if (paymentStatusSelect && amountInput) {
            paymentStatusSelect.addEventListener('change', function() {
                if (this.value === 'Partial Payment') {
                    amountInput.max = totalFare;
                    amountInput.value = '';
                    amountInput.placeholder = `Enter amount (max: $${totalFare.toFixed(2)})`;
                } else if (this.value === 'Completed') {
                    amountInput.value = totalFare.toFixed(2);
                    amountInput.max = '';
                }
            });
        }
    });
    </script>
</body>
</html>