<?php $this->start('body'); ?>

<?php $t = $this->data['t']; $docs = $this->data['docs']; ?>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-semibold"><i class="fas fa-truck me-2 text-muted"></i><?= htmlspecialchars($t['reg_no']); ?>
      <?php $badge = ['active'=>'success','maintenance'=>'warning','inactive'=>'secondary','retired'=>'dark'][$t['status']] ?? 'secondary'; ?>
      <span class="badge bg-<?= $badge; ?> ms-2" style="text-transform:capitalize;font-size:.65em;vertical-align:middle;"><?= htmlspecialchars($t['status']); ?></span>
    </h5>
    <div class="text-muted small">
      <?= htmlspecialchars(($t['type_name'] ?? 'Truck') . ' · ' . trim(($t['make'] ?? '') . ' ' . ($t['model'] ?? ''))); ?>
      <?php if (!empty($t['year'])): ?> · <?= (int)$t['year']; ?><?php endif; ?>
    </div>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= PROOT; ?>Trucks" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    <a href="<?= PROOT; ?>Trucks/edit/<?= (int)$t['c0d']; ?>" class="btn btn-sm btn-primary"><i class="fas fa-pen me-1"></i>Edit</a>
  </div>
</div>

<?= flashHtml(); ?>

<?php
  // Currently-active driver assignments on this truck (0..N — allows shift work)
  $active_drivers = (new DriverAssignments())->activeForTruck((int)$t['c0d']);
?>
<div class="card border-0 shadow-sm mb-3">
  <div class="card-body py-2 d-flex align-items-center flex-wrap gap-2">
    <span class="text-uppercase text-muted small me-2"><i class="fas fa-user me-1"></i>Currently driven by</span>
    <?php if (empty($active_drivers)): ?>
      <span class="text-muted small fst-italic">No active driver assigned</span>
    <?php else: ?>
      <?php foreach ($active_drivers as $ad): ?>
        <a href="<?= PROOT; ?>Drivers/view/<?= (int)$ad['driver_id']; ?>"
           class="badge bg-primary text-decoration-none py-2 px-2" style="font-weight:500;">
           <?= htmlspecialchars($ad['driver_name']); ?>
           <?php if ($ad['role_type'] !== 'primary'): ?> · <?= htmlspecialchars($ad['role_type']); ?><?php endif; ?>
           <?php if ($ad['phone_1']): ?> · <span style="opacity:.8;"><?= htmlspecialchars($ad['phone_1']); ?></span><?php endif; ?>
        </a>
      <?php endforeach; ?>
    <?php endif; ?>
    <div class="ms-auto">
      <a href="<?= PROOT; ?>DriverAssignments/add?truck_id=<?= (int)$t['c0d']; ?>" class="btn btn-sm btn-outline-primary">
        <i class="fas fa-plus me-1"></i>Assign driver
      </a>
      <a href="<?= PROOT; ?>DriverAssignments?truck_id=<?= (int)$t['c0d']; ?>" class="btn btn-sm btn-outline-secondary ms-1" title="History">
        <i class="fas fa-history"></i>
      </a>
    </div>
  </div>
</div>

<?php $gps = $this->data['gps'] ?? []; if (!empty($gps)): ?>
<?php $gpsStale = !empty($gps['last_seen_at']) && strtotime($gps['last_seen_at']) < strtotime('-15 minutes'); ?>
<div class="card border-0 shadow-sm mb-3">
  <div class="card-body py-2 d-flex align-items-center flex-wrap gap-2 small">
    <span class="text-uppercase text-muted small me-2"><i class="fas fa-map-marker-alt me-1"></i>Last known position</span>
    <?php if (!empty($gps['ts'])): ?>
      <span class="font-monospace"><?= number_format((float)$gps['lat'], 5); ?>, <?= number_format((float)$gps['lng'], 5); ?></span>
      <span class="text-muted">·</span>
      <?php if ($gps['speed_kph'] !== null): ?><span><?= number_format((float)$gps['speed_kph'], 0); ?> kph</span><span class="text-muted">·</span><?php endif; ?>
      <?php if ($gps['ignition'] !== null): ?><span class="badge bg-<?= $gps['ignition'] ? 'success' : 'secondary'; ?>"><?= $gps['ignition'] ? 'Ignition on' : 'Ignition off'; ?></span><?php endif; ?>
      <span class="text-muted"><i class="fas fa-clock fa-xs me-1"></i><?= humanDateTime($gps['ts']); ?></span>
      <?php if ($gpsStale): ?><span class="badge bg-danger">stale</span><?php endif; ?>
      <a href="https://www.google.com/maps/search/?api=1&query=<?= (float)$gps['lat']; ?>,<?= (float)$gps['lng']; ?>" target="_blank" rel="noopener" class="btn btn-sm btn-outline-primary ms-auto"><i class="fas fa-external-link-alt me-1"></i>Map</a>
      <a href="<?= PROOT; ?>GpsDevices/view/<?= (int)$gps['device_id']; ?>" class="btn btn-sm btn-outline-secondary" title="Device <?= htmlspecialchars($gps['device_code']); ?>"><i class="fas fa-satellite-dish"></i></a>
    <?php else: ?>
      <span class="text-muted fst-italic">Device <span class="font-monospace"><?= htmlspecialchars($gps['device_code']); ?></span> registered — awaiting first fix.</span>
      <a href="<?= PROOT; ?>GpsDevices/view/<?= (int)$gps['device_id']; ?>" class="btn btn-sm btn-outline-secondary ms-auto"><i class="fas fa-satellite-dish"></i></a>
    <?php endif; ?>
  </div>
