<?= $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>';
};

$priorityPill = static function (string $priority): string {
    $map = ['low' => 'inactive', 'normal' => 'default', 'high' => 'on_leave', 'urgent' => 'terminated'];
    $class = $map[$priority] ?? 'default';

    return '<span class="enterprise-status-pill enterprise-status-pill--' . esc($class) . '">'
        . esc(ucfirst($priority)) . '</span>';
};

$status = $schedule['status'];
$canEdit = in_array($status, ['planned', 'scheduled'], true);

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

$stopLegLabel = static function (?string $address): string {
    $address = (string) $address;
    if (str_starts_with($address, '[BOARD]')) {
        return 'Board';
    }
    if (str_starts_with($address, '[DROP]')) {
        return 'Drop';
    }
    if (str_starts_with($address, '[RETURN]')) {
        return 'Return pickup';
    }

    return 'Stop';
};

$stopLegText = static function (?string $address): string {
    return preg_replace('/^\[(BOARD|DROP|RETURN)\]\s*/', '', (string) $address) ?: '—';
};

$stops = $stops ?? [];
?>

<?= view('partials/workspace_hero', [
    'workspaceCrumbPill'    => 'Transport',
    'workspaceCrumbCurrent' => $schedule['number'],
    'workspaceTitle'        => esc($schedule['number']),
    'workspaceDesc'         => esc($schedule['title']),
]) ?>

