<?php $this->start('body'); ?>
<?php $d = $this->data['d']; $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-id-card me-2 text-muted"></i><?= htmlspecialchars($d['full_name']); ?>
      <?php $bg = ['available'=>'success','on_trip'=>'primary','on_leave'=>'info','suspended'=>'warning','terminated'=>'dark'][$d['status']] ?? 'secondary'; ?>
      <span class="badge bg-<?= $bg; ?> ms-2" style="text-transform:capitalize;font-size:.65em;vertical-align:middle;"><?= htmlspecialchars(str_replace('_',' ',$d['status'])); ?></span>
    </h5>
    <div class="text-muted small">
      <?= htmlspecialchars($d['employee_no'] ?? 'No employee number'); ?>
      <?php if ($d['licence_no']): ?> · Licence <?= htmlspecialchars($d['licence_no']); ?> (<?= htmlspecialchars($d['licence_class'] ?? '—'); ?>)<?php endif; ?>
    </div>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= PROOT; ?>Drivers" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    <div class="btn-group btn-group-sm">
      <a href="<?= PROOT; ?>Drivers/staffId/<?= (int)$d['c0d']; ?>" target="_blank" class="btn btn-outline-primary" title="View card in browser">
        <i class="fas fa-id-badge me-1"></i>Staff ID
      </a>
      <a href="<?= PROOT; ?>Drivers/staffId/<?= (int)$d['c0d']; ?>?dl=1" class="btn btn-outline-primary" title="Download PDF">
        <i class="fas fa-download"></i>
      </a>
    </div>
    <div class="btn-group btn-group-sm">
      <a href="<?= PROOT; ?>Payroll/p9/<?= (int)$d['c0d']; ?>?year=<?= date('Y'); ?>" target="_blank" class="btn btn-outline-primary" title="P9 for this year">
        <i class="fas fa-file-invoice me-1"></i>P9 <?= date('Y'); ?>
      </a>
      <button type="button" class="btn btn-outline-primary" onclick="doPickP9Year(<?= (int)$d['c0d']; ?>)" title="Pick a different year"><i class="fas fa-caret-down"></i></button>
    </div>
    <a href="<?= PROOT; ?>Drivers/edit/<?= (int)$d['c0d']; ?>" class="btn btn-sm btn-primary"><i class="fas fa-pen me-1"></i>Edit</a>
  </div>
</div>

<?= flashHtml(); ?>

