<?php
session_start();

require_once __DIR__ . '/../../includes/helpers.php';
require_once __DIR__ . '/../../includes/layout.php';
require_once __DIR__ . '/../../includes/expense_shell.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) ($_POST['trip_id'] ?? $_GET['trip_id'] ?? 0);
if ($tripId <= 0) {
    redirect(page_url('trips'));
}

$trip = trip_fetch_by_id($tripId, $userId);
if (!$trip) {
    flash('trip_error', 'That trip could not be found.');
    redirect(page_url('trips'));
}

$modes = ['flight', 'hotel', 'car', 'bus', 'train'];
$mode = strtolower(trim((string) ($_GET['selectedTravelMode'] ?? $_GET['mode'] ?? 'flight')));
if (!in_array($mode, $modes, true)) {
    $mode = 'flight';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postedRows = $_POST['rows'] ?? [];
    if (!is_array($postedRows)) {
        $postedRows = [];
    }

    $normalizedRows = [];
    foreach ($postedRows as $row) {
        if (!is_array($row)) {
            continue;
        }
        $rowMode = strtolower(trim((string) ($row['mode'] ?? $mode)));
        if (!in_array($rowMode, $modes, true)) {
            continue;
        }
        $row['mode'] = $rowMode;
        $normalizedRows[] = $row;
    }

    if ($normalizedRows === []) {
        flash('trip_error', 'Please add at least one itinerary item.');
        redirect(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=' . $mode));
    }

    $saved = trip_store_itineraries($tripId, $userId, $normalizedRows);
    if ($saved >= 0) {
        flash('trip_success', 'Itinerary saved.');
        redirect(route_url('trips/view/?trip_id=' . $tripId . '&tab=itinerary'));
    }

    flash('trip_error', 'We could not save the itinerary right now.');
    redirect(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=' . $mode));
}

$tripNumber = trip_trip_number($tripId);
$allItineraries = trip_fetch_itineraries($tripId);
$modeRows = array_values(array_filter($allItineraries, static fn(array $row): bool => (string) ($row['mode'] ?? '') === $mode));
$tripSuccess = flash('trip_success');
$tripError = flash('trip_error');

$modeLabels = [
    'flight' => 'Flight',
    'hotel' => 'Hotel',
    'car' => 'Car Rental',
    'bus' => 'Bus',
    'train' => 'Train',
];

$modeIcons = [
    'flight' => 'fa-solid fa-plane',
    'hotel' => 'fa-solid fa-hotel',
    'car' => 'fa-solid fa-car-side',
    'bus' => 'fa-solid fa-bus',
    'train' => 'fa-solid fa-train-subway',
];

$plannerLocations = trip_planner_location_options();
$plannerPreferences = trip_planner_preference_options();

function trip_planner_decode_payload(array $row): array
{
    $payload = [];
    if (!empty($row['payload_json'])) {
        $decoded = json_decode((string) $row['payload_json'], true);
        if (is_array($decoded)) {
            $payload = $decoded;
        }
    }
    return $payload;
}

function trip_planner_date_value(?string $value): string
{
    $value = trim((string) $value);
    if ($value === '') {
        return '';
    }

    $formats = ['Y-m-d', 'd M Y', 'd/m/Y', 'd-m-Y', 'd M, Y'];
    foreach ($formats as $format) {
        $date = DateTime::createFromFormat($format, $value);
        if ($date instanceof DateTime) {
            return $date->format('Y-m-d');
        }
    }

    $timestamp = strtotime($value);
    if ($timestamp !== false) {
        return date('Y-m-d', $timestamp);
    }

    return '';
}

function trip_planner_input(string $name, string $value = '', string $placeholder = ''): string
{
    return '<input type="text" name="' . e($name) . '" value="' . e($value) . '" placeholder="' . e($placeholder) . '">';
}

render_expense_shell_start('Plan Itinerary | Expense', 'dashboard-page trips-page trip-planner-page', 'trips');
?>
<div class="trip-planner-shell">
    <header class="trip-planner-head">
        <div>
            <p class="trip-planner-kicker">Plan Itinerary</p>
            <h1>(<?= e($tripNumber) ?> - <?= e((string) $trip['trip_name']) ?>)</h1>
        </div>
        <a class="trip-planner-close" href="<?= e(route_url('trips/view/?trip_id=' . $tripId)) ?>" aria-label="Close">
            <i class="fa-solid fa-xmark"></i>
        </a>
    </header>

    <?php if ($tripSuccess !== null): ?>
        <div class="trip-banner trip-banner--success"><?= e($tripSuccess) ?></div>
    <?php endif; ?>
    <?php if ($tripError !== null): ?>
        <div class="trip-banner trip-banner--error"><?= e($tripError) ?></div>
    <?php endif; ?>

    <div class="trip-planner-layout">
        <aside class="trip-planner-rail">
            <?php foreach ($modes as $itemMode): ?>
                <a class="trip-planner-rail-item<?= $mode === $itemMode ? ' is-active' : '' ?>" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=' . $itemMode)) ?>">
                    <i class="<?= e($modeIcons[$itemMode] ?? 'fa-solid fa-circle') ?>" aria-hidden="true"></i>
                    <span><?= e($modeLabels[$itemMode] ?? ucfirst($itemMode)) ?></span>
                </a>
            <?php endforeach; ?>
        </aside>

        <main class="trip-planner-main">
            <form method="post" class="trip-planner-form" data-trip-planner-form>
                <input type="hidden" name="trip_id" value="<?= (int) $tripId ?>">

                <section class="trip-planner-section">
                    <header class="trip-planner-section-head">
                        <h2><?= e($modeLabels[$mode] ?? ucfirst($mode)) ?></h2>
                        <div class="trip-planner-swap">
                            <?php if ($mode === 'flight'): ?>
                                <button type="button" class="trip-planner-pill is-active" data-planner-leg-choice="one_way">One Way</button>
                                <button type="button" class="trip-planner-pill" data-planner-leg-choice="round_trip">Round Trip</button>
                                <button type="button" class="trip-planner-pill" data-planner-leg-choice="multi_city">Multi-city</button>
                            <?php endif; ?>
                        </div>
                    </header>

                    <div class="trip-planner-rows" data-planner-mode="<?= e($mode) ?>">
                        <?php if ($modeRows === []): ?>
                            <?php $modeRows = [['mode' => $mode, 'payload_json' => null, 'leg_type' => $mode === 'flight' ? 'round_trip' : 'single', 'item_title' => '']]; ?>
                        <?php endif; ?>

                        <?php foreach ($modeRows as $index => $row): ?>
                            <?php $payload = trip_planner_decode_payload($row); ?>
                            <article class="trip-planner-card" data-planner-row>
                                <div class="trip-planner-card-head">
                                    <strong><?= e($modeLabels[$mode] ?? ucfirst($mode)) ?></strong>
                                    <button type="button" class="trip-planner-remove" data-planner-remove aria-label="Remove itinerary">
                                        <i class="fa-regular fa-trash-can"></i>
                                    </button>
                                </div>

                                <input type="hidden" name="rows[<?= (int) $index ?>][mode]" value="<?= e($mode) ?>">
                                <input type="hidden" name="rows[<?= (int) $index ?>][leg_type]" value="<?= e((string) ($row['leg_type'] ?? ($mode === 'flight' ? 'round_trip' : 'single'))) ?>" data-leg-type>
                                <input type="hidden" name="rows[<?= (int) $index ?>][item_title]" value="<?= e((string) ($row['item_title'] ?? '')) ?>">

                                <?php if ($mode === 'flight'): ?>
                                    <div class="trip-planner-grid trip-planner-grid--flight">
                                        <label><span>Depart from *</span><input type="text" name="rows[<?= (int) $index ?>][depart_from]" value="<?= e((string) ($payload['depart_from'] ?? '')) ?>" placeholder="Select City"></label>
                                        <label><span>Arrive at *</span><input type="text" name="rows[<?= (int) $index ?>][arrive_at]" value="<?= e((string) ($payload['arrive_at'] ?? '')) ?>" placeholder="Select City"></label>
                                        <label><span>Departure date *</span><input type="date" name="rows[<?= (int) $index ?>][departure_date]" value="<?= e(trip_planner_date_value((string) ($payload['departure_date'] ?? ''))) ?>"></label>
                                        <label data-return-field="<?= e((string) ($row['leg_type'] ?? 'round_trip')) ?>"><span>Return date *</span><input type="date" name="rows[<?= (int) $index ?>][return_date]" value="<?= e(trip_planner_date_value((string) ($payload['return_date'] ?? ''))) ?>"></label>
                                    </div>
                                    <div class="trip-planner-preferences">
                                        <label><span>Time</span><input type="text" name="rows[<?= (int) $index ?>][time_preference]" value="<?= e((string) ($payload['time_preference'] ?? '')) ?>" placeholder="Time"></label>
                                        <label><span>Class</span><input type="text" name="rows[<?= (int) $index ?>][class_preference]" value="<?= e((string) ($payload['class_preference'] ?? '')) ?>" placeholder="Class"></label>
                                        <label><span>Seat</span><input type="text" name="rows[<?= (int) $index ?>][seat_preference]" value="<?= e((string) ($payload['seat_preference'] ?? '')) ?>" placeholder="Seat"></label>
                                        <label><span>Meal</span><input type="text" name="rows[<?= (int) $index ?>][meal_preference]" value="<?= e((string) ($payload['meal_preference'] ?? '')) ?>" placeholder="Asian Vegetarian Meal"></label>
                                    </div>
                                <?php elseif ($mode === 'hotel'): ?>
                                    <div class="trip-planner-grid trip-planner-grid--hotel">
                                        <label class="trip-planner-wide"><span>Location *</span><input type="text" name="rows[<?= (int) $index ?>][location]" value="<?= e((string) ($payload['location'] ?? '')) ?>" placeholder="Select or type city"></label>
                                        <label><span>Check-in date *</span><input type="date" name="rows[<?= (int) $index ?>][check_in_date]" value="<?= e(trip_planner_date_value((string) ($payload['check_in_date'] ?? ''))) ?>"></label>
                                        <label><span>Check-in time</span><input type="text" name="rows[<?= (int) $index ?>][check_in_time]" value="<?= e((string) ($payload['check_in_time'] ?? '')) ?>" placeholder="HH:MM"></label>
                                        <label><span>Check-out date *</span><input type="date" name="rows[<?= (int) $index ?>][check_out_date]" value="<?= e(trip_planner_date_value((string) ($payload['check_out_date'] ?? ''))) ?>"></label>
                                        <label><span>Check-out time</span><input type="text" name="rows[<?= (int) $index ?>][check_out_time]" value="<?= e((string) ($payload['check_out_time'] ?? '')) ?>" placeholder="HH:MM"></label>
                                    </div>
                                <?php elseif ($mode === 'car'): ?>
                                    <div class="trip-planner-car-stack">
                                        <div class="trip-planner-grid trip-planner-grid--car-locations">
                                            <label><span>Pick-up location *</span><input type="text" name="rows[<?= (int) $index ?>][pickup_location]" value="<?= e((string) ($payload['pickup_location'] ?? '')) ?>" placeholder="Select or type city"></label>
                                            <label><span>Drop-off location *</span><input type="text" name="rows[<?= (int) $index ?>][dropoff_location]" value="<?= e((string) ($payload['dropoff_location'] ?? '')) ?>" placeholder="Select or type city"></label>
                                        </div>
                                        <div class="trip-planner-grid trip-planner-grid--car-dates">
                                            <label><span>Pick-up date *</span><input type="date" name="rows[<?= (int) $index ?>][pickup_date]" value="<?= e(trip_planner_date_value((string) ($payload['pickup_date'] ?? ''))) ?>"></label>
                                            <label><span>Pick-up time</span><input type="text" name="rows[<?= (int) $index ?>][pickup_time]" value="<?= e((string) ($payload['pickup_time'] ?? '')) ?>" placeholder="HH:MM"></label>
                                            <label><span>Drop-off date *</span><input type="date" name="rows[<?= (int) $index ?>][dropoff_date]" value="<?= e(trip_planner_date_value((string) ($payload['dropoff_date'] ?? ''))) ?>"></label>
                                            <label><span>Drop-off time</span><input type="text" name="rows[<?= (int) $index ?>][dropoff_time]" value="<?= e((string) ($payload['dropoff_time'] ?? '')) ?>" placeholder="HH:MM"></label>
                                        </div>
                                        <div class="trip-planner-preferences trip-planner-preferences--car">
                                            <label><span>Car type</span><input type="text" name="rows[<?= (int) $index ?>][car_type]" value="<?= e((string) ($payload['car_type'] ?? '')) ?>" placeholder="Car Type"></label>
                                            <label><span>Driver required?</span><input type="text" name="rows[<?= (int) $index ?>][driver_required]" value="<?= e((string) ($payload['driver_required'] ?? '')) ?>" placeholder="Yes / No"></label>
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <div class="trip-planner-grid trip-planner-grid--basic">
                                        <label><span>Depart from *</span><input type="text" name="rows[<?= (int) $index ?>][depart_from]" value="<?= e((string) ($payload['depart_from'] ?? '')) ?>" placeholder="Select or type city"></label>
                                        <label><span>Arrive at *</span><input type="text" name="rows[<?= (int) $index ?>][arrive_at]" value="<?= e((string) ($payload['arrive_at'] ?? '')) ?>" placeholder="Select or type city"></label>
                                        <label><span>Departure date *</span><input type="date" name="rows[<?= (int) $index ?>][departure_date]" value="<?= e(trip_planner_date_value((string) ($payload['departure_date'] ?? ''))) ?>"></label>
                                    </div>
                                <?php endif; ?>

                                <label class="trip-planner-description"><span>Description</span><textarea name="rows[<?= (int) $index ?>][description]" rows="2" placeholder="Max 500 characters"><?= e((string) ($payload['description'] ?? '')) ?></textarea></label>
                            </article>
                        <?php endforeach; ?>
                    </div>

                    <button type="button" class="trip-planner-add" data-planner-add>+ Add <?= e($modeLabels[$mode] ?? ucfirst($mode)) ?></button>
                </section>

                <footer class="trip-planner-footer">
                    <button type="submit" class="trip-primary">Save</button>
                    <a class="trip-secondary" href="<?= e(route_url('trips/view/?trip_id=' . $tripId)) ?>">Cancel</a>
                </footer>
            </form>

            <template data-planner-template="<?= e($mode) ?>">
                <article class="trip-planner-card" data-planner-row>
                    <div class="trip-planner-card-head">
                        <strong><?= e($modeLabels[$mode] ?? ucfirst($mode)) ?></strong>
                        <button type="button" class="trip-planner-remove" data-planner-remove aria-label="Remove itinerary">
                            <i class="fa-regular fa-trash-can"></i>
                        </button>
                    </div>
                    <input type="hidden" data-field="mode" value="<?= e($mode) ?>">
                    <input type="hidden" data-field="leg_type" value="<?= e($mode === 'flight' ? 'round_trip' : 'single') ?>">
                    <input type="hidden" data-field="item_title" value="">
                    <?php if ($mode === 'flight'): ?>
                        <div class="trip-planner-grid trip-planner-grid--flight">
                            <label><span>Depart from *</span><input type="text" data-field="depart_from" placeholder="Select City"></label>
                            <label><span>Arrive at *</span><input type="text" data-field="arrive_at" placeholder="Select City"></label>
                            <label><span>Departure date *</span><input type="date" data-field="departure_date"></label>
                            <label data-return-field="round_trip"><span>Return date *</span><input type="date" data-field="return_date"></label>
                        </div>
                        <div class="trip-planner-preferences">
                            <label><span>Time</span><input type="text" data-field="time_preference" placeholder="Time"></label>
                            <label><span>Class</span><input type="text" data-field="class_preference" placeholder="Class"></label>
                            <label><span>Seat</span><input type="text" data-field="seat_preference" placeholder="Seat"></label>
                            <label><span>Meal</span><input type="text" data-field="meal_preference" placeholder="Asian Vegetarian Meal"></label>
                        </div>
                    <?php elseif ($mode === 'hotel'): ?>
                        <div class="trip-planner-grid trip-planner-grid--hotel">
                            <label class="trip-planner-wide"><span>Location *</span><input type="text" data-field="location" placeholder="Select or type city"></label>
                            <label><span>Check-in date *</span><input type="date" data-field="check_in_date"></label>
                            <label><span>Check-in time</span><input type="text" data-field="check_in_time" placeholder="HH:MM"></label>
                            <label><span>Check-out date *</span><input type="date" data-field="check_out_date"></label>
                            <label><span>Check-out time</span><input type="text" data-field="check_out_time" placeholder="HH:MM"></label>
                        </div>
                    <?php elseif ($mode === 'car'): ?>
                        <div class="trip-planner-car-stack">
                            <div class="trip-planner-grid trip-planner-grid--car-locations">
                                <label><span>Pick-up location *</span><input type="text" data-field="pickup_location" placeholder="Select or type city"></label>
                                <label><span>Drop-off location *</span><input type="text" data-field="dropoff_location" placeholder="Select or type city"></label>
                            </div>
                            <div class="trip-planner-grid trip-planner-grid--car-dates">
                                <label><span>Pick-up date *</span><input type="date" data-field="pickup_date"></label>
                                <label><span>Pick-up time</span><input type="text" data-field="pickup_time" placeholder="HH:MM"></label>
                                <label><span>Drop-off date *</span><input type="date" data-field="dropoff_date"></label>
                                <label><span>Drop-off time</span><input type="text" data-field="dropoff_time" placeholder="HH:MM"></label>
                            </div>
                            <div class="trip-planner-preferences trip-planner-preferences--car">
                                <label><span>Car type</span><input type="text" data-field="car_type" placeholder="Car Type"></label>
                                <label><span>Driver required?</span><input type="text" data-field="driver_required" placeholder="Yes / No"></label>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="trip-planner-grid trip-planner-grid--basic">
                            <label><span>Depart from *</span><input type="text" data-field="depart_from" placeholder="Select or type city"></label>
                            <label><span>Arrive at *</span><input type="text" data-field="arrive_at" placeholder="Select or type city"></label>
                            <label><span>Departure date *</span><input type="date" data-field="departure_date"></label>
                        </div>
                    <?php endif; ?>
                    <label class="trip-planner-description"><span>Description</span><textarea data-field="description" rows="2" placeholder="Max 500 characters"></textarea></label>
                </article>
            </template>
        </main>

        <aside class="trip-planner-summary panel">
            <strong>Itinerary Summary</strong>
            <?php if ($allItineraries === []): ?>
                <p>No itinerary has been added.</p>
            <?php else: ?>
                <div class="trip-planner-summary-list">
                    <?php foreach ($allItineraries as $summaryRow): ?>
                        <?php $summaryPayload = trip_planner_decode_payload($summaryRow); ?>
                        <article class="trip-planner-summary-item">
                            <span><?= e($modeLabels[(string) ($summaryRow['mode'] ?? 'flight')] ?? ucfirst((string) ($summaryRow['mode'] ?? 'flight'))) ?></span>
                            <strong><?= e((string) ($summaryRow['item_title'] ?: ($summaryPayload['depart_from'] ?? $summaryPayload['location'] ?? 'Itinerary'))) ?></strong>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </aside>
    </div>
</div>
<script>
window.tripPlannerLocations = <?= json_encode($plannerLocations, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
window.tripPlannerPreferenceOptions = <?= json_encode($plannerPreferences, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
</script>
<?php render_expense_shell_end(); ?>
