<?php include 'layouts/session.php'; ?>
<?php include 'layouts/main.php'; ?>
<?php include 'layouts/dbconn.php'; ?>
<?php
include 'PricingEngine.php'; // Include your pricing engine

// Fetch airports (Assuming you have an airports table)
$airports = $conn->query("SELECT airport_id, airport_name FROM airports")->fetch_all(MYSQLI_ASSOC);

// Fetch flights
$flights = $conn->query("SELECT flight_id, flight_number FROM flights")->fetch_all(MYSQLI_ASSOC);

// Fetch customers
$customers = $conn->query("SELECT customer_id, first_name, last_name FROM customers")->fetch_all(MYSQLI_ASSOC);

// Set user_id from session or default to 1
$userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 1; // Replace with actual session variable name


// Initialize price variable
$finalPrice = '';
$basePrice = '';

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['flight_number'])) {
    $flightNumber = $_POST['flight_number'];
    // Query to get the flight details
    $result = $conn->query("SELECT price FROM flights WHERE flight_number = '$flightNumber'");
    if ($result->num_rows > 0) {
        $flight = $result->fetch_assoc();
        $basePrice = $flight['price'];
        // Initialize Pricing Engine
        $pricingEngine = new PricingEngine($basePrice);
        // Calculate both prices
        $finalPrice = $pricingEngine->calculateFinalPrice();
        $basePrice = $pricingEngine->getBasePrice();
        
        echo "Base Price (no taxes or discounts): " . $pricing->getBasePrice();
    } else {
        $finalPrice = '0.00';
        $basePrice = '0.00';
    }
} else {
    $finalPrice = '';
    $basePrice = '';
}
?>


<head>

    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Booking')); ?>

    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />

    <?php include 'layouts/head-css.php'; ?>
    
    <style>
    .form-icon {
        display: flex;
        align-items: center;
    }
    
    .js-example-basic-single {
        flex-grow: 1;
    }
    
    .btn-sm {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
        line-height: 1.5;
        border-radius: 0.2rem;
    }
</style>

</head>

