<?php $this->start('body'); ?>
<?php $k = $this->data['kpis']; ?>

<!-- ── Greeting ─────────────────────────────────────────── -->
<div class="mb-3">
  <h5 class="mb-0 fw-semibold">Welcome, <?= htmlspecialchars($this->v('full_name', 'there')); ?></h5>
  <div class="text-muted small"><?= htmlspecialchars($this->v('role_name', '')); ?> · <?= date('l · j F Y'); ?></div>
</div>

<?= flashHtml(); ?>

<!-- ══════════════════════════════════════════════════════
     ROW 1 — Directory KPIs (link out to list pages)
     ══════════════════════════════════════════════════════ -->
<div class="row g-2 g-md-3 mb-3">
  <?php
    $tiles1 = [
      ['url'=>'Trucks',            'ico'=>'fa-truck',        'accent'=>'primary','label'=>'Trucks',      'value'=>$k['trucks_total'],       'sub'=>$k['trucks_active'] . ' active' . ($k['trucks_maintenance'] > 0 ? ' · ' . $k['trucks_maintenance'] . ' in maintenance' : '')],
      ['url'=>'Drivers',           'ico'=>'fa-id-card',      'accent'=>'primary','label'=>'Drivers',     'value'=>$k['drivers_total'],      'sub'=>$k['drivers_available'] . ' available · ' . $k['drivers_on_trip'] . ' on trip'],
      ['url'=>'Customers',         'ico'=>'fa-building',     'accent'=>'primary','label'=>'Customers',   'value'=>$k['customers_active'],   'sub'=>'active'],
      ['url'=>'DriverAssignments?status=active', 'ico'=>'fa-exchange-alt', 'accent'=>'primary','label'=>'Active Assignments','value'=>$k['assignments_active'], 'sub'=>'drivers currently on a truck'],
    ];
    foreach ($tiles1 as $t): ?>
      <div class="col-6 col-md-3">
        <a href="<?= PROOT; ?><?= $t['url']; ?>" class="text-decoration-none">
          <div class="card border-0 shadow-sm h-100 dashboard-tile">
            <div class="card-body p-3 d-flex align-items-center gap-3">
              <div class="tile-icon tile-icon-<?= $t['accent']; ?>"><i class="fas <?= $t['ico']; ?>"></i></div>
              <div class="flex-grow-1 min-w-0">
                <div class="tile-value"><?= number_format((int)$t['value']); ?></div>
                <div class="tile-label"><?= htmlspecialchars($t['label']); ?></div>
                <div class="tile-sub"><?= htmlspecialchars($t['sub']); ?></div>
              </div>
            </div>
          </div>
        </a>
      </div>
  <?php endforeach; ?>
</div>

<!-- ══════════════════════════════════════════════════════
     ROW 2 — Workflow / operational status
     ══════════════════════════════════════════════════════ -->
<div class="row g-2 g-md-3 mb-3">
  <?php
    $tiles2 = [
      ['url'=>'TripRequests?status=pending_review','ico'=>'fa-hourglass-half','accent'=>'warning','label'=>'Requests Pending Review','value'=>$k['requests_pending'],'sub'=>'awaiting Ops approval'],
      ['url'=>'Trips/board',        'ico'=>'fa-inbox',           'accent'=>'info',   'label'=>'Approved / Awaiting Dispatch','value'=>$k['requests_approved'],'sub'=>'ready to dispatch'],
      ['url'=>'Trips?status=in_transit','ico'=>'fa-route',       'accent'=>'primary','label'=>'Trips In Transit',         'value'=>$k['trips_in_transit'],'sub'=>$k['trips_dispatched'] . ' also dispatched'],
      ['url'=>'Trips?status=delivered','ico'=>'fa-check-double', 'accent'=>'success','label'=>'Delivered · Awaiting close','value'=>$k['trips_delivered'],'sub'=>$k['trips_closed_month'] . ' closed in last 30d'],
    ];
    foreach ($tiles2 as $t): ?>
      <div class="col-6 col-md-3">
        <a href="<?= PROOT; ?><?= $t['url']; ?>" class="text-decoration-none">
          <div class="card border-0 shadow-sm h-100 dashboard-tile">
            <div class="card-body p-3 d-flex align-items-center gap-3">
              <div class="tile-icon tile-icon-<?= $t['accent']; ?>"><i class="fas <?= $t['ico']; ?>"></i></div>
              <div class="flex-grow-1 min-w-0">
                <div class="tile-value"><?= number_format((int)$t['value']); ?></div>
                <div class="tile-label"><?= htmlspecialchars($t['label']); ?></div>
                <div class="tile-sub"><?= htmlspecialchars($t['sub']); ?></div>
              </div>
            </div>
          </div>
        </a>
      </div>
  <?php endforeach; ?>