<div class="row g-4">
    <div class="col-lg-8">
        <article class="enterprise-settings-card">
            <div class="enterprise-settings-card__head">
                <i class="fa-solid fa-calendar-check"></i>
                <h2 class="enterprise-settings-card__title">Trip Information</h2>
            </div>
            <dl class="row mb-0 small">
                <dt class="col-sm-4 text-muted">Number</dt>
                <dd class="col-sm-8 fw-semibold"><code><?= esc($schedule['number']) ?></code></dd>
                <dt class="col-sm-4 text-muted">Title</dt>
                <dd class="col-sm-8"><?= esc($schedule['title']) ?></dd>
                <dt class="col-sm-4 text-muted">Route</dt>
                <dd class="col-sm-8"><?= esc($schedule['route_name'] ?? '—') ?></dd>
                <dt class="col-sm-4 text-muted">Vehicle</dt>
                <dd class="col-sm-8"><?= esc($schedule['vehicle_registration'] ?? '—') ?></dd>
                <dt class="col-sm-4 text-muted">Driver</dt>
                <dd class="col-sm-8"><?= esc($schedule['driver_name'] ?? '—') ?></dd>
                <dt class="col-sm-4 text-muted">Date</dt>
                <dd class="col-sm-8"><?= esc($schedule['schedule_date']) ?></dd>
                <dt class="col-sm-4 text-muted">Departure</dt>
                <dd class="col-sm-8"><?= $hm($schedule['departure_time'] ?? null) ?></dd>
                <dt class="col-sm-4 text-muted">Arrival (outbound)</dt>
                <dd class="col-sm-8">
                    <?= $hm($schedule['arrival_time'] ?? null) ?>
                    <?php if (! empty($schedule['shift_start_time'])): ?>
                        <span class="text-muted">(shift <?= $hm($schedule['shift_start_time']) ?>)</span>
                    <?php endif; ?>
                </dd>
                <?php if (! empty($schedule['return_departure_time']) || ! empty($schedule['return_arrival_time'])): ?>
                    <dt class="col-sm-4 text-muted">Return departs</dt>
                    <dd class="col-sm-8">
                        <?= $hm($schedule['return_departure_time'] ?? null) ?>
                        <?php if (! empty($schedule['shift_end_time'])): ?>
                            <span class="text-muted">(shift ends <?= $hm($schedule['shift_end_time']) ?>)</span>
                        <?php endif; ?>
                    </dd>
                    <dt class="col-sm-4 text-muted">Back at base</dt>
                    <dd class="col-sm-8"><?= $hm($schedule['return_arrival_time'] ?? null) ?></dd>
                <?php endif; ?>
                <dt class="col-sm-4 text-muted">Priority</dt>
                <dd class="col-sm-8"><?= $priorityPill($schedule['priority'] ?? 'normal') ?></dd>
                <dt class="col-sm-4 text-muted">Status</dt>
                <dd class="col-sm-8"><?= $statusPill($status) ?></dd>
                <?php if ($status === 'in_progress' || $status === 'completed'): ?>
                    <dt class="col-sm-4 text-muted">Started</dt>
                    <dd class="col-sm-8"><?= esc($schedule['started_at'] ?: '—') ?></dd>
                <?php endif; ?>
                <?php if ($status === 'completed'): ?>
                    <dt class="col-sm-4 text-muted">Completed</dt>
                    <dd class="col-sm-8"><?= esc($schedule['completed_at'] ?: '—') ?></dd>
                <?php endif; ?>
                <dt class="col-sm-4 text-muted">Notes</dt>
                <dd class="col-sm-8"><?= nl2br(esc($schedule['notes'] ?: '—')) ?></dd>
            </dl>
        </article>

        <?php if ($stops !== []): ?>
            <article class="enterprise-settings-card mt-4">
                <div class="enterprise-settings-card__head">
                    <i class="fa-solid fa-route"></i>
                    <h2 class="enterprise-settings-card__title">Transport Legs</h2>
                </div>
                <div class="table-responsive">
                    <table class="enterprise-data-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Leg</th>
                                <th>Time</th>
                                <th>Employee</th>
                                <th>Location</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($stops as $stop): ?>
                                <tr>
                                    <td><?= (int) $stop['stop_order'] ?></td>
                                    <td><span class="badge bg-light text-dark"><?= esc($stopLegLabel($stop['address'] ?? '')) ?></span></td>
                                    <td><strong><?= $hm($stop['pickup_time'] ?? null) ?></strong></td>
                                    <td>
                                        <?= esc($stop['employee_name'] ?? ('#' . $stop['employee_id'])) ?>
                                        <?php if (! empty($stop['employee_number'])): ?>
                                            <div class="text-muted small"><?= esc($stop['employee_number']) ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="small text-muted"><?= esc($stopLegText($stop['address'] ?? '')) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </article>
        <?php endif; ?>
    </div>

    <div class="col-lg-4">
        <article class="enterprise-settings-card">
            <div class="enterprise-settings-card__head">
                <i class="fa-solid fa-bolt"></i>
                <h2 class="enterprise-settings-card__title">Actions</h2>
            </div>
            <div class="d-grid gap-2">
                <?php if ($canEdit): ?>
                    <a href="<?= base_url('transport/scheduling/' . $schedule['id'] . '/edit') ?>" class="btn btn-outline-primary btn-sm">
                        <i class="fa-solid fa-pen me-1"></i> Edit
                    </a>
                <?php endif; ?>

                <?php if ($status === 'planned'): ?>
                    <form action="<?= base_url('transport/scheduling/' . $schedule['id'] . '/confirm') ?>" method="post"
                          onsubmit="return confirm('Confirm this trip?');">
                        <?= csrf_field() ?>
                        <button type="submit" class="btn btn-primary btn-sm w-100">
                            <i class="fa-solid fa-check me-1"></i> Confirm Trip
                        </button>
                    </form>
                <?php endif; ?>

                <?php if ($status === 'scheduled'): ?>
                    <form action="<?= base_url('transport/scheduling/' . $schedule['id'] . '/start') ?>" method="post"
                          onsubmit="return confirm('Start this trip?');">
                        <?= csrf_field() ?>
                        <button type="submit" class="btn btn-primary btn-sm w-100">
                            <i class="fa-solid fa-play me-1"></i> Start Trip
                        </button>
                    </form>
                <?php endif; ?>

                <?php if ($status === 'in_progress'): ?>
                    <form action="<?= base_url('transport/scheduling/' . $schedule['id'] . '/complete') ?>" method="post"
                          onsubmit="return confirm('Mark this trip as completed?');">
                        <?= csrf_field() ?>
                        <button type="submit" class="btn btn-primary btn-sm w-100">
                            <i class="fa-solid fa-flag-checkered me-1"></i> Complete Trip
                        </button>
                    </form>
                <?php endif; ?>

                <?php if (in_array($status, ['planned', 'scheduled', 'in_progress'], true)): ?>
                    <form action="<?= base_url('transport/scheduling/' . $schedule['id'] . '/cancel') ?>" method="post"
                          onsubmit="return confirm('Cancel this trip?');">
                        <?= csrf_field() ?>
                        <button type="submit" class="btn btn-outline-secondary btn-sm w-100">
                            <i class="fa-solid fa-ban me-1"></i> Cancel Trip
                        </button>
                    </form>
                <?php endif; ?>

                <?php if (in_array($status, ['planned', 'cancelled'], true)): ?>
                    <form action="<?= base_url('transport/scheduling/' . $schedule['id'] . '/delete') ?>" method="post"
                          onsubmit="return confirm('Delete this schedule permanently?');">
                        <?= csrf_field() ?>
                        <button type="submit" class="btn btn-outline-danger btn-sm w-100">
                            <i class="fa-solid fa-trash me-1"></i> Delete
                        </button>
                    </form>
                <?php endif; ?>

                <a href="<?= base_url('transport/scheduling') ?>" class="btn btn-outline-secondary btn-sm">Back to Scheduling</a>
            </div>
        </article>
    </div>
</div>

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