<?php include 'layouts/session.php'; ?>
<?php include 'layouts/main.php'; ?>
<?php include 'layouts/dbconn.php'; ?>
<?php
// Fetch bookings for reference
$bookingsQuery = "SELECT booking_id, booking_code FROM bookings WHERE status = 'Booked' ORDER BY booking_date DESC";
$bookings = $conn->query($bookingsQuery)->fetch_all(MYSQLI_ASSOC);
?>


<head>

    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Ticket 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 Ticket Booking')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Create New Ticket</h5>
                                </div>
                                <div class="card-body">
                                    <form id="ticketForm" method="POST" action="save_new_ticket.php">
                                        <div class="row g-3">
                                            <!-- Salutation -->
                                            <div class="col-md-2">
                                                <label for="salutation" class="form-label">Salutation</label>
                                                <select class="form-select" id="salutation" name="salutation" required>
                                                    <option value="">Select</option>
                                                    <option value="Mr">Mr</option>
                                                    <option value="Mrs">Mrs</option>
                                                    <option value="Ms">Ms</option>
                                                    <option value="Dr">Dr</option>
                                                    <option value="Prof">Prof</option>
                                                </select>
                                            </div>

                                            <!-- Customer Name -->
                                            <div class="col-md-4">
                                                <label for="customerName" class="form-label">Customer Name</label>
                                                <input type="text" class="form-control" id="customerName" name="customer_name" required>
                                            </div>

                                            <!-- Ticket Reference -->
                                            <div class="col-md-3">
                                                <label for="ticketRef" class="form-label">Ticket Reference</label>
                                                <input type="text" class="form-control" id="ticketRef" name="ticket_ref" required>
                                            </div>

                                            <!-- Booking Class -->
                                            <div class="col-md-3">
                                                <label for="bookingClass" class="form-label">Booking Class</label>
                                                <select class="form-select" id="bookingClass" name="booking_class" required>
                                                    <option value="">Select</option>
                                                    <option value="Y">Y</option>
                                                    <option value="L">L</option>
                                                    <option value="First">First</option>
                                                </select>
                                            </div>
                                            <!-- Airline -->
                                            <div class="col-md-3">
                                                <label for="airline" class="form-label">Airline</label>
                                                <select class="form-select" id="airline" name="airline" required>
                                                    <option value="">Select Airline</option>
                                                    <option value="iFly Air">iFly Air</option>
                                                    <option value="Mandeeq">Mandeeq</option>
                                                    <option value="Daalo Air">Daalo Air</option>
                                                    <option value="Freedom Airlines">Freedom Airlines</option>
                                                    <option value="Premier Airlines">Premier Airlines</option>
                                                    <option value="Salaam Air">Salaam Air</option>
                                                </select>
                                            </div>
                                            <!-- Flight Route -->
                                            <div class="col-md-3">
                                                <label for="flightRoute" class="form-label">Flight Route</label>
                                                <select class="form-select" id="flightRoute" name="flight_route" required>
                                                    <option value="">Select Route</option>
                                                    <option value="NBO-MGQ">NBO-MGQ</option>
                                                    <option value="MGQ-NBO">MGQ-NBO</option>
                                                </select>    
                                            </div>

                                            <!-- Flight Date -->
                                            <div class="col-md-3">
                                                <label for="flightDate" class="form-label">Flight Date</label>
                                                <input type="date" class="form-control" id="flightDate" name="flight_date" required>
                                            </div>

                                            <!-- Ticket Cost -->
                                            <div class="col-md-3">
                                                <label for="ticketCost" class="form-label">Ticket Cost (USD)</label>
                                                <input type="number" step="0.01" min="0" class="form-control" id="ticketCost" 
                                                       name="ticket_cost" required onchange="calculateTotal()">
                                            </div>

                                            <!-- Agency Fee -->
                                            <div class="col-md-3">
                                                <label for="agencyFee" class="form-label">Agency Fee (USD)</label>
                                                <input type="number" step="0.01" min="0" class="form-control" id="agencyFee" 
                                                       name="agency_fee" required value="30.00" onchange="calculateTotal()">
                                            </div>

                                            <!-- Total Amount (Read-only) -->
                                            <div class="col-md-3">
                                                <label for="totalAmount" class="form-label">Total Amount (USD)</label>
                                                <input type="number" step="0.01" class="form-control" id="totalAmount" 
                                                       name="total_amount" readonly>
                                            </div>
                                            
                                            <!-- Currency -->
                                            <div class="col-md-3">
                                                <label for="currency" class="form-label">Currency</label>
                                                    <select class="form-select" id="currency" name="currency" required>
                                                        <option value="KES">Kenyan Shillings (KES)</option>
                                                        <option value="USD">US Dollars (USD)</option>
                                                    </select>
                                            </div>

                                            <!-- Related Booking -->
                                            <div class="col-md-3">
                                                <label for="bookingId" class="form-label">Related Booking (Optional)</label>
                                                <select class="form-select" id="bookingId" name="booking_id">
                                                    <option value="">Select Booking</option>
                                                    <?php foreach ($bookings as $booking): ?>
                                                        <option value="<?php echo $booking['booking_id']; ?>">
                                                            <?php echo $booking['booking_code']; ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </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 Ticket
                                                    </button>
                                                    <a href="all_new_tickets.php" class="btn btn-danger btn-label waves-effect waves-light rounded-pill">
                                                        <i class="ri-close-circle-line label-icon align-middle rounded-pill fs-16 me-2"></i> Cancel
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </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() {
        // Set minimum date for flight date input to today
        const today = new Date().toISOString().slice(0, 16);
        document.getElementById('flightDate').min = today;

        // Initialize form validation and submission
        const form = document.getElementById('ticketForm');
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            submitForm();
        });

        // Auto-format flight route to uppercase
        const routeInput = document.getElementById('flightRoute');
        routeInput.addEventListener('input', function(e) {
            this.value = this.value.toUpperCase();
        });
    });

    function calculateTotal() {
        const ticketCost = parseFloat(document.getElementById('ticketCost').value) || 0;
        const agencyFee = parseFloat(document.getElementById('agencyFee').value) || 0;
        const total = ticketCost + agencyFee;
        document.getElementById('totalAmount').value = total.toFixed(2);
    }

    function submitForm() {
        const formData = new FormData(document.getElementById('ticketForm'));

        fetch('save_new_ticket.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 = 'all_new_tickets.php';
                    }
                });
            } else {
                Swal.fire({
                    title: 'Error!',
                    text: data.message,
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire({
                title: 'Error!',
                text: 'An error occurred while saving the ticket.',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        });
    }
    </script>
    <!-- App js -->
    <script src="assets/js/app.js"></script>

</body>

</html>