</div>

<!-- ══════════════════════════════════════════════════════
     ROW 3 — Financial Ops (Iter 2 KPIs)
     ══════════════════════════════════════════════════════ -->
<?php
  // Format helper — display "TZS 1.2M" for large numbers, exact for smaller
  $moneyShort = function (float $v): string {
      if ($v >= 1_000_000)  return 'TZS ' . number_format($v / 1_000_000, 1) . 'M';
      if ($v >= 1_000)      return 'TZS ' . number_format($v / 1_000, 0) . 'K';
      return 'TZS ' . number_format($v, 0);
  };
  $expensesAwaiting = (int)$k['expenses_submitted'] + (int)$k['expenses_reviewed'];
  $wosActive        = (int)$k['work_orders_open']  + (int)$k['work_orders_in_progress'];
?>
<div class="row g-2 g-md-3 mb-3">
  <?php
    $tiles3 = [
      ['url'=>'WorkOrders?status=open',              'ico'=>'fa-wrench',       'accent'=>'warning', 'label'=>'Active Work Orders',   'value'=>$wosActive,               'valueIsMoney'=>false, 'sub'=>$k['work_orders_open'] . ' open · ' . $k['work_orders_in_progress'] . ' in-progress'],
      ['url'=>'Trucks?status=maintenance',           'ico'=>'fa-tools',        'accent'=>'warning', 'label'=>'Trucks in Maintenance','value'=>$k['trucks_maintenance_now'],'valueIsMoney'=>false, 'sub'=>'off-road right now'],
      ['url'=>'FuelEntries',                         'ico'=>'fa-gas-pump',     'accent'=>'primary', 'label'=>'Fuel MTD',             'value'=>$k['fuel_spend_month_tzs'],  'valueIsMoney'=>true,  'sub'=>number_format($k['fuel_litres_month'], 0) . ' L this month'],
      ['url'=>'Expenses?status=submitted',           'ico'=>'fa-hourglass-half','accent'=>'info',   'label'=>'Expenses Awaiting Action','value'=>$expensesAwaiting,       'valueIsMoney'=>false, 'sub'=>$k['expenses_submitted'] . ' to review · ' . $k['expenses_reviewed'] . ' to approve · ' . $k['expenses_approved_unpaid'] . ' to pay'],
    ];
    foreach ($tiles3 as $t): ?>
      <div class="col-6 col-md-3">
        <a href="<?= PROOT; ?><?= $t['url']; ?>" class="text-decoration-none">
          <div class="card border-0 shadow-sm h-100 dashboard-tile">
            <div class="card-body p-3 d-flex align-items-center gap-3">
              <div class="tile-icon tile-icon-<?= $t['accent']; ?>"><i class="fas <?= $t['ico']; ?>"></i></div>
              <div class="flex-grow-1 min-w-0">
                <div class="tile-value"><?= $t['valueIsMoney'] ? htmlspecialchars($moneyShort((float)$t['value'])) : number_format((int)$t['value']); ?></div>
                <div class="tile-label"><?= htmlspecialchars($t['label']); ?></div>
                <div class="tile-sub"><?= htmlspecialchars($t['sub']); ?></div>
              </div>
            </div>
          </div>
        </a>
      </div>
  <?php endforeach; ?>
</div>

<!-- ══════════════════════════════════════════════════════
     ROW 4 — Compliance alerts + Revenue snapshot
     ══════════════════════════════════════════════════════ -->
<?php
  $anyExpiredTruck  = $k['truck_docs_expired'] > 0;
  $anyExpiringTruck = $k['truck_docs_expiring'] > 0;
  $anyExpiredLic    = $k['driver_licences_expired'] > 0;
  $anyExpiringLic   = $k['driver_licences_expiring'] > 0;
  $hasComplianceHeat = $anyExpiredTruck || $anyExpiringTruck || $anyExpiredLic || $anyExpiringLic;
