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

<?= $this->section('styles') ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css">
<?= $this->endSection() ?>

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

<?php
$statusPill = static function (string $status): string {
    $map = [
        'draft'            => 'inactive',
        'pending_approval' => 'on_leave',
        'approved'         => 'active',
        'rejected'         => '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) : '—';

$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) ?: '—';
};

// Map payload: one entry per route with geometry + stops.
$mapRoutes = [];
foreach ($routes as $route) {
    $geometry = $route['route_geometry'] ? json_decode($route['route_geometry'], true) : null;
    $routeStops = [];
    foreach ($stops[(int) $route['id']] ?? [] as $stop) {
        $routeStops[] = [
            'lat'   => (float) $stop['latitude'],
            'lng'   => (float) $stop['longitude'],
            'label' => $stop['stop_order'] . '. ' . ($stop['employee_name'] ?? '') . ' — ' . substr((string) $stop['pickup_time'], 0, 5),
        ];
    }
    $mapRoutes[] = [
        'name'        => $route['route_name'],
        'date'        => $route['service_date'],
        'geometry'    => $geometry,
        'stops'       => $routeStops,
        'origin'      => ($route['origin_latitude'] ?? null) ? ['lat' => (float) $route['origin_latitude'], 'lng' => (float) $route['origin_longitude'], 'label' => 'Origin: ' . $route['origin_name']] : null,
        'destination' => ($route['destination_latitude'] ?? null) ? ['lat' => (float) $route['destination_latitude'], 'lng' => (float) $route['destination_longitude'], 'label' => 'Destination: ' . $route['destination_name']] : null,
    ];
}
$mapRoutesJson = json_encode($mapRoutes, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);

// Group routes by date for schedule tables.
$routesByDate = [];
foreach ($routes as $route) {
    $routesByDate[$route['service_date']][] = $route;
}

$errors   = array_filter($conflicts, static fn (array $c): bool => ($c['severity'] ?? '') === 'error');
$warnings = array_filter($conflicts, static fn (array $c): bool => ($c['severity'] ?? '') !== 'error');
?>

<?= view('partials/workspace_hero', [
    'workspaceCrumbPill'    => 'Transport',
    'workspaceCrumbCurrent' => $plan['number'],
    'workspaceTitle'        => $plan['title'],
    'workspaceDesc'         => 'AI-generated transportation plan for ' . $plan['plan_start_date'] . ' to ' . $plan['plan_end_date'] . '. Proposed schedules only — nothing is published until approval.',
]) ?>

<div class="d-flex flex-wrap align-items-center gap-2 mb-4">
    <?= $statusPill($plan['status']) ?>
    <span class="text-muted small">
        Generated by <?= esc($plan['generated_by_username'] ?? 'system') ?>
        <?= $plan['created_at'] ? 'on ' . esc($plan['created_at']) : '' ?>
        <?php if ($plan['status'] === 'approved'): ?>
            · Approved by <?= esc($plan['approved_by_username'] ?? '—') ?> on <?= esc($plan['approved_at']) ?>
        <?php endif; ?>
    </span>
    <div class="ms-auto d-flex gap-2">
        <?php if ($plan['status'] === 'draft' && $canGenerate): ?>
            <form action="<?= base_url('transport/ai/plans/' . $plan['id'] . '/submit') ?>" method="post">
                <?= csrf_field() ?>
                <button type="submit" class="btn btn-sm btn-primary">
                    <i class="fa-solid fa-paper-plane me-1"></i> Submit for Approval
                </button>
            </form>
        <?php endif; ?>
        <?php if ($plan['status'] === 'pending_approval' && $canApprove): ?>
            <form action="<?= base_url('transport/ai/plans/' . $plan['id'] . '/approve') ?>" method="post" data-tpin-confirm
                  onsubmit="return confirm('Approve this plan? All routes will be published as official transport schedules.');">
                <?= csrf_field() ?>
                <button type="submit" class="btn btn-sm btn-success">
                    <i class="fa-solid fa-check me-1"></i> Approve & Publish
                </button>
            </form>
            <button type="button" class="btn btn-sm btn-outline-danger" data-bs-toggle="modal" data-bs-target="#reject-plan-modal">
                <i class="fa-solid fa-xmark me-1"></i> Reject
            </button>
        <?php endif; ?>
    </div>