<body>

    <!-- Begin page -->
    <div id="layout-wrapper">

        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">

            <div class="page-content">
                <div class="container-fluid">

                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Bookings Management', 'title' => 'Create Booking')); ?>


                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Create Booking</h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST" action="save_booking.php" id="bookingForm">
                                        <div class="live-preview">
                                            <div class="row gy-4">
                                                <!-- Flight Number -->
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="flightId" class="form-label">Flight Number</label>
                                                        <div class="form-icon">
                                                            <i class="ri-plane-line"></i>
                                                            <select class="js-example-basic-single" id="flightId" name="flight_id" required>
                                                                <option value="">Select a Flight</option>
                                                                <?php foreach ($flights as $flight): ?>
                                                                    <option value="<?php echo $flight['flight_id']; ?>"><?php echo $flight['flight_number']; ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                            
                                                        </div>
                                                    </div>
                                                </div>
                                    
                                                <!-- Customer ID -->
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="customerId" class="form-label">Customer</label>
                                                        <div class="form-icon d-flex align-items-center">
                                                            <select class="js-example-basic-single flex-grow-1" id="customerId" name="customer_id" required>
                                                                <option value="">Select a Customer</option>
                                                                <?php foreach ($customers as $customer): ?>
                                                                    <option value="<?php echo $customer['customer_id']; ?>"><?php echo $customer['first_name']; ?> <?php echo $customer['last_name']; ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                            <button type="button" class="btn btn-primary btn-sm ms-2" data-bs-toggle="modal" data-bs-target="#customerModal">
                                                                +
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <!-- User ID (default to session or 1) -->
                                                <input type="hidden" name="user_id" value="<?php echo $userId; ?>">
                                    
                                                <!-- Promotion ID (optional) -->
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="promotionId" class="form-label">Promotion ID (Optional)</label>
                                                        <div class="form-icon">
                                                            <input type="number" class="form-control form-control-icon" id="promotionId" name="promotion_id">
                                                            <i class="ri-gift-line"></i>
                                                        </div>
                                                    </div>
                                                </div>
                                    
                                                <!-- Flight Price -->
                                    
                                                
                                        <div class="col-xxl-4 col-md-6">
                                            <div>
                                                <label for="basePrice" class="form-label">Flight Base Fare</label>
                                                <div class="form-icon">
                                                    <input type="text" class="form-control form-control-icon" id="basePrice" name="base_price" value="<?php echo isset($_SESSION['basePrice']) ? $_SESSION['basePrice'] : ''; ?>" readonly>
                                                    <i class="ri-money-dollar-circle-line"></i>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-xxl-4 col-md-6">
                                            <div>
                                                <label for="flightPrice" class="form-label">Flight Net Fare</label>
                                                <div class="form-icon">
                                                    <input type="text" class="form-control form-control-icon" id="flightPrice" name="price" value="<?php echo $finalPrice; ?>" readonly>
                                                    <i class="ri-money-dollar-circle-line"></i>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-xxl-4 col-md-6">
                                            <div>
                                                <label for="agencyFeePercentage" class="form-label">Agency Fee (%)</label>
                                                <div class="form-icon">
                                                    <input type="number" step="0.01" min="0" max="100" class="form-control form-control-icon" 
                                                           id="agencyFeePercentage" name="agency_fee_percentage" value="3.00">
                                                    <i class="ri-percent-line"></i>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-xxl-4 col-md-6">
                                            <div>
                                                <label for="agencyFeeAmount" class="form-label">Agency Fee Amount</label>
                                                <div class="form-icon">
                                                    <input type="text" class="form-control form-control-icon" id="agencyFeeAmount" 
                                                           name="agency_fee_amount" readonly>
                                                    <i class="ri-money-dollar-circle-line"></i>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-xxl-4 col-md-6">
                                            <div>
                                                <label for="totalWithFees" class="form-label">Total Amount (incl. Agency Fees)</label>
                                                <div class="form-icon">
                                                    <input type="text" class="form-control form-control-icon" id="totalWithFees" 
                                                           name="total_with_fees" readonly>
                                                    <i class="ri-money-dollar-circle-line"></i>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- Status -->
                                        <div class="col-xxl-4 col-md-6">
                                            <div>
                                                <label for="status" class="form-label">Status</label>
                                                <div class="form-icon">
                                                    <select class="js-example-basic-single" id="status" name="status" required>
                                                        <option value="">Please select a Status</option>
                                                        <option value="Booked">Booked</option>
                                                        <option value="Cancelled">Cancelled</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Family Members Section -->
                                            <div class="col-xxl-12">
                                                <h4>Family Members</h4>
                                                <div class="accordion custom-accordionwithicon" id="familyMembersAccordion">
                                                    <!-- Family members will be added here dynamically -->
                                                </div>
                                                <button type="button" class="btn btn-primary mt-3" id="addFamilyMemberBtn">Add Family Member</button>
                                            </div>
                                            
                                                        <!-- Submit Button -->
                                                        <div class="col-xxl-4 col-md-6">
                                                            <div>
                                                                <button type="submit" class="btn btn-success btn-label waves-effect waves-light rounded-pill">
                                                                    <i class="ri-check-double-line label-icon align-middle rounded-pill fs-16 me-2"></i> Save Booking
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </form>
                                </div>
                            </div>
                        </div>
                    </div><!--end row-->


                    

                </div>
                <!-- container-fluid -->
                <!-- Modal -->
            <div class="modal fade" id="customerModal" tabindex="-1" aria-labelledby="customerModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="customerModalLabel">Add New Customer</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="newCustomerForm">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="firstName" class="form-label">First Name</label>
                                            <input type="text" class="form-control" id="firstName" name="first_name" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="email" class="form-label">Email</label>
                                            <input type="email" class="form-control" id="email" name="email" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="address" class="form-label">Address</label>
                                            <textarea class="form-control" id="address" name="address"></textarea>
                                        </div>
                                        <div class="mb-3">
                                            <label for="country" class="form-label">Country</label>
                                            <input type="text" class="form-control" id="country" name="country">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="lastName" class="form-label">Last Name</label>
                                            <input type="text" class="form-control" id="lastName" name="last_name" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="phoneNumber" class="form-label">Phone Number</label>
                                            <input type="text" class="form-control" id="phoneNumber" name="phone_number">
                                        </div>
                                        <div class="mb-3">
                                            <label for="passportNumber" class="form-label">Passport Number</label>
                                            <input type="text" class="form-control" id="passportNumber" name="passport">
                                        </div>
                                        <div class="mb-3">
                                            <label for="city" class="form-label">City</label>
                                            <input type="text" class="form-control" id="city" name="city">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-12">
                                        <button type="submit" class="btn btn-success btn-label waves-effect waves-light rounded-pill">
                                            <i class="ri-check-double-line label-icon align-middle rounded-pill fs-16 me-2"></i> Save Customer
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->

    </div>
    <!-- END layout-wrapper -->


    <?php include 'layouts/vendor-scripts.php'; ?>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <!--select2 cdn-->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
        <!-- Sweet Alerts js -->
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <!-- Sweet alert init js-->
    <script src="assets/js/pages/sweetalerts.init.js"></script>
    <script src="assets/js/pages/select2.init.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    // Initialize Select2 on both dropdowns
    $('#originAirport').select2();
    $('#destinationAirport').select2();

    // Get both dropdowns
    const originSelect = document.getElementById('originAirport');
    const destinationSelect = document.getElementById('destinationAirport');

    // Ensure both dropdown elements are present
    if (!originSelect || !destinationSelect) return;

    // Helper function to disable the selected option in the opposite dropdown
    function disableSelectedOption(selectElement, valueToDisable) {
        Array.from(selectElement.options).forEach(option => {
            option.disabled = option.value === valueToDisable;
        });

        // Refresh Select2 to reflect changes
        $('#' + selectElement.id).select2();
    }

    // Function to check for duplicate selections and reset if necessary
    function checkForDuplicates() {
        const selectedOrigin = originSelect.value;
        const selectedDestination = destinationSelect.value;

        if (selectedOrigin === selectedDestination && selectedOrigin !== "") {
            alert("Origin and Destination cannot be the same. Please select a different option.");
            destinationSelect.value = "";
            $('#destinationAirport').val("").trigger('change');
        }
    }

    // Event listener for Origin dropdown changes
    $('#originAirport').on('change', function () {
        const selectedOrigin = originSelect.value;

        // Reset all options in the Destination dropdown
        Array.from(destinationSelect.options).forEach(option => option.disabled = false);

        // Disable the selected origin airport in the destination dropdown
        if (selectedOrigin) {
            disableSelectedOption(destinationSelect, selectedOrigin);
        }

        // Check for duplicates after processing
        checkForDuplicates();
    });

    // Event listener for Destination dropdown changes
    $('#destinationAirport').on('change', function () {
        const selectedDestination = destinationSelect.value;

        // Reset all options in the Origin dropdown
        Array.from(originSelect.options).forEach(option => option.disabled = false);

        // Disable the selected destination airport in the origin dropdown
        if (selectedDestination) {
            disableSelectedOption(originSelect, selectedDestination);
        }

        // Check for duplicates after processing
        checkForDuplicates();
    });
});

