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

$ticketId = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Fetch ticket details
$stmt = $conn->prepare("
    SELECT t.*, b.booking_code 
    FROM ticket_details t
    LEFT JOIN bookings b ON t.booking_id = b.booking_id
    WHERE t.ticket_id = ? AND t.status = 'Active'
");

$stmt->bind_param("i", $ticketId);
$stmt->execute();
$result = $stmt->get_result();
$ticket = $result->fetch_assoc();

if (!$ticket) {
    header('Location: all_new_tickets.php');
    exit();
}

// 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' => 'Edit 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' => 'Ticket Management', 'title' => 'Edit Ticket')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Edit Ticket</h5>
                                </div>
                                <div class="card-body">
                                    <form id="editTicketForm" method="POST" action="update_ticket.php">
                                        <input type="hidden" name="ticket_id" value="<?php echo $ticketId; ?>">
                                        <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>
                                                    <?php
                                                    $salutations = ['Mr', 'Mrs', 'Ms', 'Dr', 'Prof'];
                                                    foreach ($salutations as $s) {
                                                        $selected = ($ticket['salutation'] === $s) ? 'selected' : '';
                                                        echo "<option value=\"$s\" $selected>$s</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" 
                                                       value="<?php echo htmlspecialchars($ticket['customer_name']); ?>" required>
                                            </div>

                                            <!-- Ticket Reference (Read-only) -->
                                            <div class="col-md-3">
                                                <label for="ticketRef" class="form-label">Ticket Reference</label>
                                                <input type="text" class="form-control" id="ticketRef" 
                                                       value="<?php echo htmlspecialchars($ticket['ticket_ref']); ?>" readonly>
                                            </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>
                                                    <?php
                                                    $classes = ['Economy', 'Business', 'First'];
                                                    foreach ($classes as $class) {
                                                        $selected = ($ticket['booking_class'] === $class) ? 'selected' : '';
                                                        echo "<option value=\"$class\" $selected>$class</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <!-- Flight Route -->
                                            <div class="col-md-3">
                                                <label for="flightRoute" class="form-label">Flight Route</label>
                                                <input type="text" class="form-control" id="flightRoute" name="flight_route" 
                                                       value="<?php echo htmlspecialchars($ticket['flight_route']); ?>"
                                                       pattern="[A-Z]{3}-[A-Z]{3}" required
                                                       title="Please enter route in format: XXX-XXX (e.g., NBO-MGQ)">
                                            </div>

                                            <!-- Flight Date -->
                                            <div class="col-md-3">
                                                <label for="flightDate" class="form-label">Flight Date</label>
                                                <input type="datetime-local" class="form-control" id="flightDate" 
                                                       name="flight_date" 
                                                       value="<?php echo date('Y-m-d\TH:i', strtotime($ticket['flight_date'])); ?>" 
                                                       required>
                                            </div>

                                            <!-- Ticket Cost -->
                                            <div class="col-md-2">
                                                <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" value="<?php echo $ticket['ticket_cost']; ?>" 
                                                       required onchange="calculateTotal()">
                                            </div>

                                            <!-- Agency Fee -->
                                            <div class="col-md-2">
                                                <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" value="<?php echo $ticket['agency_fee']; ?>" 
                                                       required onchange="calculateTotal()">
                                            </div>

                                            <!-- Total Amount (Read-only) -->
                                            <div class="col-md-2">
                                                <label for="totalAmount" class="form-label">Total Amount (USD)</label>
                                                <input type="number" step="0.01" class="form-control" id="totalAmount" 
                                                       name="total_amount" value="<?php echo $ticket['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): ?>
                                                        <?php $selected = ($ticket['booking_id'] == $booking['booking_id']) ? 'selected' : ''; ?>
                                                        <option value="<?php echo $booking['booking_id']; ?>" <?php echo $selected; ?>>
                                                            <?php echo htmlspecialchars($booking['booking_code']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>

                                            <!-- Submit Buttons -->
                                            <div class="col-12">
                                                <button type="submit" class="btn btn-primary">Update 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('editTicketForm');
        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() {
        // Validate flight route format
        const flightRoute = document.getElementById('flightRoute').value;
        if (!/^[A-Z]{3}-[A-Z]{3}$/.test(flightRoute)) {
            Swal.fire({
                title: 'Invalid Format',
                text: 'Flight route must be in format: XXX-XXX (e.g., NBO-MGQ)',
                icon: 'error',
                confirmButtonText: 'OK'
            });
            return;
        }

        const formData = new FormData(document.getElementById('editTicketForm'));

        fetch('update_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 updating the ticket.',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        });
    }

    // Initial calculation of total
    calculateTotal();

    // Add validation for dates
    document.getElementById('flightDate').addEventListener('change', function() {
        const selectedDate = new Date(this.value);
        const now = new Date();
        
        if (selectedDate < now) {
            Swal.fire({
                title: 'Invalid Date',
                text: 'Flight date cannot be in the past',
                icon: 'warning',
                confirmButtonText: 'OK'
            });
            this.value = now.toISOString().slice(0, 16);
        }
    });
    </script>
</body>
</html>