</div>

<?php if ($plan['status'] === 'rejected' && $plan['rejection_reason']): ?>
    <div class="alert alert-danger">
        <strong>Rejected:</strong> <?= esc($plan['rejection_reason']) ?>
    </div>
<?php endif; ?>

<!-- Fleet summary -->
<div class="row g-3 mb-4">
    <?php
    $kpis = [
        ['label' => 'Optimized Routes', 'value' => (int) $plan['total_routes'], 'icon' => 'fa-route'],
        ['label' => 'Employees Transported', 'value' => (int) $plan['total_employees'], 'icon' => 'fa-users'],
        ['label' => 'Vehicles Used', 'value' => (int) ($fleetSummary['vehicles_used'] ?? 0), 'icon' => 'fa-truck'],
        ['label' => 'Drivers Used', 'value' => (int) ($fleetSummary['drivers_used'] ?? 0), 'icon' => 'fa-id-card'],
        ['label' => 'Total Distance', 'value' => number_format((float) $plan['total_distance_km'], 1) . ' km', 'icon' => 'fa-road'],
        ['label' => 'Travel Time', 'value' => number_format((int) $plan['total_duration_minutes']) . ' min', 'icon' => 'fa-clock'],
        ['label' => 'Est. Fuel Usage', 'value' => number_format((float) $plan['total_fuel_litres'], 1) . ' L', 'icon' => 'fa-gas-pump'],
        ['label' => 'Est. Transport Cost', 'value' => number_format((float) $plan['total_cost'], 3), 'icon' => 'fa-coins'],
    ];
    ?>
    <?php foreach ($kpis as $kpi): ?>
        <div class="col-md-3 col-sm-6">
            <article class="enterprise-kpi-card">
                <div class="enterprise-kpi-header">
                    <span class="enterprise-kpi-label"><?= esc($kpi['label']) ?></span>
                    <span class="enterprise-kpi-icon"><i class="fa-solid <?= esc($kpi['icon']) ?>"></i></span>
                </div>
                <div class="enterprise-kpi-value" style="font-size:1.35rem;"><?= esc((string) $kpi['value']) ?></div>
            </article>
        </div>
    <?php endforeach; ?>
</div>

<!-- Optimization summary -->
<article class="enterprise-settings-card mb-4">
    <div class="enterprise-settings-card__head">
        <i class="fa-solid fa-wand-magic-sparkles"></i>
        <h2 class="enterprise-settings-card__title">Optimization Summary</h2>
    </div>
    <p class="mb-0" style="white-space:pre-line;"><?= esc($plan['optimization_summary'] ?: 'No summary available.') ?></p>
</article>

<!-- Conflicts -->
<article class="enterprise-settings-card mb-4">
    <div class="enterprise-settings-card__head">
        <i class="fa-solid fa-triangle-exclamation"></i>
        <h2 class="enterprise-settings-card__title">
            Conflicts Detected
            <?php if ($conflicts === []): ?>
                <span class="enterprise-status-pill enterprise-status-pill--active ms-2">None</span>
            <?php else: ?>
                <span class="enterprise-status-pill enterprise-status-pill--terminated ms-2"><?= count($errors) ?> errors</span>
                <span class="enterprise-status-pill enterprise-status-pill--on_leave ms-1"><?= count($warnings) ?> warnings</span>
            <?php endif; ?>
        </h2>
    </div>
    <?php if ($conflicts === []): ?>
        <p class="text-muted mb-0">All validation rules passed: driver availability, license matching, vehicle availability and capacity, no overlapping schedules, and on-time arrivals.</p>
    <?php else: ?>
        <div class="table-responsive">
            <table class="enterprise-data-table">
                <thead>
                    <tr>
                        <th>Severity</th>
                        <th>Date</th>
                        <th>Route</th>
                        <th>Issue</th>
                        <th>Recommended Solutions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($conflicts as $conflict): ?>
                        <tr>
                            <td>
                                <?php if (($conflict['severity'] ?? '') === 'error'): ?>
                                    <span class="enterprise-status-pill enterprise-status-pill--terminated">Error</span>
                                <?php else: ?>
                                    <span class="enterprise-status-pill enterprise-status-pill--on_leave">Warning</span>
                                <?php endif; ?>
                            </td>
                            <td><?= esc($conflict['service_date'] ?? '—') ?></td>
                            <td><?= esc($conflict['route_name'] ?? '—') ?></td>
                            <td><?= esc($conflict['message']) ?></td>
                            <td>
                                <?php if (! empty($conflict['recommendations'])): ?>
                                    <ul class="mb-0 small">
                                        <?php foreach ($conflict['recommendations'] as $rec): ?>
                                            <li><?= esc($rec) ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</article>

