<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';

// --- Page-Specific Logic Starts Here ---

$page_error = '';
$data = null;

// 2. VALIDATE URL PARAMETERS
$booking_ref = trim($_GET['booking_ref'] ?? '');
$booking_type = $_GET['type'] ?? '';

if (empty($booking_ref) || !in_array($booking_type, ['flight', 'ferry'])) {
    $page_error = "Invalid or missing booking reference.";
} else {
    // 3. SET DYNAMIC CONFIGURATION
    if ($booking_type === 'flight') {
        $config = [
            'booking_table' => 'flight_bookings', 'pass_table' => 'flight_boarding_passes',
            'origin_join_table' => 'airports', 'dest_join_table' => 'airports',
            'origin_id_col' => 'origin_airport_id', 'dest_id_col' => 'destination_airport_id',
            'page_title' => 'Flight Boarding Pass', 'carrier_label' => 'Airline',
            'travel_no_label' => 'Flight No.', 'icon' => 'bi-airplane-fill'
        ];
    } else { // ferry
        $config = [
            'booking_table' => 'ferry_bookings', 'pass_table' => 'ferry_boarding_passes',
            'origin_join_table' => 'ferry_ports', 'dest_join_table' => 'ferry_ports',
            'origin_id_col' => 'origin_port_id', 'dest_id_col' => 'destination_port_id',
            'page_title' => 'Ferry Boarding Pass', 'carrier_label' => 'Ferry Company',
            'travel_no_label' => 'Vessel No.', 'icon' => 'bi-tsunami'
        ];
    }

    // 4. HANDLE FORM SUBMISSION (UPSERT LOGIC)
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $booking_id_to_update = filter_input(INPUT_POST, 'booking_id', FILTER_VALIDATE_INT);
        $post_data = [
            'status' => $_POST['status'],
            'passenger_name' => trim($_POST['passenger_name']), 'pnr_code' => trim($_POST['pnr_code']),
            'carrier_name' => trim($_POST['carrier_name']), 'travel_number' => trim($_POST['travel_number']),
            'seat_number' => trim($_POST['seat_number']), 'gate' => trim($_POST['gate']),
            'departure_datetime' => $_POST['departure_datetime'], 'arrival_datetime' => $_POST['arrival_datetime'],
            'boarding_datetime' => $_POST['boarding_datetime'],
        ];

        $stmt_check = $conn->prepare("SELECT id FROM {$config['pass_table']} WHERE booking_id = ?");
        $stmt_check->bind_param("i", $booking_id_to_update);
        $stmt_check->execute();
        $existing_pass = $stmt_check->get_result()->fetch_assoc();
        $stmt_check->close();

        if ($existing_pass) { // UPDATE
            $sql = "UPDATE {$config['pass_table']} SET status=?, passenger_name=?, pnr_code=?, carrier_name=?, travel_number=?, seat_number=?, gate=?, departure_datetime=?, arrival_datetime=?, boarding_datetime=? WHERE booking_id = ?";
            $stmt = $conn->prepare($sql);
            $update_params = array_values($post_data);
            $update_params[] = $booking_id_to_update;
            $stmt->bind_param("ssssssssssi", ...$update_params);
        } else { // INSERT
            $sql = "INSERT INTO {$config['pass_table']} (booking_id, status, passenger_name, pnr_code, carrier_name, travel_number, seat_number, gate, departure_datetime, arrival_datetime, boarding_datetime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("issssssssss", $booking_id_to_update, ...array_values($post_data));
        }

        if ($stmt->execute()) { $_SESSION['success_message'] = "Boarding pass details saved successfully.";
        } else { $_SESSION['error_message'] = "Error saving details: " . $stmt->error; }
        $stmt->close();
        header("Location: {$booking_type}-bookings.php");
        exit();
    }

    // 5. FETCH DATA FOR FORM
    $origin_code_col = ($booking_type === 'flight') ? 'orig.airport_code as origin_code' : "'' as origin_code";
    $dest_code_col = ($booking_type === 'flight') ? 'dest.airport_code as dest_code' : "'' as dest_code";

    $sql_fetch = "SELECT b.id as booking_id_num, b.*, u.full_name, 
                  orig.name as origin_city, dest.name as dest_city, 
                  $origin_code_col, $dest_code_col, bp.*
                  FROM {$config['booking_table']} b JOIN users u ON b.user_id = u.id
                  LEFT JOIN {$config['origin_join_table']} orig ON b.{$config['origin_id_col']} = orig.id
                  LEFT JOIN {$config['dest_join_table']} dest ON b.{$config['dest_id_col']} = dest.id
                  LEFT JOIN {$config['pass_table']} bp ON b.id = bp.booking_id
                  WHERE b.booking_ref = ?";
    $stmt_fetch = $conn->prepare($sql_fetch);
    $stmt_fetch->bind_param("s", $booking_ref);
    $stmt_fetch->execute();
    $data = $stmt_fetch->get_result()->fetch_assoc();
    $stmt_fetch->close();
    if (!$data) { $page_error = "Booking (Ref: " . htmlspecialchars($booking_ref) . ") not found."; }
}