<?php $current = (new DriverAssignments())->currentForDriver((int)$d['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-truck me-1"></i>Currently assigned truck</span>
    <?php if (empty($current)): ?>
      <span class="text-muted small fst-italic">No active truck — this driver is unassigned</span>
    <?php else: ?>
      <a href="<?= PROOT; ?>Trucks/view/<?= (int)$current['truck_id']; ?>"
         class="badge bg-primary text-decoration-none py-2 px-2" style="font-weight:500;">
         <?= htmlspecialchars($current['truck_reg']); ?>
         <?php if ($current['make'] || $current['model']): ?> · <?= htmlspecialchars(trim(($current['make'] ?? '') . ' ' . ($current['model'] ?? ''))); ?><?php endif; ?>
         <?php if ($current['role_type'] !== 'primary'): ?> · <?= htmlspecialchars($current['role_type']); ?><?php endif; ?>
      </a>
      <span class="text-muted small">since <?= humanDate($current['assigned_from']); ?></span>
    <?php endif; ?>
    <div class="ms-auto">
      <?php if (empty($current)): ?>
        <a href="<?= PROOT; ?>DriverAssignments/add?driver_id=<?= (int)$d['c0d']; ?>" class="btn btn-sm btn-outline-primary">
          <i class="fas fa-plus me-1"></i>Assign truck
        </a>
      <?php else: ?>
        <a href="<?= PROOT; ?>DriverAssignments/view/<?= (int)$current['c0d']; ?>" class="btn btn-sm btn-outline-primary">
          <i class="fas fa-exchange-alt me-1"></i>Manage
        </a>
      <?php endif; ?>
      <a href="<?= PROOT; ?>DriverAssignments?driver_id=<?= (int)$d['c0d']; ?>" class="btn btn-sm btn-outline-secondary ms-1" title="History">
        <i class="fas fa-history"></i>
      </a>
    </div>
  </div>
</div>

<div class="row g-3">
  <div class="col-lg-5">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-body">
        <?php if (!empty($d['photo_url'])): ?>
          <div class="d-flex align-items-start gap-3 mb-3">
            <img src="<?= htmlspecialchars($d['photo_url']); ?>" alt=""
                 style="width:96px; height:128px; object-fit:cover; border-radius:6px; border:1px solid var(--pacific-border, #E2E7EF);">
            <div class="small text-muted">
              <div class="text-uppercase small mb-1" style="letter-spacing:.05em;">Portrait</div>
              <div>Used on the printed Staff&nbsp;ID card.</div>
            </div>
          </div>
        <?php endif; ?>
        <h6 class="text-uppercase text-muted small mb-3">Details</h6>
        <dl class="row mb-0">
          <dt class="col-5 text-muted fw-normal">Employee #</dt><dd class="col-7"><?= htmlspecialchars($d['employee_no'] ?? '—'); ?></dd>
          <dt class="col-5 text-muted fw-normal">National ID</dt><dd class="col-7 font-monospace small"><?= htmlspecialchars($d['id_no'] ?? '—'); ?></dd>
          <dt class="col-5 text-muted fw-normal">Phone 1</dt><dd class="col-7"><?= htmlspecialchars($d['phone_1'] ?? '—'); ?></dd>
          <?php if ($d['phone_2']): ?><dt class="col-5 text-muted fw-normal">Phone 2</dt><dd class="col-7"><?= htmlspecialchars($d['phone_2']); ?></dd><?php endif; ?>
          <?php if ($d['email']):   ?><dt class="col-5 text-muted fw-normal">Email</dt>  <dd class="col-7"><?= htmlspecialchars($d['email']); ?></dd><?php endif; ?>
          <?php if ($d['dob']):     ?><dt class="col-5 text-muted fw-normal">Date of birth</dt><dd class="col-7"><?= humanDate($d['dob']); ?></dd><?php endif; ?>
          <?php if ($d['gender']):  ?><dt class="col-5 text-muted fw-normal">Gender</dt> <dd class="col-7"><?= htmlspecialchars(ucfirst($d['gender'])); ?></dd><?php endif; ?>
          <?php if (!empty($d['blood_group'])): ?><dt class="col-5 text-muted fw-normal">Blood group</dt><dd class="col-7"><?= htmlspecialchars($d['blood_group']); ?></dd><?php endif; ?>
          <dt class="col-5 text-muted fw-normal">Address</dt> <dd class="col-7"><?= htmlspecialchars(trim(($d['address'] ?? '') . ($d['city'] ? ', ' . $d['city'] : ''))) ?: '—'; ?></dd>
          <dt class="col-5 text-muted fw-normal">Country</dt> <dd class="col-7"><?= htmlspecialchars($d['country'] ?? '—'); ?></dd>
          <hr class="my-2"><br>
          <dt class="col-5 text-muted fw-normal">Licence no</dt>    <dd class="col-7 font-monospace small"><?= htmlspecialchars($d['licence_no'] ?? '—'); ?></dd>
          <dt class="col-5 text-muted fw-normal">Licence class</dt> <dd class="col-7"><?= htmlspecialchars($d['licence_class'] ?? '—'); ?></dd>
          <dt class="col-5 text-muted fw-normal">Licence expires</dt><dd class="col-7">
            <?php if ($d['licence_expires']): ?>
              <?= humanDate($d['licence_expires']); ?>
              <?php
                $expired = strtotime($d['licence_expires']) < time();
                $expSoon = !$expired && strtotime($d['licence_expires']) < strtotime('+30 days');
              ?>
              <?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; ?>
          </dd>
          <?php if ($d['hire_date']):        ?><dt class="col-5 text-muted fw-normal">Hire date</dt>    <dd class="col-7"><?= humanDate($d['hire_date']); ?></dd><?php endif; ?>
          <?php if ($d['next_of_kin_name']): ?><dt class="col-5 text-muted fw-normal">Next of kin</dt>  <dd class="col-7"><?= htmlspecialchars($d['next_of_kin_name']); ?><?php if ($d['next_of_kin_phone']): ?> · <?= htmlspecialchars($d['next_of_kin_phone']); ?><?php endif; ?></dd><?php endif; ?>
          <?php if ($d['notes']):            ?><dt class="col-5 text-muted fw-normal">Notes</dt><dd class="col-7"><?= nl2br(htmlspecialchars($d['notes'])); ?></dd><?php endif; ?>
        </dl>
      </div>
    </div>
  </div>

  <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>

        <div id="uploadDocPanel" class="collapse mb-3">
          <form method="POST" action="<?= PROOT; ?>Drivers/uploadDoc/<?= (int)$d['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-6"><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,.doc,.docx"></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>

        <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"></th></tr>
            </thead>
            <tbody>
              <?php foreach ($docs as $doc): ?>
                <?php
                  $expired = !empty($doc['expires_on']) && strtotime($doc['expires_on']) < time();
                  $expSoon = !$expired && !empty($doc['expires_on']) && strtotime($doc['expires_on']) < strtotime('+' . (int)($doc['warn_days'] ?? 30) . ' days');
                ?>
                <tr>
                  <td><?= htmlspecialchars($doc['doc_type_name']); ?></td>
                  <td class="font-monospace small"><?= htmlspecialchars($doc['doc_no'] ?? '—'); ?></td>
                  <td class="small"><?= $doc['issued_on'] ? humanDate($doc['issued_on']) : '—'; ?></td>
                  <td class="small">
                    <?php if ($doc['expires_on']): ?>
                      <?= humanDate($doc['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="text-end">
                    <?php if ($doc['file_url']): ?>
                      <button type="button" class="btn btn-sm btn-outline-secondary js-view-file"
                              data-url="<?= htmlspecialchars($doc['file_url']); ?>"
                              data-name="<?= htmlspecialchars($doc['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)$doc['c0d']; ?>"
                            data-name="<?= htmlspecialchars($doc['doc_type_name']); ?>"
                            title="Delete"><i class="fas fa-trash"></i></button>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if (empty($docs)): ?>
                <tr><td colspan="5" class="text-center text-muted py-4">No documents uploaded yet.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

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

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
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' }
      }
    });
  });
});

function doPickP9Year(driverId) {
  const now = new Date().getFullYear();
  let opts = '';
  for (let y = now; y >= now - 5; y--) opts += '<option value="' + y + '">' + y + '</option>';
  $.confirm({
    title: 'P9 for which year?',
    content: '<label class="form-label small mb-1">Year</label><select id="py" class="form-select form-select-sm">' + opts + '</select>',
    type: 'blue',
    buttons: {
      go: { text: 'Open P9', btnClass: 'btn-primary', action: function() {
        const y = document.getElementById('py').value;
        window.open('<?= PROOT; ?>Payroll/p9/' + driverId + '?year=' + y, '_blank');
      }},
      cancel: function(){}
    }
  });
}

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(); ?>