<!-- Route map -->
<article class="enterprise-settings-card mb-4">
    <div class="enterprise-settings-card__head">
        <i class="fa-solid fa-map"></i>
        <h2 class="enterprise-settings-card__title">Route Map</h2>
    </div>
    <div id="ai-plan-map" style="height:520px;border-radius:8px;border:1px solid #e5e7eb;"></div>
    <p class="text-muted small mt-2 mb-0">Colored lines are the garage-to-site road paths; markers show boarding at the origin. Travel times are typical driving times (no live traffic).</p>
</article>

<!-- Optimized routes -->
<div class="enterprise-data-panel mb-4">
    <div class="enterprise-data-panel__head">
        <h2 class="enterprise-data-panel__title">Optimized Routes</h2>
        <p class="enterprise-data-panel__subtitle">Click a route to see assigned staff and boarding time.</p>
    </div>
    <div class="enterprise-data-panel__body">
        <div class="table-responsive">
            <table class="enterprise-data-table">
                <thead>
                    <tr>
                        <th></th>
                        <th>Route</th>
                        <th>Date</th>
                        <th>Start → Destination</th>
                        <th>Vehicle</th>
                        <th>Driver</th>
                        <th class="text-end">Pax</th>
                        <th class="text-end">Km</th>
                        <th class="text-end">Min</th>
                        <th class="text-end">Fuel (L)</th>
                        <th class="text-end">Cost</th>
                        <th>Depart</th>
                        <th>Arrive</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($routes as $route): ?>
                        <?php $routeStops = $stops[(int) $route['id']] ?? []; ?>
                        <tr data-bs-toggle="collapse" data-bs-target="#route-stops-<?= (int) $route['id'] ?>" style="cursor:pointer;">
                            <td><i class="fa-solid fa-chevron-down small text-muted"></i></td>
                            <td class="enterprise-data-table__primary"><?= esc($route['route_name']) ?></td>
                            <td><?= esc($route['service_date']) ?></td>
                            <td class="small"><?= esc($route['origin_name'] ?? '—') ?> → <?= esc($route['destination_name'] ?? '—') ?></td>
                            <td><?= esc($route['vehicle_registration'] ?? 'Unassigned') ?></td>
                            <td><?= esc($route['driver_name'] ?? 'Unassigned') ?></td>
                            <td class="text-end"><?= (int) $route['employee_count'] ?><?= $route['vehicle_capacity'] ? '/' . (int) $route['vehicle_capacity'] : '' ?></td>
                            <td class="text-end"><?= number_format((float) $route['total_distance_km'], 1) ?></td>
                            <td class="text-end"><?= (int) $route['estimated_duration_minutes'] ?></td>
                            <td class="text-end"><?= number_format((float) $route['estimated_fuel_litres'], 1) ?></td>
                            <td class="text-end"><?= number_format((float) $route['estimated_cost'], 3) ?></td>
                            <td><?= $hm($route['departure_time']) ?></td>
                            <td><?= $hm($route['arrival_time']) ?> <span class="text-muted small">(shift <?= $hm($route['shift_start_time']) ?>)</span></td>
                        </tr>
                        <tr class="collapse" id="route-stops-<?= (int) $route['id'] ?>">
                            <td colspan="13" class="bg-light">
                                <div class="p-2">
                                    <strong class="small">Staff legs (board / drop / return pickup)</strong>
                                    <ol class="small mb-2">
                                        <?php foreach ($routeStops as $stop): ?>
                                            <li>
                                                <span class="badge bg-secondary"><?= esc($stopLegLabel($stop['address'] ?? '')) ?></span>
                                                <?= esc($stop['employee_name'] ?? ('Employee #' . $stop['employee_id'])) ?>
                                                (<?= esc($stop['employee_number'] ?? '—') ?>)
                                                — <?= $hm($stop['pickup_time']) ?>
                                                <?= $stop['address'] ? ' · ' . esc($stopLegText($stop['address'])) : '' ?>
                                                <?php if ((float) $stop['leg_distance_km'] > 0): ?>
                                                    <span class="text-muted">(+<?= number_format((float) $stop['leg_distance_km'], 1) ?> km)</span>
                                                <?php endif; ?>
                                            </li>
                                        <?php endforeach; ?>
                                    </ol>
                                    <span class="small text-muted">
                                        Return trip: departs site <?= $hm($route['return_departure_time']) ?>, arrives <?= $hm($route['return_arrival_time']) ?> (shift ends <?= $hm($route['shift_end_time']) ?>).
                                        <?= $route['optimization_notes'] ? ' ' . esc($route['optimization_notes']) : '' ?>
                                    </span>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if ($routes === []): ?>
                        <tr><td colspan="13" class="text-center text-muted py-4">No routes in this plan.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Driver schedule + vehicle assignments -->