</script>
    <!-- App js -->
    <script src="assets/js/app.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    let familyMemberCount = 0;
    const addFamilyMemberBtn = document.getElementById('addFamilyMemberBtn');
    const familyMembersAccordion = document.getElementById('familyMembersAccordion');

    addFamilyMemberBtn.addEventListener('click', function() {
        addFamilyMember();
    });

    familyMembersAccordion.addEventListener('click', function(event) {
        if (event.target.classList.contains('remove-family-member')) {
            removeFamilyMember(event.target.closest('.accordion-item'));
        }
    });

    function addFamilyMember() {
        familyMemberCount++;
        const newMemberCard = `
            <div class="accordion-item">
                <h2 class="accordion-header" id="familyMemberHeading${familyMemberCount}">
                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#familyMemberCollapse${familyMemberCount}" aria-expanded="true" aria-controls="familyMemberCollapse${familyMemberCount}">
                        <i class="ri-user-line"></i> Family Member ${familyMemberCount}
                    </button>
                </h2>
                <div id="familyMemberCollapse${familyMemberCount}" class="accordion-collapse collapse show" aria-labelledby="familyMemberHeading${familyMemberCount}" data-bs-parent="#familyMembersAccordion">
                    <div class="accordion-body">
                        <div class="mb-3">
                            <label for="member${familyMemberCount}Name" class="form-label">Name</label>
                            <input type="text" class="form-control" id="member${familyMemberCount}Name" name="family_members[${familyMemberCount - 1}][name]" required>
                        </div>
                        <div class="mb-3">
                            <label for="member${familyMemberCount}Relation" class="form-label">Relation</label>
                            <select class="form-select" id="member${familyMemberCount}Relation" name="family_members[${familyMemberCount - 1}][relation]" required>
                                <option value="">Select Relation</option>
                                <option value="Father">Father</option>
                                <option value="Mother">Mother</option>
                                <option value="Wife">Wife</option>
                                <option value="Child">Child</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="member${familyMemberCount}Gender" class="form-label">Gender</label>
                            <select class="form-select" id="member${familyMemberCount}Gender" name="family_members[${familyMemberCount - 1}][gender]" required>
                                <option value="">Select Gender</option>
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="member${familyMemberCount}Age" class="form-label">Age</label>
                            <input type="number" class="form-control" id="member${familyMemberCount}Age" name="family_members[${familyMemberCount - 1}][age]" required min="0" max="120">
                        </div>
                        <div class="mb-3">
                            <label for="member${familyMemberCount}Passport" class="form-label">Passport Number</label>
                            <input type="text" class="form-control" id="member${familyMemberCount}Passport" name="family_members[${familyMemberCount - 1}][passport_number]">
                        </div>
                        <button type="button" class="btn btn-danger btn-sm remove-family-member">Remove Family Member</button>
                    </div>
                </div>
            </div>
        `;
        familyMembersAccordion.insertAdjacentHTML('beforeend', newMemberCard);
    }

    function removeFamilyMember(accordionItem) {
        accordionItem.remove();
        updateFamilyMemberNumbers();
    }

    function updateFamilyMemberNumbers() {
        const familyMemberItems = familyMembersAccordion.querySelectorAll('.accordion-item');
        familyMemberItems.forEach((item, index) => {
            const newIndex = index + 1;
            const header = item.querySelector('.accordion-header');
            const button = item.querySelector('.accordion-button');
            const collapse = item.querySelector('.accordion-collapse');
            const inputs = item.querySelectorAll('input, select');
            
            header.id = `familyMemberHeading${newIndex}`;
            button.setAttribute('data-bs-target', `#familyMemberCollapse${newIndex}`);
            button.setAttribute('aria-controls', `familyMemberCollapse${newIndex}`);
            button.innerHTML = `<i class="ri-user-line"></i> Family Member ${newIndex}`;
            
            collapse.id = `familyMemberCollapse${newIndex}`;
            collapse.setAttribute('aria-labelledby', `familyMemberHeading${newIndex}`);
            
            inputs.forEach(input => {
                const fieldName = input.name.split('[')[1].split(']')[0];
                input.id = `member${newIndex}${fieldName.charAt(0).toUpperCase() + fieldName.slice(1)}`;
                input.name = `family_members[${index}][${fieldName}]`;
            });
        });
        familyMemberCount = familyMemberItems.length;
    }
});
</script>
<script>
    $(document).ready(function() {
    $('#flightId').change(function() {
        var flightId = $(this).val();
        if (flightId) {
            $.ajax({
                type: 'POST',
                url: 'get_flight_price.php',
                data: { flight_id: flightId },
                dataType: 'json', // Specify that we're expecting JSON
                success: function(response) {
                    // Update both price fields
                    $('#basePrice').val(response.basePrice);
                    $('#flightPrice').val(response.finalPrice);
                },
                error: function() {
                    // Clear both fields on error
                    $('#basePrice').val('');
                    $('#flightPrice').val('');
                }
            });
        } else {
            // Clear both fields if no flight is selected
            $('#basePrice').val('');
            $('#flightPrice').val('');
        }
    });
});
</script>

