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

// Handle search parameters
$search = isset($_GET['search']) ? $_GET['search'] : '';
$dateFrom = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$dateTo = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build the query
$query = "SELECT * FROM ticket_details WHERE 1=1";
if (!empty($search)) {
    $query .= " AND (customer_name LIKE '%$search%' OR ticket_ref LIKE '%$search%' OR flight_route LIKE '%$search%' OR airline LIKE '%$search%')";
}
if (!empty($dateFrom)) {
    $query .= " AND DATE(flight_date) >= '$dateFrom'";
}
if (!empty($dateTo)) {
    $query .= " AND DATE(flight_date) <= '$dateTo'";
}
$query .= " ORDER BY created_date DESC";

$result = $conn->query($query);
?>

<!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' => 'All Tickets')); ?>
    <?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' => 'View All Bookings')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">Tickets List</h5>
                                    <button onclick="exportToCSV()" class="btn btn-success btn-label waves-effect waves-light rounded-pill"><i class="ri-upload-line label-icon align-middle rounded-pill fs-16 me-2"></i>
                                        Export to CSV
                                    </button>
                                    <a href="add_tickets.php" 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> Add New Ticket
                                    </a>
                                </div>

                                <div class="card-body">
                                    <!-- Search Form -->
                                    <form class="row g-3 mb-4" method="GET">
                                        <div class="col-md-4">
                                            <input type="text" class="form-control" name="search" 
                                                   placeholder="Search tickets..." value="<?php echo htmlspecialchars($search); ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <input type="date" class="form-control" name="date_from" 
                                                   value="<?php echo htmlspecialchars($dateFrom); ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <input type="date" class="form-control" name="date_to" 
                                                   value="<?php echo htmlspecialchars($dateTo); ?>">
                                        </div>
                                        <div class="col-md-2">
                                            <button type="submit" class="btn btn-primary w-100 btn-label waves-effect waves-light rounded-pill"><i class="ri-search-2-line label-icon align-middle rounded-pill fs-16 me-2"></i>Search</button>
                                        </div>
                                    </form>

                                    <!-- Tickets Table -->
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-striped table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Ticket Ref</th>
                                                    <th>Customer</th>
                                                    <th>Route</th>
                                                    <th>Airline</th>
                                                    <th>Class</th>
                                                    <th>Flight Date</th>
                                                    <th>Ticket Cost</th>
                                                    <th>Agency Fee</th>
                                                    <th>Total</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result->num_rows > 0): ?>
                                                    <?php while ($row = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($row['ticket_ref']); ?></td>
                                                            <td>
                                                                <?php echo htmlspecialchars($row['salutation'] . ' ' . $row['customer_name']); ?>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($row['flight_route']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['airline']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['booking_class']); ?></td>
                                                            <td>
                                                                <?php echo date('d M Y H:i', strtotime($row['flight_date'])); ?>
                                                            </td>
                                                            <td>$<?php echo number_format($row['ticket_cost'], 2); ?></td>
                                                            <td>$<?php echo number_format($row['agency_fee'], 2); ?></td>
                                                            <td>$<?php echo number_format($row['total_amount'], 2); ?></td>
                                                            <td>
                                                                <span class="badge 
                                                                    <?php echo $row['status'] === 'Active' ? 'bg-success' : 
                                                                        ($row['status'] === 'Used' ? 'bg-info' : 'bg-danger'); ?>">
                                                                    <?php echo htmlspecialchars($row['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-sm btn-light dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                                                        Actions
                                                                    </button>
                                                                    <ul class="dropdown-menu">
                                                                        <li>
                                                                            <a class="dropdown-item" href="view_ticket.php?id=<?php echo $row['ticket_id']; ?>">
                                                                                <i class="ri-eye-line align-middle me-1"></i> View
                                                                            </a>
                                                                        </li>
                                                                        <?php if ($row['status'] === 'Active'): ?>
                                                                            <li>
                                                                                <a class="dropdown-item" href="edit_ticket.php?id=<?php echo $row['ticket_id']; ?>">
                                                                                    <i class="ri-pencil-line align-middle me-1"></i> Edit
                                                                                </a>
                                                                            </li>
                                                                            <li>
                                                                                <a class="dropdown-item text-danger" href="#" 
                                                                                   onclick="confirmCancel(<?php echo $row['ticket_id']; ?>)">
                                                                                    <i class="ri-close-circle-line align-middle me-1"></i> Cancel
                                                                                </a>
                                                                            </li>
                                                                        <?php endif; ?>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="10" class="text-center">No tickets found</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </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 src="assets/js/app.js"></script>
    <script>
    function confirmCancel(ticketId) {
        Swal.fire({
            title: 'Are you sure?',
            text: "Do you want to cancel this ticket?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, cancel it!',
            cancelButtonText: 'No, keep it'
        }).then((result) => {
            if (result.isConfirmed) {
                cancelTicket(ticketId);
            }
        });
    }

    function cancelTicket(ticketId) {
        fetch('cancel_ticket.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                ticket_id: ticketId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                Swal.fire({
                    title: 'Success!',
                    text: data.message,
                    icon: 'success',
                    confirmButtonText: 'OK'
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire({
                    title: 'Error!',
                    text: data.message,
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        })
        .catch(error => {
            Swal.fire({
                title: 'Error!',
                text: 'An error occurred while cancelling the ticket.',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        });
    }
    </script>
    <script>
function exportToCSV() {
    // Get current search parameters
    const urlParams = new URLSearchParams(window.location.search);
    const searchParams = {
        search: urlParams.get('search') || '',
        date_from: urlParams.get('date_from') || '',
        date_to: urlParams.get('date_to') || ''
    };

    // Create export URL with parameters
    const exportURL = `export_tickets.php?${new URLSearchParams(searchParams)}`;
    window.location.href = exportURL;
}
</script>
</body>
</html>