<div class="row g-4 mb-4">
    <div class="col-lg-7">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Driver Schedule</h2>
                <p class="enterprise-data-panel__subtitle">Outbound and return trips per driver, per day.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <div class="table-responsive">
                    <table class="enterprise-data-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Driver</th>
                                <th>Route</th>
                                <th>Depart</th>
                                <th>Arrive</th>
                                <th>Return</th>
                                <th>Back at</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($routesByDate as $date => $dateRoutes): ?>
                                <?php foreach ($dateRoutes as $route): ?>
                                    <tr>
                                        <td><?= esc($date) ?></td>
                                        <td><?= esc($route['driver_name'] ?? 'Unassigned') ?></td>
                                        <td class="small"><?= esc($route['route_name']) ?></td>
                                        <td><?= $hm($route['departure_time']) ?></td>
                                        <td><?= $hm($route['arrival_time']) ?></td>
                                        <td><?= $hm($route['return_departure_time']) ?></td>
                                        <td><?= $hm($route['return_arrival_time']) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php if (! empty($fleetSummary['driver_workloads'])): ?>
                    <div class="mt-3">
                        <strong class="small">Workload balance</strong>
                        <ul class="small text-muted mb-0">
                            <?php foreach ($fleetSummary['driver_workloads'] as $workload): ?>
                                <li>
                                    <?= esc($workload['driver_name'] ?? ('Driver #' . $workload['driver_id'])) ?>:
                                    <?= (int) $workload['routes'] ?> route<?= (int) $workload['routes'] === 1 ? '' : 's' ?>,
                                    <?= (int) $workload['minutes'] ?> driving minutes across <?= (int) $workload['days'] ?> day<?= (int) $workload['days'] === 1 ? '' : 's' ?>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-lg-5">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Vehicle Assignments</h2>
                <p class="enterprise-data-panel__subtitle">Utilisation per assigned vehicle.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <div class="table-responsive">
                    <table class="enterprise-data-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Vehicle</th>
                                <th>Route</th>
                                <th class="text-end">Seats Used</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($routesByDate as $date => $dateRoutes): ?>
                                <?php foreach ($dateRoutes as $route): ?>
                                    <tr>
                                        <td><?= esc($date) ?></td>
                                        <td><?= esc($route['vehicle_registration'] ?? 'Unassigned') ?></td>
                                        <td class="small"><?= esc($route['route_name']) ?></td>
                                        <td class="text-end">
                                            <?= (int) $route['employee_count'] ?><?= $route['vehicle_capacity'] ? ' / ' . (int) $route['vehicle_capacity'] : '' ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Pickup + arrival schedules -->