?>
<div class="row g-2 g-md-3 mb-3">
  <div class="col-md-4">
    <div class="card border-0 shadow-sm h-100 dashboard-tile">
      <div class="card-body p-3 d-flex align-items-center gap-3">
        <div class="tile-icon tile-icon-success"><i class="fas fa-money-bill-wave"></i></div>
        <div class="flex-grow-1 min-w-0">
          <div class="tile-value">TZS <?= number_format($k['revenue_month_tzs'], 0, '.', ','); ?></div>
          <div class="tile-label">Revenue this month</div>
          <div class="tile-sub">Sum of invoiced amounts on closed trips (MTD)</div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-8">
    <div class="card border-0 shadow-sm h-100 dashboard-tile">
      <div class="card-body p-3">
        <div class="d-flex justify-content-between align-items-start mb-2">
          <div class="fw-semibold text-uppercase small text-muted"><i class="fas fa-exclamation-triangle me-1"></i>Compliance Alerts</div>
          <span class="small text-muted"><?= (int)$k['truck_docs_expired'] + (int)$k['truck_docs_expiring'] + (int)$k['driver_licences_expired'] + (int)$k['driver_licences_expiring']; ?> total</span>
        </div>
        <div class="row g-2">
          <div class="col-6 col-md-3">
            <div class="compliance-mini <?= $anyExpiredTruck ? 'danger' : 'muted'; ?>">
              <div class="fw-semibold"><?= (int)$k['truck_docs_expired']; ?></div>
              <div class="small">Truck docs expired</div>
            </div>
          </div>
          <div class="col-6 col-md-3">
            <div class="compliance-mini <?= $anyExpiringTruck ? 'warning' : 'muted'; ?>">
              <div class="fw-semibold"><?= (int)$k['truck_docs_expiring']; ?></div>
              <div class="small">Truck docs · 30d</div>
            </div>
          </div>
          <div class="col-6 col-md-3">
            <div class="compliance-mini <?= $anyExpiredLic ? 'danger' : 'muted'; ?>">
              <div class="fw-semibold"><?= (int)$k['driver_licences_expired']; ?></div>
              <div class="small">Licences expired</div>
            </div>
          </div>
          <div class="col-6 col-md-3">
            <div class="compliance-mini <?= $anyExpiringLic ? 'warning' : 'muted'; ?>">
              <div class="fw-semibold"><?= (int)$k['driver_licences_expiring']; ?></div>
              <div class="small">Licences · 30d</div>
            </div>
          </div>
        </div>
        <?php if (!empty($this->data['compliance'])): ?>
          <hr class="my-2">
          <ul class="list-unstyled mb-0 small">
            <?php foreach ($this->data['compliance'] as $a): ?>
              <?php
                $days = (int)$a['days_left'];
                $urgency = $days < 0 ? 'text-danger fw-semibold' : ($days <= 7 ? 'text-danger' : ($days <= 30 ? 'text-warning' : 'text-muted'));
                $whenTxt = $days < 0 ? abs($days) . 'd overdue' : ($days === 0 ? 'today' : "in {$days}d");
                $link = $a['kind'] === 'truck_doc'
                  ? PROOT . 'Trucks/view/' . (int)$a['entity_id']
                  : PROOT . 'Drivers/view/' . (int)$a['entity_id'];
              ?>
              <li class="d-flex justify-content-between py-1 border-bottom">
                <span>
                  <i class="fas fa-<?= $a['kind']==='truck_doc' ? 'truck' : 'id-card'; ?> fa-xs text-muted me-1"></i>
                  <a href="<?= $link; ?>" class="text-decoration-none"><?= htmlspecialchars($a['entity_label']); ?></a>
                  <span class="text-muted">· <?= htmlspecialchars($a['doc_type']); ?></span>
                </span>
                <span class="<?= $urgency; ?>"><?= $whenTxt; ?></span>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php elseif (!$hasComplianceHeat): ?>
          <hr class="my-2">
          <p class="text-muted small mb-0 fst-italic"><i class="fas fa-check-circle text-success me-1"></i>No expiring documents in the next 30 days — you're compliant.</p>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- ══════════════════════════════════════════════════════
     ROW 4 — Recent trips + Pending requests
     ══════════════════════════════════════════════════════ -->
