
<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Database connection
include('layouts/dbconn.php');
include('layouts/main.php');

// Fetch booking_id from URL
$booking_id = isset($_GET['booking_id']) ? intval($_GET['booking_id']) : 0;

if ($booking_id <= 0) {
    die("Invalid booking ID");
}

// Prepare the query using a prepared statement for security
$query = "SELECT b.booking_id, c.first_name, c.last_name, c.email, f.flight_number, f.departure_time,
          oa.city AS origin_city, oa.country AS origin_country,
          da.city AS destination_city, da.country AS destination_country,
          b.booking_code, b.total_passengers
          FROM bookings b
          JOIN customers c ON b.customer_id = c.customer_id
          JOIN flights f ON b.flight_id = f.flight_id
          JOIN airports oa ON f.origin_id = oa.airport_id
          JOIN airports da ON f.destination_id = da.airport_id
          WHERE b.booking_id = ?";

$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "i", $booking_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

$boardingPasses = [];

if ($row = mysqli_fetch_assoc($result)) {
    $main_customer_data = [
        'first_name' => $row['first_name'],
        'last_name' => $row['last_name'],
        'flight_number' => $row['flight_number'],
        'email' => $row['email'],
        'departure_time' => $row['departure_time'],
        'origin_city' => $row['origin_city'],
        'origin_country' => $row['origin_country'],
        'destination_city' => $row['destination_city'],
        'destination_country' => $row['destination_country'],
        'booking_code' => $row['booking_code'],
        'total_passengers' => $row['total_passengers']
    ];

    // Fetch family members from the database
    $family_query = "SELECT name, relation FROM family_members WHERE booking_id = ?";
    $family_stmt = mysqli_prepare($conn, $family_query);
    mysqli_stmt_bind_param($family_stmt, "i", $booking_id);
    mysqli_stmt_execute($family_stmt);
    $family_result = mysqli_stmt_get_result($family_stmt);

    $family_members = [];
    while ($family_row = mysqli_fetch_assoc($family_result)) {
        $family_members[] = $family_row;
    }

    // Create boarding passes for the main customer and each family member
    $boardingPasses[] = createBoardingPass($main_customer_data, 'tickets/TicketFront.png');
    foreach ($family_members as $family_member) {
        $family_member_data = array_merge($main_customer_data, [
            'first_name' => $family_member['name'],
            'relation' => $family_member['relation']
        ]);
        $boardingPasses[] = createBoardingPass($family_member_data, 'tickets/TicketFront.png');
    }
} else {
    die("Booking not found.");
}

function createBoardingPass($data, $template) {
    // Load the ticket template image
    $image = imagecreatefrompng($template);
    if (!$image) {
        die("Failed to load template image");
    }

    $fontPath = __DIR__ . '/assets/fonts/hkgrotesk-bold.ttf';
    if (!file_exists($fontPath)) {
        die("Font file not found");
    }

    // Set colors
    $black = imagecolorallocate($image, 0, 0, 0);

    // Define text positions
    $textPositions = [
        ['text' => $data['first_name'] . ' ' . $data['last_name'], 'x' => 30, 'y' => 90, 'size' => 9.12],
        ['text' => $data['flight_number'], 'x' => 175, 'y' => 90, 'size' => 9.12],
        ['text' => date('d M', strtotime($data['departure_time'])), 'x' => 240, 'y' => 90, 'size' => 9.12],
        ['text' => $data['origin_city'] . ', ' . $data['origin_country'], 'x' => 50, 'y' => 125, 'size' => 9.12],
        ['text' => $data['destination_city'] . ', ' . $data['destination_country'], 'x' => 50, 'y' => 165, 'size' => 9.12],
        ['text' => date('H:i', strtotime($data['departure_time'])), 'x' => 240, 'y' => 125, 'size' => 9.12],
        ['text' => '17A', 'x' => 175, 'y' => 125, 'size' => 9.12], // Example seat
        ['text' => 'D7', 'x' => 343, 'y' => 185, 'size' => 9.12],  // Example gate

        // Detachable Section
        ['text' => $data['first_name'] . ' ' . $data['last_name'], 'x' => 343, 'y' => 90, 'size' => 9.12],
        ['text' => date('d M', strtotime($data['departure_time'])), 'x' => 343, 'y' => 125, 'size' => 9.12],
        ['text' => $data['origin_city'], 'x' => 343, 'y' => 155, 'size' => 9.12],
        ['text' => $data['destination_city'], 'x' => 420, 'y' => 155, 'size' => 9.12],
        ['text' => date('H:i', strtotime($data['departure_time'])), 'x' => 420, 'y' => 125, 'size' => 9.12],
        ['text' => '17A', 'x' => 420, 'y' => 185, 'size' => 9.12],
    ];

    // Overlay text onto the image
    foreach ($textPositions as $pos) {
        imagettftext($image, $pos['size'], 0, $pos['x'], $pos['y'], $black, $fontPath, $pos['text']);
    }

    // Capture the image data and encode as base64
    ob_start();
    imagepng($image);
    $imageData = ob_get_clean();
    imagedestroy($image);

    return base64_encode($imageData);
}