<div class="row g-4 mb-4">
    <div class="col-lg-7">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Transport Legs</h2>
                <p class="enterprise-data-panel__subtitle">Board at base, drop at sites, and return pickups along the route.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <div class="table-responsive" style="max-height:420px;overflow-y:auto;">
                    <table class="enterprise-data-table">
                        <thead>
                            <tr>
                                <th>Leg</th>
                                <th>Time</th>
                                <th>Employee</th>
                                <th>Route</th>
                                <th>Location</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($routes as $route): ?>
                                <?php foreach ($stops[(int) $route['id']] ?? [] as $stop): ?>
                                    <tr>
                                        <td><?= esc($route['service_date']) ?></td>
                                        <td><span class="badge bg-light text-dark"><?= esc($stopLegLabel($stop['address'] ?? '')) ?></span></td>
                                        <td><strong><?= $hm($stop['pickup_time']) ?></strong></td>
                                        <td><?= esc($stop['employee_name'] ?? ('#' . $stop['employee_id'])) ?></td>
                                        <td class="small"><?= esc($route['route_name']) ?></td>
                                        <td class="small text-muted"><?= esc($stopLegText($stop['address'] ?? '')) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-5">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Arrival Schedule</h2>
                <p class="enterprise-data-panel__subtitle">Site arrivals versus shift start times.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <div class="table-responsive" style="max-height:420px;overflow-y:auto;">
                    <table class="enterprise-data-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Destination</th>
                                <th>Arrival</th>
                                <th>Shift Start</th>
                                <th>Margin</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($routes as $route): ?>
                                <?php
                                $toMin = static fn (?string $t): int => $t ? ((int) substr($t, 0, 2)) * 60 + (int) substr($t, 3, 2) : 0;
                                $margin = $toMin($route['shift_start_time']) - $toMin($route['arrival_time']);
                                ?>
                                <tr>
                                    <td><?= esc($route['service_date']) ?></td>
                                    <td class="small"><?= esc($route['destination_name'] ?? '—') ?></td>
                                    <td><?= $hm($route['arrival_time']) ?></td>
                                    <td><?= $hm($route['shift_start_time']) ?></td>
                                    <td>
                                        <?php if ($margin > 0): ?>
                                            <span class="text-success"><?= $margin ?> min early</span>
                                        <?php else: ?>
                                            <span class="text-danger"><?= abs($margin) ?> min late</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Reject modal -->
<div class="modal fade" id="reject-plan-modal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="<?= base_url('transport/ai/plans/' . $plan['id'] . '/reject') ?>" method="post" data-tpin-confirm>
                <?= csrf_field() ?>
                <div class="modal-header">
                    <h6 class="modal-title">Reject Plan <?= esc($plan['number']) ?></h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <label class="enterprise-field-label">Rejection Reason <span class="text-danger">*</span></label>
                    <textarea name="rejection_reason" class="form-control" rows="3" required
                              placeholder="Explain what must change before this plan can be approved"></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Reject Plan</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>
<script>
(function () {
    'use strict';

    var routes = <?= $mapRoutesJson ?: '[]' ?>;
    var el = document.getElementById('ai-plan-map');
    if (!el || typeof L === 'undefined') { return; }

    var map = L.map(el).setView([
        <?= (float) ($mapSettings['default_latitude'] ?? 26.0667) ?>,
        <?= (float) ($mapSettings['default_longitude'] ?? 50.5577) ?>
    ], <?= (int) ($mapSettings['default_zoom'] ?? 12) ?>);

    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '&copy; OpenStreetMap contributors'
    }).addTo(map);

    var palette = ['#2563eb', '#dc2626', '#059669', '#d97706', '#7c3aed', '#0891b2', '#be185d', '#4d7c0f'];
    var bounds = [];

    routes.forEach(function (route, index) {
        var color = palette[index % palette.length];

        if (Array.isArray(route.geometry) && route.geometry.length > 1) {
            // GeoJSON coordinates are [lng, lat]
            var latlngs = route.geometry.map(function (pair) { return [pair[1], pair[0]]; });
            L.polyline(latlngs, { color: color, weight: 4, opacity: 0.75 })
                .bindPopup(route.name + ' (' + route.date + ')')
                .addTo(map);
            latlngs.forEach(function (ll) { bounds.push(ll); });
        }

        (route.stops || []).forEach(function (stop) {
            L.circleMarker([stop.lat, stop.lng], {
                radius: 7, color: color, fillColor: '#ffffff', fillOpacity: 1, weight: 3
            }).bindPopup(route.name + '<br>' + stop.label).addTo(map);
            bounds.push([stop.lat, stop.lng]);
        });

        ['origin', 'destination'].forEach(function (key) {
            if (route[key]) {
                L.marker([route[key].lat, route[key].lng])
                    .bindPopup(route.name + '<br>' + route[key].label)
                    .addTo(map);
                bounds.push([route[key].lat, route[key].lng]);
            }
        });
    });

    if (bounds.length > 0) {
        map.fitBounds(bounds, { padding: [30, 30] });
    }
})();
</script>
<?= $this->endSection() ?>