function format_datetime_for_input($datetime) { return $datetime ? date('Y-m-d\TH:i', strtotime($datetime)) : ''; }

// 6. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<style>
    .boarding-pass { background-color: #fff; color: #333; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; border-radius: 12px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); }
    .pass-main { padding: 20px; }
    .pass-stub { background-color: #f8f9fa; padding: 20px; border-left: 3px dashed #ddd; }
    .pass-header { border-bottom: 1px solid #eee; }
    .pass-label { font-size: 0.7rem; color: #888; font-weight: bold; letter-spacing: 1px; text-transform: uppercase; }
    .pass-data { font-size: 1.25rem; font-weight: 500; line-height: 1.2; font-family: 'Courier New', Courier, monospace; }
    .pass-data-lg { font-size: 3rem; font-weight: bold; }
</style>

<?php if ($page_error): ?>
    <div class="alert alert-danger mt-4"><h4 class="alert-heading">Error</h4><p><?php echo $page_error; ?></p><hr><a href="dashboard.php" class="btn btn-outline-danger">Return to Dashboard</a></div>
<?php else: ?>
<form action="edit-boarding-pass.php?type=<?php echo $booking_type; ?>&booking_ref=<?php echo htmlspecialchars($booking_ref); ?>" method="POST">
    <input type="hidden" name="booking_id" value="<?php echo $data['booking_id_num']; ?>">
    <div class="row g-4">
        <div class="col-lg-7">
            <div class="card shadow-sm">
                 <div class="card-header"><h5 class="mb-0">Edit <?php echo $config['page_title']; ?> Details</h5></div>
                 <div class="card-body">
                    <p class="text-muted">Changes you make here will be reflected in the live preview on the right.</p>
                     <fieldset class="border p-3 rounded-3 mb-3">
                        <legend class="float-none w-auto px-3 h6">Passenger & Itinerary</legend>
                        <div class="mb-3"><label for="passenger_name" class="form-label">Passenger Full Name</label><input type="text" class="form-control" id="passenger_name" name="passenger_name" value="<?php echo htmlspecialchars($data['passenger_name'] ?? $data['full_name']); ?>"></div>
                        <div class="row">
                            <div class="col-md-6 mb-3"><label for="pnr_code" class="form-label">PNR / Booking Ref</label><input type="text" class="form-control" id="pnr_code" name="pnr_code" value="<?php echo htmlspecialchars($data['pnr_code'] ?? ''); ?>"></div>
                            <div class="col-md-6 mb-3"><label for="carrier_name" class="form-label"><?php echo $config['carrier_label']; ?></label><input type="text" class="form-control" id="carrier_name" name="carrier_name" value="<?php echo htmlspecialchars($data['carrier_name'] ?? ''); ?>"></div>
                        </div>
                     </fieldset>
                     <fieldset class="border p-3 rounded-3">
                         <legend class="float-none w-auto px-3 h6">Boarding Details</legend>
                         <div class="row">
                            <div class="col-md-4 mb-3"><label for="travel_number" class="form-label"><?php echo $config['travel_no_label']; ?></label><input type="text" class="form-control" id="travel_number" name="travel_number" value="<?php echo htmlspecialchars($data['travel_number'] ?? ''); ?>"></div>
                            <div class="col-md-4 mb-3"><label for="gate" class="form-label">Gate / Pier</label><input type="text" class="form-control" id="gate" name="gate" value="<?php echo htmlspecialchars($data['gate'] ?? ''); ?>"></div>
                            <div class="col-md-4 mb-3"><label for="seat_number" class="form-label">Seat Number</label><input type="text" class="form-control" id="seat_number" name="seat_number" value="<?php echo htmlspecialchars($data['seat_number'] ?? ''); ?>"></div>
                         </div>
                         <div class="row">
                            <div class="col-md-6 mb-3"><label for="boarding_datetime" class="form-label">Boarding Time</label><input type="datetime-local" class="form-control" id="boarding_datetime" name="boarding_datetime" value="<?php echo format_datetime_for_input($data['boarding_datetime'] ?? null); ?>"></div>
                            <div class="col-md-6 mb-3"><label for="departure_datetime" class="form-label">Departure Time</label><input type="datetime-local" class="form-control" id="departure_datetime" name="departure_datetime" value="<?php echo format_datetime_for_input($data['departure_datetime'] ?? null); ?>"></div>
                         </div>
                         <div class="mb-3"><label for="arrival_datetime" class="form-label">Arrival Time</label><input type="datetime-local" class="form-control" id="arrival_datetime" name="arrival_datetime" value="<?php echo format_datetime_for_input($data['arrival_datetime'] ?? null); ?>"></div>
                         <hr>
                         <div class="mb-3">
                            <label for="status" class="form-label fw-bold">Boarding Pass Status</label>
                            <select class="form-select" id="status" name="status">
                                <option value="Draft" <?php if (($data['status'] ?? 'Draft') === 'Draft') echo 'selected'; ?>>Draft (Not ready for user)</option>
                                <option value="Finalized" <?php if (($data['status'] ?? '') === 'Finalized') echo 'selected'; ?>>Finalized (Ready for user)</option>
                            </select>
                            <small class="text-muted">Set to 'Finalized' when Gate and Seat are confirmed.</small>
                        </div>
                     </fieldset>
                 </div>
            </div>
            <div class="mt-4 d-flex justify-content-end gap-2"><a href="<?php echo $booking_type; ?>-bookings.php" class="btn btn-secondary">Cancel</a><button type="submit" class="btn btn-primary"><i class="bi bi-save-fill me-1"></i> Save Details</button></div>
        </div>
        
        <div class="col-lg-5">
            <div class="sticky-top" style="top: 20px;">
                <div class="boarding-pass row g-0">
                    <div class="pass-main col-8">
                        <div class="pass-header pb-2 mb-3 d-flex justify-content-between">
                            <div><small class="pass-label">Boarding Pass</small><h5 class="mb-0" id="preview-carrier">Airline</h5></div>
                            <i class="bi <?php echo $config['icon']; ?> fs-2"></i>
                        </div>
                        <div class="mb-3"><span class="pass-label">Passenger</span><div class="pass-data" id="preview-passenger-name">---</div></div>
                        <div class="row mb-3">
                            <div class="col-6"><span class="pass-label"><?php echo $config['travel_type'] ?? 'Travel'; ?> No.</span><div class="pass-data" id="preview-flight">--</div></div>
                            <div class="col-6"><span class="pass-label">PNR</span><div class="pass-data" id="preview-pnr">--</div></div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-6"><span class="pass-label">Seat</span><div class="pass-data-lg" id="preview-seat">--</div></div>
                            <div class="col-6"><span class="pass-label">Gate/Pier</span><div class="pass-data-lg" id="preview-gate">--</div></div>
                        </div>
                    </div>
                    <div class="pass-stub col-4">
                        <div class="text-center mb-3"><img id="preview-qr-code" src="https://api.qrserver.com/v1/create-qr-code/?size=80x80&data=DXP-HUB" alt="QR Code"></div>
                        <div class="mb-2"><span class="pass-label"><?php echo $config['travel_type'] ?? 'Travel'; ?> No.</span><div id="preview-stub-flight">--</div></div>
                        <div class="mb-2"><span class="pass-label">Seat</span><div id="preview-stub-seat">--</div></div>
                        <div class="mb-2"><span class="pass-label">Passenger</span><div class="small" id="preview-stub-passenger">---</div></div>
                        <div class="mb-0"><span class="pass-label">Date</span><div id="preview-stub-date">-- ---</div></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const inputs = ['passenger_name', 'pnr_code', 'carrier_name', 'travel_number', 'seat_number', 'gate', 'departure_datetime'];
    
    function formatDate(dateTimeStr) {
        if (!dateTimeStr) return '-- ---';
        return new Date(dateTimeStr).toLocaleDateString('en-US', { month: 'short', day: '2-digit' }).toUpperCase();
    }

    function updatePreview() {
        const pnr = document.getElementById('pnr_code').value || 'DXP-HUB';
        document.getElementById('preview-qr-code').src = `https://api.qrserver.com/v1/create-qr-code/?size=80x80&data=${encodeURIComponent(pnr)}`;
        
        document.getElementById('preview-passenger-name').textContent = document.getElementById('passenger_name').value || 'PASSENGER NAME';
        document.getElementById('preview-carrier').textContent = document.getElementById('carrier_name').value || 'CARRIER';
        document.getElementById('preview-flight').textContent = document.getElementById('travel_number').value || '--';
        document.getElementById('preview-pnr').textContent = document.getElementById('pnr_code').value || '--';
        document.getElementById('preview-seat').textContent = document.getElementById('seat_number').value || '--';
        document.getElementById('preview-gate').textContent = document.getElementById('gate').value || '--';
        
        document.getElementById('preview-stub-flight').textContent = document.getElementById('travel_number').value || '--';
        document.getElementById('preview-stub-seat').textContent = document.getElementById('seat_number').value || '--';
        document.getElementById('preview-stub-passenger').textContent = document.getElementById('passenger_name').value || 'PASSENGER';
        document.getElementById('preview-stub-date').textContent = formatDate(document.getElementById('departure_datetime').value);
    }

    inputs.forEach(id => document.getElementById(id)?.addEventListener('input', updatePreview));
    updatePreview(); // Initial call
});
</script>

<?php include 'admin-footer.php'; ?>
