<?= $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',
        'active'      => 'active',
        'maintenance' => 'on_leave',
        'retired'     => 'terminated',
        'inactive'    => 'inactive',
        'suspended'   => 'terminated',
    ];
    $class = $map[$status] ?? 'inactive';

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

$vehicleCounts  = $report['vehicleCounts'] ?? [];
$driverCounts   = $report['driverCounts'] ?? [];
$scheduleCounts = $report['scheduleCounts'] ?? [];

$kpis = [
    [
        'label'     => 'Active vehicles',
        'value'     => (string) ($vehicleCounts['active'] ?? 0),
        'icon'      => 'fa-truck',
        'badge'     => (string) (($vehicleCounts['maintenance'] ?? 0) . ' in maintenance'),
        'badgeType' => ($vehicleCounts['maintenance'] ?? 0) > 0 ? 'negative' : 'neutral',
        'dept'      => 'Fleet',
    ],
    [
        'label'     => 'Active drivers',
        'value'     => (string) ($driverCounts['active'] ?? 0),
        'icon'      => 'fa-id-card',
        'badge'     => 'Licensed',
        'badgeType' => 'positive',
        'dept'      => 'Drivers',
    ],
    [
        'label'     => 'Trips completed',
        'value'     => (string) ($report['completedInPeriod'] ?? 0),
        'icon'      => 'fa-flag-checkered',
        'badge'     => 'Period',
        'badgeType' => 'positive',
        'dept'      => 'Scheduling',
    ],
    [
        'label'     => 'Active locations',
        'value'     => (string) ($report['locationCount'] ?? 0),
        'icon'      => 'fa-map-location-dot',
        'badge'     => 'Sites',
        'badgeType' => 'neutral',
        'dept'      => 'Locations',
    ],
];

$scheduleChartLabels = [];
$scheduleChartValues = [];
foreach (['planned', 'scheduled', 'in_progress', 'completed', 'cancelled'] as $s) {
    $scheduleChartLabels[] = ucwords(str_replace('_', ' ', $s));
    $scheduleChartValues[] = (int) ($scheduleCounts[$s] ?? 0);
}

$vehicleChartLabels = ['Active', 'Maintenance', 'Retired'];
$vehicleChartValues = [
    (int) ($vehicleCounts['active'] ?? 0),
    (int) ($vehicleCounts['maintenance'] ?? 0),
    (int) ($vehicleCounts['retired'] ?? 0),
];
?>

<?= view('partials/workspace_hero', [
    'workspaceCrumbPill'    => 'Transport',
    'workspaceCrumbCurrent' => 'Reports',
    'workspaceTitle'        => 'Transport Reports',
    'workspaceDesc'         => 'Fleet KPIs, trip activity, expiring licenses, and maintenance vehicles.',
]) ?>

<section class="enterprise-kpi-grid mb-4">
    <?php foreach ($kpis as $kpi): ?>
        <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"><?= esc($kpi['value']) ?></div>
            <div class="enterprise-kpi-footer">
                <span class="enterprise-kpi-badge enterprise-kpi-badge--<?= esc($kpi['badgeType']) ?>">
                    <?= esc($kpi['badge']) ?>
                </span>
                <span class="enterprise-kpi-dept"><?= esc($kpi['dept']) ?></span>
            </div>
        </article>
    <?php endforeach; ?>
</section>

<div class="enterprise-data-panel mb-4">
    <div class="enterprise-data-panel__head">
        <h2 class="enterprise-data-panel__title">Filters</h2>
        <p class="enterprise-data-panel__subtitle">Date range and trip status for the report period.</p>
    </div>
    <div class="enterprise-data-panel__toolbar">
        <form action="<?= base_url('transport/reports') ?>" method="get">
            <div class="enterprise-filter-grid">
                <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'] ?? '') ?>">
                </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'] ?? '') ?>">
                </div>
                <div>
                    <label class="enterprise-field-label">Trip 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">Apply Filters</button>
                </div>
            </div>
        </form>
    </div>
</div>

<section class="enterprise-charts-grid mb-4">
    <article class="enterprise-chart-card">
        <div class="enterprise-chart-header">
            <h3 class="enterprise-chart-title">TRIP STATUS MIX</h3>
        </div>
        <div class="enterprise-chart-body">
            <canvas id="transportScheduleStatusChart" height="220"></canvas>
        </div>
    </article>
    <article class="enterprise-chart-card">
        <div class="enterprise-chart-header">
            <h3 class="enterprise-chart-title">VEHICLE STATUS</h3>
        </div>
        <div class="enterprise-chart-body">
            <canvas id="transportVehicleStatusChart" height="220"></canvas>
        </div>
    </article>
</section>