// Include PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'layouts/mail/src/Exception.php';
require 'layouts/mail/src/PHPMailer.php';
require 'layouts/mail/src/SMTP.php';

function sendTicketEmail($booking_id, $email) {
    global $conn;

    // Fetch booking details
    $query = "SELECT c.email, c.first_name, c.last_name, b.booking_code, f.flight_number,
              f.departure_time, oa.city AS origin_city, da.city AS destination_city
              FROM bookings b
              JOIN customers c ON b.customer_id = c.customer_id
              JOIN flights f ON b.flight_id = f.flight_id
              JOIN airports oa ON f.origin_id = oa.airport_id
              JOIN airports da ON f.destination_id = da.airport_id
              WHERE b.booking_id = ?";

    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, "i", $booking_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $booking = mysqli_fetch_assoc($result);

    if (!$booking) {
        error_log("Booking not found for booking_id: $booking_id");
        return false;
    }

    // Generate PDF ticket (you'll need to implement this function)
    $pdfPath = generatePDFTicket($booking_id);

    // Create a new PHPMailer instance
    $mail = new PHPMailer(true);

    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host       = 'mail.myne.co.ke';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'mailer@myne.co.ke';
        $mail->Password   = '#@#2025Wemadeit';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        // Recipients
        $mail->setFrom('noreply@yourairline.com', 'Your Airline');
        $mail->addAddress($email, $booking['first_name'] . ' ' . $booking['last_name']);

        // Attachments
        $mail->addAttachment($pdfPath, 'ticket.pdf');

        // Content
        $mail->isHTML(true);
        $mail->Subject = "Your Flight Ticket - Booking {$booking['booking_code']}";
        $mail->Body    = "
            <html>
            <body>
                <h2>Your Flight Ticket</h2>
                <p>Dear {$booking['first_name']},</p>
                <p>Thank you for choosing our airline. Your flight details are as follows:</p>
                <ul>
                    <li><strong>Booking Code:</strong> {$booking['booking_code']}</li>
                    <li><strong>Flight Number:</strong> {$booking['flight_number']}</li>
                    <li><strong>Departure:</strong> {$booking['origin_city']} at {$booking['departure_time']}</li>
                    <li><strong>Destination:</strong> {$booking['destination_city']}</li>
                </ul>
                <p>Your ticket is attached to this email. We wish you a pleasant journey!</p>
                <p>Best regards,<br>Your Airline Team</p>
            </body>
            </html>
        ";
        $mail->AltBody = "
            Your Flight Ticket - Booking {$booking['booking_code']}

            Dear {$booking['first_name']},

            Thank you for choosing our airline. Your flight details are as follows:

            Booking Code: {$booking['booking_code']}
            Flight Number: {$booking['flight_number']}
            Departure: {$booking['origin_city']} at {$booking['departure_time']}
            Destination: {$booking['destination_city']}

            Your ticket is attached to this email. We wish you a pleasant journey!

            Best regards,
            Your Airline Team
        ";

        $mail->send();

        // Clean up
        unlink($pdfPath);

        return true;
    } catch (Exception $e) {
        error_log("Message could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}

// Handle the AJAX request
if (isset($_POST['action']) && $_POST['action'] == 'send_email') {
    $booking_id = $_POST['booking_id'];
    $email = $_POST['email'];

    try {
        error_log("Attempting to send email for booking ID: $booking_id to email: $email");
        $result = sendTicketEmail($booking_id, $email);
        error_log("Email sent successfully");
        echo json_encode(['success' => $result]);
    } catch (Exception $e) {
        error_log("Failed to send email: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Print Tickets')); ?>

    <!--datatable css-->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" />
    <!--datatable responsive css-->
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.bootstrap.min.css" />

    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css">
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <?php include 'layouts/head-css.php'; ?>

    <style>
    .boarding-pass-container {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 20px;
    }
    .boarding-pass-card {
        width: 100%;
        max-width: 400px;
        margin-bottom: 20px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        border-radius: 8px;
        overflow: hidden;
    }
    .boarding-pass-card h2 {
        background-color: #f0f0f0;
        margin: 0;
        padding: 10px;
        font-size: 18px;
        text-align: center;
    }
    .boarding-pass-image {
        width: 100%;
        height: auto;
        display: block;
    }
    @media print {
        body * {
            visibility: hidden;
        }
        .boarding-pass-container, .boarding-pass-container * {
            visibility: visible;
        }
        .boarding-pass-container {
            position: absolute;
            left: 0;
            top: 0;
        }
        .print-button, #printTicketsBtn, .card h2 {
            display: none !important;
        }
    }
    .card-content {
        padding: 15px;
    }
    .button-container {
        padding: 15px;
        border-top: 1px solid #e0e0e0;
        text-align: center;
    }
    </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' => 'Print Tickets')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex align-items-center flex-wrap gap-2">
                                

<div class="flex-grow-1">
                                            Booking ID: <?php echo $booking_id;?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!--end col-->
                        <div class="col-xxl-12">
                            <div class="card" id="contactList">
                                <div class="card-header">
                                    <div class="row g-3">
                                        <div class="col-md-4">
                                            <div class="flight-info-box">
                                                <h5>Flight Details</h5>
                                                <?php
                                                $flightDepartureTime = isset($main_customer_data['departure_time']) ? $main_customer_data['departure_time'] : 'N/A';
                                                $flightDestination = isset($main_customer_data['destination_city']) ? $main_customer_data['destination_city'] : 'N/A';
                                                ?>
                                                <p><h5>Departure Time: <span class="badge bg-dark-subtle text-body"><?php echo htmlspecialchars($flightDepartureTime); ?></span></h5></p>
                                                <p><h5>Destination: <span class="badge bg-success"><?php echo htmlspecialchars($flightDestination); ?></span></h5></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="boarding-pass-container">
                                        <?php if (!empty($boardingPasses)): ?>
                                            <?php foreach ($boardingPasses as $index => $pass): ?>
                                                <div class="card" id="boarding-pass-<?= $index ?>">
                                                    <div class="card-content">
                                                        <h2>Boarding Pass <?= $index + 1 ?></h2>
                                                        <img class="boarding-pass-image" src="data:image/png;base64,<?= $pass ?>" alt="Boarding Pass <?= $index + 1 ?>">
                                                    </div>
                                                    <div class="button-container">
                                                        <button type="button" class="btn btn-success btn-label waves-effect waves-light print-button" data-index="<?= $index ?>">
                                                            <i class="ri-printer-line label-icon align-middle fs-16 me-2"></i> Print
                                                        </button>
                                                        <?php if ($index === 0): ?>
                                                            <button type="button" class="btn btn-primary btn-label waves-effect waves-light email-button" data-booking-id="<?= $booking_id ?>" data-default-email="<?= htmlspecialchars($main_customer_data['email']) ?>">
                                                                <i class="ri-mail-line label-icon align-middle fs-16 me-2"></i> Email Ticket
                                                            </button>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <div class="boarding-pass-card">
                                                <p>No boarding passes generated.</p>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="d-flex justify-content-end mt-3">
                                        <button id="printTicketsBtn" class="btn btn-success">Print All Tickets</button>
                                    </div>
                                </div>
                            </div>
                            <!--end card-->
                        </div>
                        <!--end col-->
                    </div>
                    <!--end row-->
                </div>
                <!-- container-fluid -->
            </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://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="assets/libs/list.js/list.min.js"></script>
    <script src="assets/libs/list.pagination.js/list.pagination.min.js"></script>

    <script src="assets/js/pages/crm-contact.init.js"></script>
    <!-- App js -->
    <script src="assets/js/app.js"></script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const printButtons = document.querySelectorAll('.print-button');
        const emailButton = document.querySelector('.email-button');
        const printAllButton = document.getElementById('printTicketsBtn');

        // Printing individual boarding passes
        printButtons.forEach(button => {
            button.addEventListener('click', function() {
                const index = this.getAttribute('data-index');
                const boardingPass = document.querySelector(`#boarding-pass-${index}`);
                printSingleBoardingPass(boardingPass);
            });
        });

        // Printing all boarding passes
        if (printAllButton) {
            printAllButton.addEventListener('click', function() {
                window.print();
            });
        }

        // Emailing all boarding passes
        if (emailButton) {
            emailButton.addEventListener('click', function() {
                const bookingId = this.getAttribute('data-booking-id');
                const defaultEmail = this.getAttribute('data-default-email');
                promptAndSendEmail(bookingId, defaultEmail);
            });
        }

        function printSingleBoardingPass(boardingPass) {
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                <head>
                    <title>Boarding Pass</title>
                    <style>
                        body * { visibility: visible; }
                        .print-button, .email-button, h2 { display: none !important; }
                    </style>
                </head>
                <body>
                    ${boardingPass.innerHTML}
                </body>
                </html>
            `);
            printWindow.document.close();
            printWindow.print();
            printWindow.onafterprint = function() {
                printWindow.close();
            };
        }

        function promptAndSendEmail(bookingId, defaultEmail) {
            Swal.fire({
                title: 'Confirm Email Address',
                html: `Send tickets to: <strong>${defaultEmail}</strong><br>Or enter a different email address:`,
                input: 'email',
                inputPlaceholder: 'Enter email address (optional)',
                showCancelButton: true,
                confirmButtonText: 'Send',
                showLoaderOnConfirm: true,
                preConfirm: (email) => {
                    const finalEmail = email || defaultEmail;
                    return sendTicketEmail(bookingId, finalEmail)
                        .then(result => {
                            if (!result.success) {
                                throw new Error(result.error || 'Unknown error occurred');
                            }
                            return result;
                        })
                        .catch(error => {
                            Swal.showValidationMessage(
                                `Request failed: ${error.message}`
                            );
                        });
                },
                allowOutsideClick: () => !Swal.isLoading()
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Success!',
                        text: 'The tickets have been sent to the email address.',
                        icon: 'success'
                    });
                }
            });
        }

        function sendTicketEmail(bookingId, email) {
        return fetch('send_ticket_email.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: `booking_id=${encodeURIComponent(bookingId)}&email=${encodeURIComponent(email)}`
        }).then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        }).catch(error => {
            console.error('Request failed:', error);
            throw error;
        });
    }
    });
    </script>
</body>
</html>