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

// 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';

// Include FPDF
require('fpdf/fpdf.php');

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']);
    }

    // Create a temporary file for the image
    $tempFilePath = sys_get_temp_dir() . '/' . uniqid('boarding_pass_') . '.png';

    // Save the image to the temporary file
    imagepng($image, $tempFilePath);
    imagedestroy($image);

    return $tempFilePath;
}

function generatePDFTicket($booking_id) {
    global $conn;

    // Fetch booking details
    $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);
    $booking = mysqli_fetch_assoc($result);

    if (!$booking) {
        return false;
    }

    // Create PDF
    $pdf = new FPDF();
    $pdf->AddPage();

    // Set font
    $pdf->SetFont('Arial', 'B', 16);

    // Title
    $pdf->Cell(0, 10, 'Flight Ticket', 0, 1, 'C');
    $pdf->Ln(10);

    // Booking details
    $pdf->SetFont('Arial', '', 12);
    $pdf->Cell(0, 10, 'Booking ID: ' . $booking['booking_id'], 0, 1);
    $pdf->Cell(0, 10, 'Passenger: ' . $booking['first_name'] . ' ' . $booking['last_name'], 0, 1);
    $pdf->Cell(0, 10, 'Flight Number: ' . $booking['flight_number'], 0, 1);
    $pdf->Cell(0, 10, 'Departure: ' . $booking['origin_city'] . ', ' . $booking['origin_country'], 0, 1);
    $pdf->Cell(0, 10, 'Destination: ' . $booking['destination_city'] . ', ' . $booking['destination_country'], 0, 1);
    $pdf->Cell(0, 10, 'Departure Time: ' . $booking['departure_time'], 0, 1);
    $pdf->Cell(0, 10, 'Booking Code: ' . $booking['booking_code'], 0, 1);
    $pdf->Cell(0, 10, 'Total Passengers: ' . $booking['total_passengers'], 0, 1);

    // 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 = [];
    $main_customer_data = [
        'first_name' => $booking['first_name'],
        'last_name' => $booking['last_name'],
        'flight_number' => $booking['flight_number'],
        'email' => '', // You might want to fetch the email from the database if needed
        'departure_time' => $booking['departure_time'],
        'origin_city' => $booking['origin_city'],
        'origin_country' => $booking['origin_country'],
        'destination_city' => $booking['destination_city'],
        'destination_country' => $booking['destination_country'],
        'booking_code' => $booking['booking_code'],
        'total_passengers' => $booking['total_passengers']
    ];

    $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');
    }

    // Add boarding passes to the PDF
    foreach ($boardingPasses as $boardingPass) {
        $pdf->AddPage();
        $pdf->Image($boardingPass, 10, 10, 190);
        // Clean up the temporary file
        unlink($boardingPass);
    }

    // Create the directory if it doesn't exist
    $directory = $_SERVER['DOCUMENT_ROOT'] . '/tickets/generated/';
    if (!file_exists($directory)) {
        mkdir($directory, 0777, true);
    }

    // Generate a unique filename
    $filename = $directory . 'ticket_' . $booking_id . '_' . time() . '.pdf';

    // Save the PDF
    $pdf->Output('F', $filename);

    return $filename;
}

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) {
        return ['success' => false, 'error' => "Booking not found for booking_id: $booking_id"];
    }

    // Generate PDF ticket
    $pdfPath = generatePDFTicket($booking_id);
    if (!$pdfPath) {
        return ['success' => false, 'error' => "Failed to generate PDF ticket"];
    }

    // 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@myne.co.ke', 'Myne CRS');
        $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>Myne CRS</p>
            </body>
            </html>
        ";
        $mail->AltBody = "Your Flight Ticket - Booking {$booking['booking_code']}..."; // Plain text version

        $mail->send();

        // Clean up
        unlink($pdfPath);

        return ['success' => true];
    } catch (Exception $e) {
        return ['success' => false, 'error' => "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"];
    }
}

// Handle the AJAX request
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $booking_id = isset($_POST['booking_id']) ? intval($_POST['booking_id']) : 0;
    $email = isset($_POST['email']) ? $_POST['email'] : '';

    if ($booking_id <= 0 || empty($email)) {
        echo json_encode(['success' => false, 'error' => 'Invalid booking ID or email']);
        exit;
    }

    $result = sendTicketEmail($booking_id, $email);
    echo json_encode($result);
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
}