<script>
document.getElementById('newCustomerForm').addEventListener('submit', function(e) {
    e.preventDefault(); // Prevent default form submission

    // Gather form data
    var formData = new FormData(this);

    // Send data to your server-side script for saving the customer
    fetch('save_customer.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Add the new customer to the select element
            var customerSelect = document.getElementById('customerId');
            var newOption = document.createElement('option');
            newOption.value = data.customer_id; // Assuming your response contains the new customer ID
            newOption.textContent = `${data.first_name} ${data.last_name}`; // Adjust according to your response
            customerSelect.appendChild(newOption);

            // Optionally, select the new customer
            customerSelect.value = data.customer_id;

            // Close the modal
            $('#customerModal').modal('hide');
        } else {
            alert('Error saving customer: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while saving the customer.');
    });
});
</script>
<script>
document.getElementById('bookingForm').addEventListener('submit', function(e) {
    e.preventDefault();

    var formData = new FormData(this);

    fetch('save_booking.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: data.message,
                showCancelButton: true,
                confirmButtonText: 'Add Payment Now',
                cancelButtonText: 'No, thanks',
                allowOutsideClick: false,
                allowEscapeKey: false
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = `add_pay.php?booking_id=${data.booking_id}`;
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    window.location.href = 'all_bookings.php';
                }
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: data.message,
                confirmButtonText: 'OK'
            });
        }
    })
    .catch((error) => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Oops...',
            text: 'Something went wrong!',
            confirmButtonText: 'OK'
        });
    });
});

</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const agencyFeePercentageInput = document.getElementById('agencyFeePercentage');
    const agencyFeeAmountInput = document.getElementById('agencyFeeAmount');
    const totalWithFeesInput = document.getElementById('totalWithFees');
    const flightPriceInput = document.getElementById('flightPrice');

    function calculateFees() {
        const flightPrice = parseFloat(flightPriceInput.value) || 0;
        const feePercentage = parseFloat(agencyFeePercentageInput.value) || 0;
        
        const feeAmount = (flightPrice * (feePercentage / 100)).toFixed(2);
        const totalAmount = (flightPrice + parseFloat(feeAmount)).toFixed(2);
        
        agencyFeeAmountInput.value = feeAmount;
        totalWithFeesInput.value = totalAmount;
    }

    // Calculate initially if there's a value
    if (flightPriceInput.value) {
        calculateFees();
    }

    // Recalculate when flight price changes
    flightPriceInput.addEventListener('change', calculateFees);
    
    // Recalculate when agency fee percentage changes
    agencyFeePercentageInput.addEventListener('input', calculateFees);
});
</script>
</body>

</html>