<?php
// Include required libraries
require_once '../includes/db.php';
require_once '../vendor/dompdf/autoload.inc.php';
require_once '../includes/qrcode/qrlib.php';

use Dompdf\Dompdf;
use Dompdf\Options;

// Security: User must be logged in
if (!isset($_SESSION['user_id'])) { die("Access Denied. Please log in."); }
$user_id = $_SESSION['user_id'];

$type = $_GET['type'] ?? '';
$booking_id = intval($_GET['id'] ?? 0);

if ($booking_id <= 0 || !in_array($type, ['tour', 'hotel', 'flight', 'ferry'])) {
    die("Invalid booking type or ID specified.");
}

// Fetch site settings for branding
$settings_result = $conn->query("SELECT * FROM site_settings");
$site_settings = [];
while ($row = $settings_result->fetch_assoc()) { $site_settings[$row['setting_name']] = $row['setting_value']; }

$booking = null;
$template_file = '';
$qr_data = '';

// Fetch the correct booking data based on type
switch ($type) {
    case 'tour':
        $stmt = $conn->prepare("SELECT b.*, t.title as tour_title, t.location, u.full_name as customer_name FROM bookings b JOIN tours t ON b.tour_id = t.id LEFT JOIN users u ON b.user_id = u.id WHERE b.id = ? AND b.user_id = ? AND b.payment_status = 'Paid'");
        $template_file = '../templates/ticket-tour.php';
        $qr_data = 'TourBookingID:' . $booking_id;
        break;
    case 'hotel':
        $stmt = $conn->prepare("SELECT b.*, h.name as hotel_name, h.location, r.room_type_name, u.full_name FROM hotel_bookings b JOIN hotels h ON b.hotel_id = h.id JOIN hotel_rooms r ON b.room_id = r.id JOIN users u ON b.user_id = u.id WHERE b.id = ? AND b.user_id = ? AND b.payment_status = 'Paid'");
        $template_file = '../templates/ticket-hotel.php';
        $qr_data = 'HotelBookingID:' . $booking_id;
        break;
    case 'flight':
         $stmt = $conn->prepare("SELECT b.*, orig.city as origin_city, dest.city as dest_city, u.full_name FROM flight_bookings b JOIN airports orig ON b.origin_id = orig.id JOIN airports dest ON b.destination_id = dest.id JOIN users u ON b.user_id = u.id WHERE b.id = ? AND b.user_id = ? AND b.payment_status = 'Paid'");
        $template_file = '../templates/ticket-flight.php';
        $qr_data = 'FlightBookingID:' . $booking_id;
        break;
    case 'ferry':
        $stmt = $conn->prepare("SELECT b.*, u.full_name, r.ferry_company, orig.city as origin_city, dest.city as dest_city FROM ferry_bookings b JOIN users u ON b.user_id = u.id JOIN ferry_routes r ON b.route_id = r.id JOIN ferry_ports orig ON r.origin_port_id = orig.id JOIN ferry_ports dest ON r.destination_port_id = dest.id WHERE b.id = ? AND b.user_id = ? AND b.payment_status = 'Paid'");
        $template_file = '../templates/ticket-ferry.php';
        $qr_data = 'FerryBookingID:' . $booking_id;
        break;
}

$stmt->bind_param("ii", $booking_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) { die("Booking not found, is not paid, or you do not have permission to view it."); }
$booking = $result->fetch_assoc();
$stmt->close();

// --- GENERATE QR CODE ---
ob_start();
QRCode::png($qr_data, null, QR_ECLEVEL_L, 3);
$qr_image_data = ob_get_contents();
ob_end_clean();
$qr_code_path = 'data:image/png;base64,' . base64_encode($qr_image_data);

// --- GENERATE PDF ---
ob_start();
include $template_file;
$html = ob_get_clean();

$options = new Options();
$options->set('isRemoteEnabled', true);
$options->setChroot($_SERVER['DOCUMENT_ROOT']);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("Ticket-".$type."-".$booking_id.".pdf", ["Attachment" => false]);
?>
