<?php
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.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);
?>

<!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 Ticket')); ?>
    <?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' => '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>

                                            <!-- 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="20.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>

                                            <!-- 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-12">
                                                <button type="submit" class="btn btn-primary">Save Ticket</button>
                                                <a href="all_new_tickets.php" class="btn btn-secondary">Cancel</a>
                                            </div>
                                        </div>
                                    </form>
                                </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() {
        // 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>
</body>
</html>