<?= $this->extend('layouts/enterprise') ?>

<?= $this->section('content') ?>

<?php
$statusPill = static function (string $status): string {
    $map = [
        'planned'     => 'draft',
        'scheduled'   => 'default',
        'in_progress' => 'active',
        'completed'   => 'active',
        'cancelled'   => 'terminated',
    ];
    $class = $map[$status] ?? 'inactive';

    return '<span class="enterprise-status-pill enterprise-status-pill--' . esc($class) . '">'
        . esc(ucwords(str_replace('_', ' ', $status))) . '</span>';
};

$hm = static fn (?string $t): string => $t ? substr($t, 0, 5) : '—';
$stopsByTrip = $stopsByTrip ?? [];
?>

<?= view('partials/workspace_hero', [
    'workspaceCrumbPill'    => 'Transport',
    'workspaceCrumbCurrent' => 'Driver Schedule Export',
    'workspaceTitle'        => 'Driver Schedule Export',
    'workspaceDesc'         => 'Export driver schedules for all drivers or one selected driver as PDF, CSV, or Word.',
    'workspaceAction'       => [
        'href'  => base_url('transport/scheduling'),
        'label' => 'Back to Scheduling',
        'icon'  => 'fa-solid fa-calendar-check',
    ],
]) ?>

<div class="enterprise-data-panel">
    <div class="enterprise-data-panel__head">
        <h2 class="enterprise-data-panel__title">Export filters</h2>
        <p class="enterprise-data-panel__subtitle">Choose the scope, date range, then download the handoff pack.</p>
    </div>

    <div class="enterprise-data-panel__toolbar">
        <form action="<?= base_url('transport/scheduling/export') ?>" method="get">
            <div class="enterprise-filter-grid">
                <div>
                    <label class="enterprise-field-label">Driver scope</label>
                    <select name="driver_id" class="form-select form-select-sm">
                        <option value="">All drivers</option>
                        <?php foreach ($drivers as $driver): ?>
                            <option value="<?= (int) $driver['id'] ?>"
                                <?= (int) ($filters['driver_id'] ?? 0) === (int) $driver['id'] ? 'selected' : '' ?>>
                                <?= esc($driver['employee_name'] ?: ($driver['number'] ?? ('Driver #' . $driver['id']))) ?>
                                <?php if (! empty($driver['number'])): ?>
                                    (<?= esc($driver['number']) ?>)
                                <?php endif; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="enterprise-field-label">From</label>
                    <input type="date" name="date_from" class="form-control form-control-sm"
                           value="<?= esc($filters['date_from'] ?? '') ?>" required>
                </div>
                <div>
                    <label class="enterprise-field-label">To</label>
                    <input type="date" name="date_to" class="form-control form-control-sm"
                           value="<?= esc($filters['date_to'] ?? '') ?>" required>
                </div>
                <div>
                    <label class="enterprise-field-label">Status</label>
                    <select name="status" class="form-select form-select-sm">
                        <option value="">Any</option>
                        <?php foreach (['planned', 'scheduled', 'in_progress', 'completed', 'cancelled'] as $s): ?>
                            <option value="<?= $s ?>" <?= ($filters['status'] ?? '') === $s ? 'selected' : '' ?>>
                                <?= esc(ucwords(str_replace('_', ' ', $s))) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="enterprise-filter-actions">
                    <button type="submit" class="btn btn-sm btn-primary">Preview</button>
                </div>
            </div>
        </form>
    </div>

    <div class="enterprise-data-panel__body">
        <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
            <div class="text-muted small">
                <?= (int) $tripCount ?> trip<?= (int) $tripCount === 1 ? '' : 's' ?>
                across <?= count($groups) ?> driver<?= count($groups) === 1 ? '' : 's' ?>
            </div>
            <div class="d-flex flex-wrap gap-2">
                <?= view('Modules\Reports\Views\partials\export_buttons', [
                    'actionPath'  => 'transport/scheduling/export',
                    'query'       => $exportQuery,
                    'includeWord' => true,
                ]) ?>
            </div>
        </div>

        <?php if ($groups === []): ?>
            <div class="text-center text-muted py-5">No driver schedules match the selected filters.</div>
        <?php else: ?>
            <?php foreach ($groups as $group): ?>
                <div class="mb-4">
                    <h3 class="h6 mb-2">
                        <i class="fa-solid fa-id-card me-1 text-muted"></i>
                        <?= esc($group['driver_name']) ?>
                        <?php if ($group['driver_number'] !== ''): ?>
                            <code class="ms-1"><?= esc($group['driver_number']) ?></code>
                        <?php endif; ?>
                        <span class="text-muted fw-normal">· <?= count($group['trips']) ?> trip<?= count($group['trips']) === 1 ? '' : 's' ?></span>
                    </h3>
                    <div class="table-responsive">
                        <table class="enterprise-data-table">
                            <thead>
                                <tr>
                                    <th>Trip #</th>
                                    <th>Date</th>
                                    <th>Depart</th>
                                    <th>Arrive</th>
                                    <th>Return</th>
                                    <th>Back</th>
                                    <th>Route</th>
                                    <th>Vehicle</th>
                                    <th>Title</th>
                                    <th>Status</th>
                                    <th>Transport legs</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($group['trips'] as $trip): ?>
                                    <?php
                                    $tripStops = $stopsByTrip[(int) ($trip['id'] ?? 0)] ?? [];
                                    $legsText = '—';
                                    if ($tripStops !== []) {
                                        $parts = [];
                                        foreach ($tripStops as $stop) {
                                            $addr = (string) ($stop['address'] ?? '');
                                            $leg = str_starts_with($addr, '[BOARD]') ? 'Board'
                                                : (str_starts_with($addr, '[DROP]') ? 'Drop'
                                                : (str_starts_with($addr, '[RETURN]') ? 'Return' : 'Stop'));
                                            $parts[] = $leg . ' ' . ($stop['employee_name'] ?? '') . ' ' . $hm($stop['pickup_time'] ?? null);
                                        }
                                        $legsText = implode(' · ', $parts);
                                    }
                                    ?>
                                    <tr>
                                        <td><code><?= esc($trip['number']) ?></code></td>
                                        <td><?= esc($trip['schedule_date']) ?></td>
                                        <td><?= $hm($trip['departure_time'] ?? null) ?></td>
                                        <td><?= $hm($trip['arrival_time'] ?? null) ?></td>
                                        <td><?= $hm($trip['return_departure_time'] ?? null) ?></td>
                                        <td><?= $hm($trip['return_arrival_time'] ?? null) ?></td>
                                        <td><?= esc($trip['route_name'] ?? '—') ?></td>
                                        <td><?= esc($trip['vehicle_registration'] ?? '—') ?></td>
                                        <td>
                                            <a href="<?= base_url('transport/scheduling/' . $trip['id']) ?>" class="enterprise-data-table__primary">
                                                <?= esc($trip['title']) ?>
                                            </a>
                                        </td>
                                        <td><?= $statusPill((string) $trip['status']) ?></td>
                                        <td class="small text-muted" style="max-width: 280px;"><?= esc($legsText) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<?= $this->endSection() ?>
