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

// Database connection
include('layouts/dbconn.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, 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'],
        '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], //name on the detachable section
        ['text' => date('d M', strtotime($data['departure_time'])), 'x' => 343, 'y' => 125, 'size' => 9.12], //date on the detachable section
        ['text' => $data['origin_city'], 'x' => 343, 'y' => 155, 'size' => 9.12], // origin on the detachable section
        ['text' => $data['destination_city'], 'x' => 420, 'y' => 155, 'size' => 9.12], //destination on the detachable section
        ['text' => date('H:i', strtotime($data['departure_time'])), 'x' => 420, 'y' => 125, 'size' => 9.12], //time on the detachable section
        ['text' => '17A', 'x' => 420, 'y' => 185, 'size' => 9.12], //gate on the detachable section
        
    ];

    // 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);
}

// Output HTML with embedded boarding passes
header('Content-Type: text/html');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Boarding Passes</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 20px;
        }
        .card {
            background-color: grey;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            padding: 20px;
            text-align: center;
        }
        img {
            max-width: 100%;
            height: auto;
        }
    </style>
</head>
<body>
    <?php if (!empty($boardingPasses)): ?>
        <?php foreach ($boardingPasses as $index => $pass): ?>
            <div class="card">
                <h2>Boarding Pass <?= $index + 1 ?></h2>
                <img src="data:image/png;base64,<?= $pass ?>" alt="Boarding Pass <?= $index + 1 ?>">
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="card">
            <p>No boarding passes generated.</p>
        </div>
    <?php endif; ?>
</body>
</html>
<?php
ob_end_flush();
?>