<?php $this->start('body'); ?>
<?php $e = $this->data['e'];
$bg  = ['upcoming'=>'info','due'=>'warning','overdue'=>'danger','completed'=>'success','skipped'=>'secondary'][$e['status']] ?? 'secondary';
$sev = ['low'=>'secondary','normal'=>'info','medium'=>'warning','high'=>'danger','critical'=>'danger'][$e['severity']] ?? 'secondary';
$kmOver = ($e['planned_km'] && $e['current_odometer'] > $e['planned_km']) ? ((int)$e['current_odometer'] - (int)$e['planned_km']) : 0;
$daysOver = ($e['planned_date'] && strtotime($e['planned_date']) < time()) ? (int)round((time() - strtotime($e['planned_date']))/86400) : 0;
$isOpen = in_array($e['status'], ['upcoming','due','overdue'], true);
?>

<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-tools me-2 text-muted"></i><span class="font-monospace"><?= htmlspecialchars($e['event_no']); ?></span>
      <span class="badge bg-<?= $bg; ?> ms-2" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars($e['status']); ?></span>
      <span class="badge bg-<?= $sev; ?> ms-1" style="font-size:.65em;vertical-align:middle;"><?= htmlspecialchars($e['severity']); ?></span>
    </h5>
    <div class="text-muted small">
      <a href="<?= PROOT; ?>Trucks/view/<?= (int)$e['truck_id']; ?>" class="fw-semibold"><?= htmlspecialchars($e['reg_no']); ?></a>
      · <?= htmlspecialchars($e['template_name']); ?>
      · triggered <?= humanDateTime($e['triggered_at']); ?>
      <?php if ($e['triggered_by'] === 'cron'): ?><span class="badge bg-light text-muted border ms-1"><i class="fas fa-robot fa-xs"></i> cron</span><?php endif; ?>
    </div>
  </div>
  <a href="<?= PROOT; ?>PmDashboard" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
</div>

<?= flashHtml(); ?>

<?php if ($e['status'] === 'skipped' && $e['skip_reason']): ?>
  <div class="alert alert-secondary py-2 small"><strong>Skipped:</strong> <?= htmlspecialchars($e['skip_reason']); ?><?php if ($e['skipped_by_name']): ?> · by <?= htmlspecialchars($e['skipped_by_name']); ?><?php endif; ?></div>
<?php endif; ?>

<?php if ($isOpen): ?>
  <div class="card border-0 shadow-sm mb-3">
    <div class="card-body py-2 d-flex flex-wrap gap-2 align-items-center">
      <span class="text-uppercase text-muted small me-2"><i class="fas fa-play-circle me-1"></i>Actions</span>
      <button type="button" class="btn btn-sm btn-success" onclick="doComplete()"><i class="fas fa-check me-1"></i>Mark completed</button>
      <button type="button" class="btn btn-sm btn-outline-secondary" onclick="doSkip()"><i class="fas fa-forward me-1"></i>Skip</button>
      <?php if ($e['alert_id']): ?>
        <a href="<?= PROOT; ?>Alerts/view/<?= (int)$e['alert_id']; ?>" class="btn btn-sm btn-outline-primary ms-auto"><i class="fas fa-bell me-1"></i>Linked alert</a>
      <?php endif; ?>
    </div>
  </div>
<?php endif; ?>

