<?php
session_start();

require_once __DIR__ . '/../../includes/helpers.php';
require_once __DIR__ . '/../../includes/layout.php';
require_once __DIR__ . '/../../includes/trips.php';

if (!isset($_SESSION['authenticated'])) {
    redirect(page_url('signin'));
}

$userId = current_user_id();
if ($userId <= 0) {
    redirect(page_url('signin'));
}

trip_ensure_schema();

$tripId = (int) ($_GET['trip_id'] ?? 0);
if ($tripId <= 0) {
    redirect(page_url('trips'));
}

$trip = trip_fetch_by_id($tripId, $userId);
if (!$trip) {
    redirect(page_url('trips'));
}

$itineraries = trip_fetch_itineraries($tripId);

?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Trip Print</title>
    <link rel="stylesheet" href="<?= e(asset_url('assets/style.css')) ?>">
    <style>
        body { font-family: Arial, sans-serif; padding: 32px; color: #1f2937; }
        .print-card { border: 1px solid #dbe3f4; border-radius: 16px; padding: 24px; margin-bottom: 20px; }
        .print-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 24px; }
        .print-grid strong { display: block; margin-top: 4px; }
        .print-item { border-top: 1px solid #e5e7eb; padding-top: 12px; margin-top: 12px; }
        @media print { body { padding: 0; } }
    </style>
</head>
<body onload="window.print()">
    <h1><?= e((string) $trip['trip_name']) ?></h1>
    <p><?= e(trip_trip_number($tripId)) ?></p>

    <section class="print-card">
        <div class="print-grid">
            <div><span>Destination</span><strong><?= e((string) $trip['destination']) ?></strong></div>
            <div><span>Business Purpose</span><strong><?= e((string) $trip['business_purpose']) ?></strong></div>
            <div><span>Status</span><strong><?= e(ucfirst((string) $trip['status'])) ?></strong></div>
            <div><span>Visa required</span><strong><?= ((int) ($trip['is_visa_required'] ?? 0)) === 1 ? 'Yes' : 'No' ?></strong></div>
        </div>
    </section>

    <section class="print-card">
        <h2>Itineraries</h2>
        <?php if ($itineraries === []): ?>
            <p>No itineraries added.</p>
        <?php else: ?>
            <?php foreach ($itineraries as $row): ?>
                <div class="print-item">
                    <strong><?= e((string) ($row['item_title'] ?: ucfirst((string) $row['mode']))) ?></strong>
                    <pre><?= e((string) $row['payload_json']) ?></pre>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </section>
</body>
</html>