</div>
<?php endif; ?>

<!-- ══ Preventive Maintenance card ══ -->
<?php $sched = $this->data['pm_schedules'] ?? []; $pmEvents = $this->data['pm_events'] ?? []; $pmTemplates = $this->data['pm_templates'] ?? []; ?>
<div class="card border-0 shadow-sm mb-3">
  <div class="card-body">
    <div class="d-flex align-items-center justify-content-between mb-3">
      <h6 class="text-uppercase text-muted small mb-0"><i class="fas fa-tools me-1"></i>Preventive Maintenance
        <span class="text-muted">· <?= count($sched); ?> schedule(s) · <?= count($pmEvents); ?> event(s)</span>
      </h6>
      <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="collapse" data-bs-target="#pmAssign"><i class="fas fa-plus me-1"></i>Assign templates</button>
    </div>

    <div id="pmAssign" class="collapse mb-3">
      <form method="POST" action="<?= PROOT; ?>TruckPmSchedules/assign/<?= (int)$t['c0d']; ?>" class="border rounded p-3 bg-light">
        <?= csrf_field(); ?>
        <div class="row g-2 mb-2">
          <div class="col-md-4"><label class="form-label small mb-1">Baseline km (last-service odo)</label>
            <input type="number" name="baseline_km" class="form-control form-control-sm" placeholder="<?= number_format((int)$t['current_odometer']); ?>"></div>
          <div class="col-md-4"><label class="form-label small mb-1">Baseline date (last-service date)</label>
            <input type="date" name="baseline_date" class="form-control form-control-sm" value="<?= date('Y-m-d'); ?>"></div>
          <div class="col-md-4"><label class="form-label small mb-1">Notes (optional)</label>
            <input type="text" name="notes" class="form-control form-control-sm"></div>
        </div>
        <label class="form-label small mb-1">Templates to assign · <span class="text-muted">tick multiple</span></label>
        <div class="row g-1">
          <?php $assignedIds = array_column($sched, 'template_id'); foreach ($pmTemplates as $tpl): ?>
            <div class="col-md-6"><div class="form-check">
              <input type="checkbox" name="template_ids[]" value="<?= (int)$tpl['c0d']; ?>" class="form-check-input" id="tpl<?= (int)$tpl['c0d']; ?>" <?= in_array($tpl['c0d'], $assignedIds) ? 'disabled' : ''; ?>>
              <label class="form-check-label small" for="tpl<?= (int)$tpl['c0d']; ?>"><?= htmlspecialchars($tpl['name']); ?>
                <?php if (in_array($tpl['c0d'], $assignedIds)): ?><span class="badge bg-success ms-1" style="font-size:.6rem;">assigned</span><?php endif; ?>
              </label>
            </div></div>
          <?php endforeach; ?>
        </div>
        <div class="text-end mt-2">
          <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#pmAssign">Cancel</button>
          <button class="btn btn-sm btn-primary"><i class="fas fa-plus me-1"></i>Assign</button>
        </div>
      </form>
    </div>

    <?php if (empty($sched)): ?>
      <p class="text-muted small mb-0 fst-italic">No PM templates assigned yet. Click <strong>Assign templates</strong> to subscribe this truck.</p>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
          <thead class="table-light">
            <tr><th>Template</th><th class="money">Next-due km</th><th>Next-due date</th><th class="money">Km remaining</th><th class="money">Days remaining</th><th>Priority</th><th class="text-end"></th></tr>
          </thead>
          <tbody>
            <?php $currentKm = (int)$t['current_odometer']; foreach ($sched as $s):
              $pri = ['low'=>'secondary','normal'=>'info','high'=>'warning','critical'=>'danger'][$s['priority']] ?? 'secondary';
              $kmRem   = $s['next_due_km']   !== null ? (int)$s['next_due_km']   - $currentKm : null;
              $daysRem = $s['next_due_date'] !== null ? (int)round((strtotime($s['next_due_date']) - time()) / 86400) : null;
              $kmClass  = $kmRem   === null ? 'text-muted' : ($kmRem   <= 0 ? 'text-danger fw-bold' : ($kmRem   <= (int)$s['threshold_km']   ? 'text-warning fw-semibold' : 'text-success'));
              $dayClass = $daysRem === null ? 'text-muted' : ($daysRem <= 0 ? 'text-danger fw-bold' : ($daysRem <= (int)$s['threshold_days'] ? 'text-warning fw-semibold' : 'text-success'));
            ?>
              <tr>
                <td class="small fw-semibold"><?= htmlspecialchars($s['template_name']); ?><div class="text-muted small" style="text-transform:capitalize;"><?= htmlspecialchars(str_replace('_', ' ', $s['kind'])); ?></div></td>
                <td class="money small"><?= $s['next_due_km']   !== null ? number_format((int)$s['next_due_km']) : '—'; ?></td>
                <td class="small"><?= $s['next_due_date'] !== null ? humanDate($s['next_due_date']) : '—'; ?></td>
                <td class="money small <?= $kmClass; ?>"><?= $kmRem   === null ? '—' : ($kmRem   >= 0 ? number_format($kmRem)  . ' km' : number_format(abs($kmRem))  . ' km over'); ?></td>
                <td class="money small <?= $dayClass; ?>"><?= $daysRem === null ? '—' : ($daysRem >= 0 ? $daysRem . ' d' : abs($daysRem) . ' d over'); ?></td>
                <td><span class="badge bg-<?= $pri; ?>" style="text-transform:capitalize;font-size:.65em;"><?= htmlspecialchars($s['priority']); ?></span></td>
                <td class="text-end">
                  <form method="POST" action="<?= PROOT; ?>TruckPmSchedules/delete/<?= (int)$s['c0d']; ?>" class="d-inline" onsubmit="return confirm('Remove this schedule?');"><?= csrf_field(); ?><button class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button></form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>

    <?php if (!empty($pmEvents)): ?>
      <hr class="my-3">
      <h6 class="text-uppercase text-muted small mb-2">Recent PM events</h6>
      <div class="d-flex flex-wrap gap-2">
        <?php foreach ($pmEvents as $ev):
          $bg = ['upcoming'=>'info','due'=>'warning','overdue'=>'danger','completed'=>'success','skipped'=>'secondary'][$ev['status']] ?? 'secondary'; ?>
          <a href="<?= PROOT; ?>PmDashboard/view/<?= (int)$ev['c0d']; ?>" class="badge bg-<?= $bg; ?> text-decoration-none py-2 px-2" style="font-weight:500;">
            <?= htmlspecialchars($ev['event_no']); ?> · <?= htmlspecialchars($ev['template_name']); ?>
          </a>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<div class="row g-3">
  <!-- ── Truck details card ─────────────────────────────────── -->
  <div class="col-lg-5">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Details</h6>
        <dl class="row mb-0">
          <dt class="col-5 text-muted fw-normal">Registration</dt><dd class="col-7 fw-semibold"><?= htmlspecialchars($t['reg_no']); ?></dd>
          <dt class="col-5 text-muted fw-normal">Type</dt>        <dd class="col-7"><?= htmlspecialchars($t['type_name'] ?? '—'); ?></dd>
          <dt class="col-5 text-muted fw-normal">Make / Model</dt><dd class="col-7"><?= htmlspecialchars(trim(($t['make'] ?? '') . ' ' . ($t['model'] ?? ''))); ?></dd>
          <dt class="col-5 text-muted fw-normal">Year / Colour</dt><dd class="col-7"><?= (int)$t['year']; ?> · <?= htmlspecialchars($t['colour'] ?? '—'); ?></dd>
          <dt class="col-5 text-muted fw-normal">Chassis no</dt>  <dd class="col-7 font-monospace small"><?= htmlspecialchars($t['chassis_no'] ?? '—'); ?></dd>
          <dt class="col-5 text-muted fw-normal">Engine no</dt>   <dd class="col-7 font-monospace small"><?= htmlspecialchars($t['engine_no']  ?? '—'); ?></dd>
          <dt class="col-5 text-muted fw-normal">Tare</dt>        <dd class="col-7"><?= $t['tare_kg']          ? number_format((int)$t['tare_kg']) . ' kg' : '—'; ?></dd>
          <dt class="col-5 text-muted fw-normal">Capacity</dt>    <dd class="col-7"><?= $t['capacity_kg']      ? number_format((int)$t['capacity_kg']) . ' kg' : '—'; ?></dd>
          <dt class="col-5 text-muted fw-normal">Fuel tank</dt>   <dd class="col-7"><?= $t['fuel_tank_liters'] ? number_format((int)$t['fuel_tank_liters']) . ' L' : '—'; ?></dd>
          <dt class="col-5 text-muted fw-normal">Odometer</dt>    <dd class="col-7"><?= number_format((int)$t['current_odometer']); ?> km</dd>
          <dt class="col-5 text-muted fw-normal">Ownership</dt>   <dd class="col-7"><?= htmlspecialchars(ucfirst($t['ownership'])); ?></dd>
          <dt class="col-5 text-muted fw-normal">Acquired</dt>    <dd class="col-7"><?= $t['acquired_on'] ? humanDate($t['acquired_on']) : '—'; ?></dd>
          <?php if (!empty($t['notes'])): ?>
            <dt class="col-5 text-muted fw-normal">Notes</dt><dd class="col-7"><?= nl2br(htmlspecialchars($t['notes'])); ?></dd>
          <?php endif; ?>
        </dl>
      </div>
    </div>
  </div>

  <!-- ── Documents card ─────────────────────────────────────── -->
  <div class="col-lg-7">
    <div class="card border-0 shadow-sm">
      <div class="card-body">
        <div class="d-flex align-items-center justify-content-between mb-3">
          <h6 class="text-uppercase text-muted small mb-0">Compliance Documents
            <span class="text-muted">· <?= count($docs); ?></span>
          </h6>
          <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="collapse" data-bs-target="#uploadDocPanel">
            <i class="fas fa-upload me-1"></i> Upload
          </button>
        </div>

        <!-- Upload panel (collapsed by default) -->
        <div id="uploadDocPanel" class="collapse mb-3">
          <form method="POST" action="<?= PROOT; ?>Trucks/uploadDoc/<?= (int)$t['c0d']; ?>" enctype="multipart/form-data" class="border rounded p-3 bg-light">
            <?= csrf_field(); ?>
            <div class="row g-2">
              <div class="col-md-4">
                <label class="form-label small mb-1">Document type <span class="text-danger">*</span></label>
                <select name="doc_type_id" class="form-select form-select-sm" required>
                  <option value="">— select —</option>
                  <?php foreach ($this->data['doc_types'] as $dt): ?>
                    <option value="<?= (int)$dt['c0d']; ?>"><?= htmlspecialchars($dt['display_name']); ?><?= $dt['required']?' *':''; ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label small mb-1">Document no</label>
                <input type="text" name="doc_no" class="form-control form-control-sm">
              </div>
              <div class="col-md-4">
                <label class="form-label small mb-1">Issuer</label>
                <input type="text" name="issuer" class="form-control form-control-sm">
              </div>
              <div class="col-md-3">
                <label class="form-label small mb-1">Issued on</label>
                <input type="date" name="issued_on" class="form-control form-control-sm">
              </div>
              <div class="col-md-3">
                <label class="form-label small mb-1">Expires on</label>
                <input type="date" name="expires_on" class="form-control form-control-sm">
              </div>
              <div class="col-md-3">
                <label class="form-label small mb-1">Cost (TZS)</label>
                <input type="text" name="cost_amount" class="form-control form-control-sm js-money">
              </div>
              <div class="col-md-3">
                <label class="form-label small mb-1">File (PDF / image)</label>
                <input type="file" name="doc_file" class="form-control form-control-sm" accept=".pdf,.jpg,.jpeg,.png,.webp">
              </div>
              <div class="col-12 d-flex gap-2 justify-content-end pt-2">
                <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#uploadDocPanel">Cancel</button>
                <button class="btn btn-sm btn-primary"><i class="fas fa-save me-1"></i>Save document</button>
              </div>
            </div>
          </form>
        </div>

        <!-- Existing docs table -->
        <div class="table-responsive">
          <table class="table table-sm align-middle mb-0">
            <thead class="table-light">
              <tr>
                <th>Type</th><th>Doc no</th><th>Issued</th><th>Expires</th><th class="text-end">Cost</th><th class="text-end"></th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($docs as $d): ?>
                <?php
                  $expired = !empty($d['expires_on']) && strtotime($d['expires_on']) < time();
                  $expSoon = !$expired && !empty($d['expires_on']) && strtotime($d['expires_on']) < strtotime('+' . (int)($d['warn_days'] ?? 30) . ' days');
                ?>
                <tr>
                  <td><?= htmlspecialchars($d['doc_type_name']); ?></td>
                  <td class="font-monospace small"><?= htmlspecialchars($d['doc_no'] ?? '—'); ?></td>
                  <td class="small"><?= $d['issued_on']  ? humanDate($d['issued_on'])  : '—'; ?></td>
                  <td class="small">
                    <?php if ($d['expires_on']): ?>
                      <?= humanDate($d['expires_on']); ?>
                      <?php if ($expired): ?><span class="badge bg-danger ms-1">Expired</span>
                      <?php elseif ($expSoon): ?><span class="badge bg-warning text-dark ms-1">Soon</span><?php endif; ?>
                    <?php else: ?>—<?php endif; ?>
                  </td>
                  <td class="money small"><?= $d['cost_amount'] ? htmlspecialchars($d['cost_currency']) . ' ' . number_format((float)$d['cost_amount'], 2, '.', ',') : '—'; ?></td>
                  <td class="text-end">
                    <?php if ($d['file_url']): ?>
                      <button type="button" class="btn btn-sm btn-outline-secondary js-view-file"
                              data-url="<?= htmlspecialchars($d['file_url']); ?>"
                              data-name="<?= htmlspecialchars($d['file_name'] ?: 'document'); ?>"
                              title="Preview"><i class="fas fa-eye"></i></button>
                    <?php endif; ?>
                    <button type="button" class="btn btn-sm btn-outline-danger js-delete-doc"
                            data-id="<?= (int)$d['c0d']; ?>"
                            data-name="<?= htmlspecialchars($d['doc_type_name']); ?>"
                            title="Delete"><i class="fas fa-trash"></i></button>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if (empty($docs)): ?>
                <tr><td colspan="6" class="text-center text-muted py-4">No documents uploaded yet.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Hidden per-doc delete forms -->