<div class="enterprise-data-panel mb-4">
    <div class="enterprise-data-panel__head">
        <h2 class="enterprise-data-panel__title">Trips in Period</h2>
        <p class="enterprise-data-panel__subtitle">
            <?= esc($filters['date_from'] ?? '') ?> — <?= esc($filters['date_to'] ?? '') ?>
        </p>
    </div>
    <div class="enterprise-data-panel__body">
        <div class="table-responsive">
            <table class="enterprise-data-table">
                <thead>
                    <tr>
                        <th>Number</th>
                        <th>Title</th>
                        <th>Date</th>
                        <th>Route</th>
                        <th>Vehicle</th>
                        <th>Driver</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($report['trips'] ?? [] as $trip): ?>
                        <tr>
                            <td>
                                <a href="<?= base_url('transport/scheduling/' . $trip['id']) ?>">
                                    <code><?= esc($trip['number']) ?></code>
                                </a>
                            </td>
                            <td><?= esc($trip['title']) ?></td>
                            <td><?= esc($trip['schedule_date']) ?></td>
                            <td><?= esc($trip['route_name'] ?? '—') ?></td>
                            <td><?= esc($trip['vehicle_registration'] ?? '—') ?></td>
                            <td><?= esc($trip['driver_name'] ?? '—') ?></td>
                            <td><?= $statusPill($trip['status']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (count($report['trips'] ?? []) === 0): ?>
                        <tr><td colspan="7" class="text-center text-muted py-5">No trips in the selected period.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-lg-6">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Expiring Licenses</h2>
                <p class="enterprise-data-panel__subtitle">Active drivers with licenses expiring within 30 days.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <div class="table-responsive">
                    <table class="enterprise-data-table">
                        <thead>
                            <tr>
                                <th>Driver</th>
                                <th>License</th>
                                <th>Expiry</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($report['expiringLicenses'] ?? [] as $row): ?>
                                <tr>
                                    <td>
                                        <a href="<?= base_url('transport/drivers/' . $row['id']) ?>" class="enterprise-data-table__primary">
                                            <?= esc($row['employee_name'] ?? $row['number']) ?>
                                        </a>
                                    </td>
                                    <td><?= esc($row['license_number']) ?></td>
                                    <td><?= esc($row['license_expiry']) ?></td>
                                    <td><?= $statusPill($row['status']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (count($report['expiringLicenses'] ?? []) === 0): ?>
                                <tr><td colspan="4" class="text-center text-muted py-4">No expiring licenses.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-6">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Maintenance Vehicles</h2>
                <p class="enterprise-data-panel__subtitle">Vehicles currently flagged for maintenance.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <div class="table-responsive">
                    <table class="enterprise-data-table">
                        <thead>
                            <tr>
                                <th>Registration</th>
                                <th>Make / Model</th>
                                <th>Last Service</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($report['maintenanceVehicles'] ?? [] as $row): ?>
                                <tr>
                                    <td>
                                        <a href="<?= base_url('transport/vehicles/' . $row['id']) ?>" class="enterprise-data-table__primary">
                                            <?= esc($row['registration_number']) ?>
                                        </a>
                                    </td>
                                    <td><?= esc(trim(($row['make'] ?? '') . ' ' . ($row['model'] ?? '')) ?: '—') ?></td>
                                    <td><?= esc($row['last_service_date'] ?: '—') ?></td>
                                    <td><?= $statusPill($row['status']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (count($report['maintenanceVehicles'] ?? []) === 0): ?>
                                <tr><td colspan="4" class="text-center text-muted py-4">No vehicles in maintenance.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
(function () {
    'use strict';

    if (typeof Chart === 'undefined') {
        return;
    }

    Chart.defaults.color = '#6b7280';
    Chart.defaults.borderColor = '#e5e7eb';
    Chart.defaults.font.family = 'Inter, sans-serif';
    Chart.defaults.font.size = 11;

    var scheduleCtx = document.getElementById('transportScheduleStatusChart');
    if (scheduleCtx) {
        new Chart(scheduleCtx, {
            type: 'bar',
            data: {
                labels: <?= json_encode($scheduleChartLabels) ?>,
                datasets: [{
                    data: <?= json_encode($scheduleChartValues) ?>,
                    backgroundColor: '#374151',
                    borderRadius: 4,
                    barPercentage: 0.55,
                }],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { grid: { display: false }, border: { display: false } },
                    y: { beginAtZero: true, ticks: { precision: 0 } },
                },
            },
        });
    }

    var vehicleCtx = document.getElementById('transportVehicleStatusChart');
    if (vehicleCtx) {
        new Chart(vehicleCtx, {
            type: 'doughnut',
            data: {
                labels: <?= json_encode($vehicleChartLabels) ?>,
                datasets: [{
                    data: <?= json_encode($vehicleChartValues) ?>,
                    backgroundColor: ['#374151', '#9ca3af', '#d1d5db'],
                    borderWidth: 0,
                }],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { boxWidth: 10, padding: 12 },
                    },
                },
            },
        });
    }
})();
</script>
<?= $this->endSection() ?>