<div class="row g-3">
  <div class="col-lg-7">
    <div class="card border-0 shadow-sm">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Plan vs current</h6>
        <div class="row g-3">
          <div class="col-md-6">
            <div class="text-muted small">Planned km</div>
            <div class="fs-4 fw-bold"><?= $e['planned_km'] ? number_format((int)$e['planned_km']) : '—'; ?><span class="fs-6 text-muted"> km</span></div>
            <div class="text-muted small">Current km · <?= number_format((int)$e['current_odometer']); ?></div>
            <?php if ($kmOver > 0): ?><div class="badge bg-danger mt-1"><?= number_format($kmOver); ?> km OVER</div><?php endif; ?>
          </div>
          <div class="col-md-6">
            <div class="text-muted small">Planned date</div>
            <div class="fs-4 fw-bold"><?= $e['planned_date'] ? humanDate($e['planned_date']) : '—'; ?></div>
            <?php if ($daysOver > 0): ?><div class="badge bg-danger mt-1"><?= $daysOver; ?> days OVER</div><?php endif; ?>
          </div>
        </div>

        <hr class="my-3">
        <h6 class="text-uppercase text-muted small mb-3">Template</h6>
        <dl class="row mb-0 small">
          <dt class="col-4 text-muted fw-normal">Kind</dt><dd class="col-8" style="text-transform:capitalize;"><?= htmlspecialchars(str_replace('_', ' ', $e['kind'])); ?></dd>
          <dt class="col-4 text-muted fw-normal">Priority</dt><dd class="col-8" style="text-transform:capitalize;"><?= htmlspecialchars($e['priority']); ?></dd>
          <dt class="col-4 text-muted fw-normal">Interval</dt><dd class="col-8">
            <?= $e['interval_km']   ? number_format((int)$e['interval_km']) . ' km' : ''; ?>
            <?= $e['interval_km'] && $e['interval_days'] ? ' or ' : ''; ?>
            <?= $e['interval_days'] ? (int)$e['interval_days'] . ' days' : ''; ?>
          </dd>
          <?php if ($e['default_labour_hours']): ?><dt class="col-4 text-muted fw-normal">Est. labour</dt><dd class="col-8"><?= number_format((float)$e['default_labour_hours'], 1); ?> hrs</dd><?php endif; ?>
          <?php if ($e['default_parts_cost']):   ?><dt class="col-4 text-muted fw-normal">Est. parts</dt><dd class="col-8">TZS <?= number_format((float)$e['default_parts_cost'], 0); ?></dd><?php endif; ?>
        </dl>
      </div>
    </div>
  </div>

  <div class="col-lg-5">
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Timeline</h6>
        <ul class="list-unstyled small mb-0">
          <li class="mb-2 ps-3" style="border-left: 2px solid var(--pacific-navy, #2626F5);">
            <div class="fw-semibold">Triggered</div>
            <div class="text-muted"><?= humanDateTime($e['triggered_at']); ?> · <?= htmlspecialchars($e['triggered_by']); ?></div>
          </li>
          <?php if ($e['due_since']): ?>
            <li class="mb-2 ps-3" style="border-left: 2px solid #F59E0B;">
              <div class="fw-semibold">Marked due</div>
              <div class="text-muted"><?= humanDateTime($e['due_since']); ?></div>
            </li>
          <?php endif; ?>
          <?php if ($e['overdue_since']): ?>
            <li class="mb-2 ps-3" style="border-left: 2px solid #DC2626;">
              <div class="fw-semibold text-danger">Escalated to overdue</div>
              <div class="text-muted"><?= humanDateTime($e['overdue_since']); ?></div>
            </li>
          <?php endif; ?>
          <?php if ($e['completed_at']): ?>
            <li class="mb-2 ps-3" style="border-left: 2px solid #16A34A;">
              <div class="fw-semibold text-success">Completed</div>
              <div class="text-muted"><?= humanDateTime($e['completed_at']); ?><?php if ($e['completed_by_name']): ?> · <?= htmlspecialchars($e['completed_by_name']); ?><?php endif; ?></div>
              <?php if ($e['completed_km']): ?><div class="small">At <?= number_format((int)$e['completed_km']); ?> km</div><?php endif; ?>
              <?php if ($e['work_order_id']): ?><div class="small"><a href="<?= PROOT; ?>WorkOrders/view/<?= (int)$e['work_order_id']; ?>">WO #<?= (int)$e['work_order_id']; ?></a></div><?php endif; ?>
            </li>
          <?php endif; ?>
        </ul>
      </div>
    </div>

    <?php if ($e['notes']): ?>
      <div class="card border-0 shadow-sm">
        <div class="card-body">
          <h6 class="text-uppercase text-muted small mb-2">Notes</h6>
          <div class="small"><?= nl2br(htmlspecialchars($e['notes'])); ?></div>
        </div>
      </div>
    <?php endif; ?>
  </div>
</div>

<form id="doneForm" method="POST" action="<?= PROOT; ?>PmDashboard/complete/<?= (int)$e['c0d']; ?>" class="d-none">
  <?= csrf_field(); ?>
  <input type="hidden" name="completed_km"   id="fKm">
  <input type="hidden" name="completed_date" id="fDate">
  <input type="hidden" name="work_order_id"  id="fWo">
  <input type="hidden" name="notes"          id="fNotes">
</form>
<form id="skipForm" method="POST" action="<?= PROOT; ?>PmDashboard/skip/<?= (int)$e['c0d']; ?>" class="d-none"><?= csrf_field(); ?><input type="hidden" name="reason" id="fSkipR"></form>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
function doComplete() {
    const currentKm = <?= (int)$e['current_odometer']; ?>;
    $.confirm({
        title: 'Mark PM completed?',
        content: `
            <div class="mb-2 small text-muted">Records the service and rolls the schedule forward to the next cycle.</div>
            <label class="form-label small mb-1">Completed at odometer (km) <span class="text-danger">*</span></label>
            <input type="number" id="cmpKm" class="form-control form-control-sm mb-2" value="${currentKm}">
            <label class="form-label small mb-1">Completion date</label>
            <input type="date" id="cmpDate" class="form-control form-control-sm mb-2" value="<?= date('Y-m-d'); ?>">
            <label class="form-label small mb-1">Link to Work Order # (optional)</label>
            <input type="number" id="cmpWo" class="form-control form-control-sm mb-2">
            <label class="form-label small mb-1">Notes</label>
            <textarea id="cmpNotes" class="form-control form-control-sm" rows="2" placeholder="Parts used, mechanic, next-check ideas..."></textarea>
        `,
        type: 'green',
        buttons: {
            go: { text: 'Complete', btnClass: 'btn-success', action: function() {
                document.getElementById('fKm').value    = document.getElementById('cmpKm').value;
                document.getElementById('fDate').value  = document.getElementById('cmpDate').value;
                document.getElementById('fWo').value    = document.getElementById('cmpWo').value;
                document.getElementById('fNotes').value = document.getElementById('cmpNotes').value;
                document.getElementById('doneForm').submit();
            }},
            back: function(){}
        }
    });
}
function doSkip() {
    $.confirm({
        title: 'Skip this PM?',
        content: '<div class="mb-2 small text-muted">The schedule rolls forward from today so we do not stack a fresh overdue immediately.</div><label class="form-label small">Reason <span class="text-danger">*</span></label><textarea id="skR" class="form-control form-control-sm" rows="3"></textarea>',
        type: 'red',
        buttons: { go: { text: 'Skip', btnClass: 'btn-outline-secondary', action: function() {
            const r = document.getElementById('skR').value.trim();
            if (!r) { $.alert('Reason required.'); return false; }
            document.getElementById('fSkipR').value = r;
            document.getElementById('skipForm').submit();
        }}, back: function(){} } });
}
</script>
<?php $this->end(); ?>