<div class="row g-2 g-md-3">
  <div class="col-lg-6">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-body p-3">
        <div class="d-flex align-items-center justify-content-between mb-2">
          <div class="fw-semibold text-uppercase small text-muted"><i class="fas fa-truck-loading me-1"></i>Recent Trips</div>
          <a href="<?= PROOT; ?>Trips" class="small text-decoration-none">All trips →</a>
        </div>
        <?php if (empty($this->data['recent_trips'])): ?>
          <p class="text-muted small mb-0 fst-italic">No trips yet — <a href="<?= PROOT; ?>Trips/board">open the dispatch board</a>.</p>
        <?php else: ?>
          <div class="table-responsive">
            <table class="table table-sm mb-0 align-middle">
              <tbody>
                <?php foreach ($this->data['recent_trips'] as $t): ?>
                  <?php $bg = ['dispatched'=>'primary','in_transit'=>'info','delivered'=>'warning','closed'=>'success','cancelled'=>'dark'][$t['status']] ?? 'secondary'; ?>
                  <tr>
                    <td class="small" style="width:100px;"><a href="<?= PROOT; ?>Trips/view/<?= (int)$t['c0d']; ?>" class="font-monospace text-decoration-none fw-semibold"><?= htmlspecialchars($t['trip_no']); ?></a></td>
                    <td class="small">
                      <?= htmlspecialchars($t['driver_name'] ?? '?'); ?>
                      <span class="text-muted">· <?= htmlspecialchars($t['truck_reg'] ?? '?'); ?></span>
                      <div class="text-muted text-truncate" style="max-width:260px;"><?= htmlspecialchars(($t['customer_name'] ?? 'Internal') . ' · ' . ($t['cargo_description'] ?? '')); ?></div>
                    </td>
                    <td class="text-end" style="width:100px;"><span class="badge bg-<?= $bg; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(str_replace('_',' ',$t['status'])); ?></span></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <div class="col-lg-6">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-body p-3">
        <div class="d-flex align-items-center justify-content-between mb-2">
          <div class="fw-semibold text-uppercase small text-muted"><i class="fas fa-clipboard-list me-1"></i>Requests Needing Attention</div>
          <a href="<?= PROOT; ?>TripRequests" class="small text-decoration-none">All requests →</a>
        </div>
        <?php if (empty($this->data['pending_reqs'])): ?>
          <p class="text-muted small mb-0 fst-italic">Nothing pending review or dispatch — <a href="<?= PROOT; ?>TripRequests/add">create a request</a>.</p>
        <?php else: ?>
          <div class="table-responsive">
            <table class="table table-sm mb-0 align-middle">
              <tbody>
                <?php foreach ($this->data['pending_reqs'] as $r): ?>
                  <?php $bg = ['pending_review'=>'warning','approved'=>'success'][$r['status']] ?? 'secondary'; ?>
                  <tr>
                    <td class="small" style="width:100px;"><a href="<?= PROOT; ?>TripRequests/view/<?= (int)$r['c0d']; ?>" class="font-monospace text-decoration-none fw-semibold"><?= htmlspecialchars($r['request_no']); ?></a></td>
                    <td class="small">
                      <?= htmlspecialchars($r['customer_name'] ?: 'Internal'); ?>
                      <?php if ($r['priority'] !== 'normal'): ?><span class="badge bg-<?= $r['priority']==='urgent'?'danger':'warning'; ?> ms-1" style="text-transform:capitalize;font-size:.6rem;"><?= htmlspecialchars($r['priority']); ?></span><?php endif; ?>
                      <div class="text-muted text-truncate" style="max-width:260px;"><?= htmlspecialchars($r['cargo_description'] ?? ''); ?><?php if ($r['pickup_date']): ?> · pickup <?= humanDate($r['pickup_date']); ?><?php endif; ?></div>
                    </td>
                    <td class="text-end" style="width:100px;"><span class="badge bg-<?= $bg; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(str_replace('_',' ',$r['status'])); ?></span></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- Dashboard tile styling -->
<style>
.dashboard-tile { transition: box-shadow .12s ease, transform .12s ease; }
a.text-decoration-none .dashboard-tile:hover { box-shadow: 0 4px 14px rgba(38,38,245,.12); transform: translateY(-1px); }

.tile-icon { width:44px; height:44px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:1.1rem; flex-shrink:0; }
.tile-icon-primary { background: var(--pacific-tint); color: var(--pacific-navy); }
.tile-icon-success { background: rgba(34,197,94,.12); color: #16a34a; }
.tile-icon-warning { background: rgba(245,158,11,.14); color: #d97706; }
.tile-icon-danger  { background: rgba(239,68,68,.12); color: #dc2626; }
.tile-icon-info    { background: rgba(59,130,246,.12); color: #2563eb; }

.tile-value { font-size:1.55rem; font-weight:700; color:var(--pacific-text); line-height:1.1; }
.tile-label { font-size:.7rem; font-weight:600; color:var(--pacific-navy); text-transform:uppercase; letter-spacing:.04em; margin-top:2px; }
.tile-sub   { font-size:.7rem; color:var(--pacific-muted); margin-top:1px; }

.compliance-mini { padding:8px 10px; border-radius:6px; text-align:center; background:#f6f7fa; color:#4b5563; }
.compliance-mini.danger  { background:rgba(239,68,68,.10);  color:#b91c1c; }
.compliance-mini.warning { background:rgba(245,158,11,.14); color:#a16207; }
.compliance-mini.muted   { background:#f6f7fa; color:#6b7280; }
.compliance-mini .fw-semibold { font-size:1.25rem; line-height:1; }

@media (max-width: 767.98px) {
  .tile-value { font-size: 1.3rem; }
  .tile-icon  { width:36px; height:36px; font-size:.95rem; }
}
</style>

<?php $this->end(); ?>