<?php foreach ($docs as $d): ?>
<form id="delDoc<?= (int)$d['c0d']; ?>" method="POST" action="<?= PROOT; ?>Trucks/deleteDoc/<?= (int)$d['c0d']; ?>" class="d-none">
  <?= csrf_field(); ?>
</form>
<?php endforeach; ?>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
document.querySelectorAll('.js-money').forEach(el => new Cleave(el, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 2 }));

// ── File preview: iframe modal with Download / Print / Open-in-new-tab ──
document.querySelectorAll('.js-view-file').forEach(function(btn){
  btn.addEventListener('click', function(){
    const url  = btn.getAttribute('data-url');
    const name = btn.getAttribute('data-name');
    $.dialog({
      title: '<i class="fas fa-file me-2"></i>' + name,
      columnClass: 'xlarge',
      backgroundDismiss: true,
      content: '<iframe src="' + url + '" style="width:100%;height:70vh;border:0;"></iframe>',
      buttons: {
        download: {
          text: '<i class="fas fa-download me-1"></i>Download',
          btnClass: 'btn-primary',
          action: function(){ var a=document.createElement('a'); a.href=url; a.download=name; document.body.appendChild(a); a.click(); a.remove(); return false; }
        },
        print: {
          text: '<i class="fas fa-print me-1"></i>Print',
          btnClass: 'btn-outline-secondary',
          action: function(){ var w=window.open(url,'_blank'); w && w.print && w.print(); return false; }
        },
        openTab: {
          text: '<i class="fas fa-external-link-alt me-1"></i>Open in new tab',
          btnClass: 'btn-outline-secondary',
          action: function(){ window.open(url, '_blank'); return false; }
        },
        close: { text: 'Close' }
      }
    });
  });
});

// ── Delete doc confirm ──────────────────────────────────────
document.querySelectorAll('.js-delete-doc').forEach(function(btn){
  btn.addEventListener('click', function(){
    const id   = btn.getAttribute('data-id');
    const name = btn.getAttribute('data-name');
    $.confirm({
      title: 'Remove document?',
      content: 'Delete <strong>' + name + '</strong>? This soft-deletes the record.',
      type: 'red',
      buttons: {
        remove: { text: 'Remove', btnClass: 'btn-danger', action: function(){ document.getElementById('delDoc' + id).submit(); } },
        cancel: function () {}
      }
    });
  });
});
</script>
<?php $this->end(); ?>
