<?php
declare(strict_types=1);
/**
 * modules/drivers/view.php
 *
 * Driver profile overview:
 * - Profile (name, email, phone, address, status)
 * - Own vehicle (reg/type/colour)
 * - Bank details (JSON) with copy-to-clipboard buttons
 * - Document upload & list (expiry badges, delete)
 */
require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Admin','Ops','MD']);

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('index.php'));

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) redirect('list.php');

/* Fetch driver */
$sel = db()->prepare("SELECT * FROM drivers WHERE id=:id AND company_id=:cid LIMIT 1");
$sel->execute([':id' => $id, ':cid' => $cid]);
$driver = $sel->fetch();
if (!$driver) redirect('list.php');

/* Decode bank details */
$bankDefaults = [
  'bank_name'      => '',
  'account_name'   => '',
  'account_number' => '',
  'sort_code'      => '',
  'iban'           => '',
  'notes'          => '',
];
$bank = $bankDefaults;
if (!empty($driver['bank_details'])) {
  $decoded = json_decode((string)$driver['bank_details'], true);
  if (is_array($decoded)) $bank = array_merge($bank, array_intersect_key($decoded, $bankDefaults));
}

$errors = [];
$ok      = null;

/* Helpers */
function expiry_badge(?string $date): string {
  if (empty($date)) return '<span class="badge text-bg-secondary">No expiry</span>';
  $today = new DateTimeImmutable('today');
  $d     = DateTimeImmutable::createFromFormat('Y-m-d', $date);
  if (!$d) return '<span class="badge text-bg-secondary">'.e($date).'</span>';
  if ($d < $today) return '<span class="badge text-bg-danger">'.e($date).' (expired)</span>';
  $diff = $today->diff($d)->days;
  if ($diff !== false && $diff <= 30) return '<span class="badge text-bg-warning">'.e($date).' (soon)</span>';
  return '<span class="badge text-bg-success">'.e($date).'</span>';
}
function ensure_dir(string $dir): void {
  if (!is_dir($dir)) @mkdir($dir, 0775, true);
}

/* Upload document */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'upload') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));
    $docType = trim((string)($_POST['doc_type'] ?? ''));
    $expiry  = trim((string)($_POST['expiry_date'] ?? ''));
    if ($docType === '') $errors[] = 'Document type is required.';
    if (!isset($_FILES['file']))  $errors[] = 'File is required.';

    if (!$errors) {
      $file = $_FILES['file'];
      if (!is_uploaded_file($file['tmp_name']) || $file['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Upload failed.');
      }
      $ext = strtolower(pathinfo((string)$file['name'], PATHINFO_EXTENSION));
      $safeName = 'drv_'.$id.'_'.time().'_'.bin2hex(random_bytes(4)).($ext ? '.'.$ext : '');
      $dirAbs = dirname(__DIR__, 2).'/public/uploads/driver_docs';
      ensure_dir($dirAbs);
      $destAbs = $dirAbs.'/'.$safeName;
      if (!move_uploaded_file($file['tmp_name'], $destAbs)) {
        throw new RuntimeException('Could not move uploaded file.');
      }
      $publicUrl = 'uploads/driver_docs/'.$safeName;

      $ins = db()->prepare("
        INSERT INTO driver_documents (driver_id, doc_type, upload_url, expiry_date, optional_flag)
        VALUES (:did, :dt, :url, :exp, 0)
      ");
      $ins->execute([
        ':did' => $id,
        ':dt'  => $docType,
        ':url' => $publicUrl,
        ':exp' => $expiry !== '' ? $expiry : null,
      ]);
      audit_log('driver.doc.upload', 'driver', $id, ['doc_type'=>$docType, 'url'=>$publicUrl]);
      $ok = 'Document uploaded.';
    }
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Upload error.';
  }
}

/* Delete document */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_doc') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));
    $docId = (int)($_POST['doc_id'] ?? 0);

    $row = db()->prepare("SELECT * FROM driver_documents WHERE id=:id AND driver_id=:did LIMIT 1");
    $row->execute([':id' => $docId, ':did' => $id]);
    $doc = $row->fetch();

    if ($doc) {
      $del = db()->prepare("DELETE FROM driver_documents WHERE id=:id");
      $del->execute([':id' => $docId]);

      $abs = dirname(__DIR__, 2).'/public/'.(string)$doc['upload_url'];
      if (is_file($abs)) @unlink($abs);

      audit_log('driver.doc.delete','driver',$id,['doc_id'=>$docId]);
      $ok = 'Document deleted.';
    }
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Delete error.';
  }
}

/* Fetch documents (ordered: non-null expiry asc => null expiry last, then latest first) */
$docsStmt = db()->prepare("
  SELECT *
  FROM driver_documents
  WHERE driver_id = :did
  ORDER BY expiry_date IS NULL, expiry_date ASC, id DESC
");
$docsStmt->execute([':did' => $id]);
$docs = $docsStmt->fetchAll();

include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Driver — <?= e($driver['name']) ?></h1>
  <div class="d-flex gap-2">
    <a href="edit.php?id=<?= (int)$driver['id'] ?>" class="btn btn-dark">Edit Driver</a>
    <a href="list.php" class="btn btn-outline-secondary">Back</a>
  </div>
</div>

<?php if ($ok): ?>
  <div class="alert alert-success"><?= e($ok) ?></div>
<?php endif; ?>
<?php if ($errors): ?>
  <div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $e) echo '<li>'.e($e).'</li>'; ?></ul></div>
<?php endif; ?>

<div class="row g-3">
  <!-- Profile & Own Vehicle -->
  <div class="col-12 col-xl-6">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted">Profile</h2>
        <dl class="row mb-0">
          <dt class="col-4">Name</dt><dd class="col-8"><?= e($driver['name']) ?></dd>
          <dt class="col-4">Email</dt><dd class="col-8"><?= e($driver['email']) ?: '—' ?></dd>
          <dt class="col-4">Phone</dt>
          <dd class="col-8">
            <?= e($driver['phone'] ?: '—') ?>
            <?php if (!empty($driver['phone'])): ?>
              <div class="mt-1 d-flex gap-1">
                <a class="btn btn-sm btn-outline-secondary" href="tel:<?= e($driver['phone']) ?>">Call</a>
                <button type="button" class="btn btn-sm btn-outline-secondary js-copy" data-copy="<?= e($driver['phone']) ?>">Copy</button>
              </div>
            <?php endif; ?>
          </dd>
          <dt class="col-4">Address</dt><dd class="col-8"><?= e($driver['address']) ?: '—' ?></dd>
          <dt class="col-4">Status</dt>
          <dd class="col-8">
            <?= ((int)$driver['is_active'] === 1)
              ? '<span class="badge text-bg-success">Active</span>'
              : '<span class="badge text-bg-secondary">Inactive</span>' ?>
          </dd>
        </dl>

        <hr>

        <h2 class="h6 text-uppercase text-muted">Own Vehicle</h2>
        <dl class="row mb-0">
          <dt class="col-4">Reg No</dt><dd class="col-8"><?= e($driver['own_vehicle_reg_no'] ?: '—') ?></dd>
          <dt class="col-4">Type</dt><dd class="col-8"><?= e($driver['own_vehicle_type'] ?: '—') ?></dd>
          <dt class="col-4">Colour</dt><dd class="col-8"><?= e($driver['own_vehicle_color'] ?: '—') ?></dd>
        </dl>
        <div class="text-muted small mt-2">
          If this driver is assigned to a booking and has an own vehicle, it will auto-fill as the vehicle for that job (can be changed there).
        </div>
      </div>
    </div>
  </div>

  <!-- Bank Details -->
  <div class="col-12 col-xl-6">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <div class="d-flex justify-content-between">
          <h2 class="h6 text-uppercase text-muted mb-0">Bank Details</h2>
          <a class="btn btn-sm btn-outline-secondary" href="edit.php?id=<?= (int)$driver['id'] ?>">Edit</a>
        </div>
        <div class="table-responsive mt-2">
          <table class="table align-middle mb-0">
            <tbody>
              <tr>
                <th style="width:30%;">Bank</th>
                <td><?= e($bank['bank_name'] ?: '—') ?></td>
              </tr>
              <tr>
                <th>Account Holder</th>
                <td><?= e($bank['account_name'] ?: '—') ?></td>
              </tr>
              <tr>
                <th>Account Number</th>
                <td>
                  <?= e($bank['account_number'] ?: '—') ?>
                  <?php if ($bank['account_number']): ?>
                    <button type="button" class="btn btn-sm btn-outline-secondary ms-2 js-copy" data-copy="<?= e($bank['account_number']) ?>">Copy</button>
                  <?php endif; ?>
                </td>
              </tr>
              <tr>
                <th>Sort Code</th>
                <td>
                  <?= e($bank['sort_code'] ?: '—') ?>
                  <?php if ($bank['sort_code']): ?>
                    <button type="button" class="btn btn-sm btn-outline-secondary ms-2 js-copy" data-copy="<?= e($bank['sort_code']) ?>">Copy</button>
                  <?php endif; ?>
                </td>
              </tr>
              <tr>
                <th>IBAN</th>
                <td>
                  <?= e($bank['iban'] ?: '—') ?>
                  <?php if ($bank['iban']): ?>
                    <button type="button" class="btn btn-sm btn-outline-secondary ms-2 js-copy" data-copy="<?= e($bank['iban']) ?>">Copy</button>
                  <?php endif; ?>
                </td>
              </tr>
              <tr>
                <th>Notes</th>
                <td><?= nl2br(e($bank['notes'] ?: '—')) ?></td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="text-muted small mt-2">
          Keep payment details current to streamline weekly/monthly payouts.
        </div>
      </div>
    </div>
  </div>

  <!-- Upload -->
  <div class="col-12 col-xl-6">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted">Upload Document</h2>
        <form method="post" enctype="multipart/form-data" class="mt-2">
          <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
          <input type="hidden" name="action" value="upload">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">Document Type</label>
              <input class="form-control" name="doc_type" placeholder="license, insurance, PCO, MOT..." required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Expiry Date (optional)</label>
              <input type="date" class="form-control" name="expiry_date">
            </div>
            <div class="col-12">
              <label class="form-label">File</label>
              <input type="file" class="form-control" name="file" required>
            </div>
          </div>
          <div class="mt-3">
            <button class="btn btn-dark">Upload</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Documents -->
  <div class="col-12 col-xl-6">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted">Documents</h2>
        <div class="table-responsive">
          <table class="table align-middle">
            <thead class="table-light">
              <tr>
                <th>Type</th>
                <th>Expiry</th>
                <th>File</th>
                <th class="text-end">Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php if ($docs): foreach ($docs as $doc): ?>
                <tr>
                  <td><?= e(ucfirst((string)$doc['doc_type'])) ?></td>
                  <td><?= expiry_badge($doc['expiry_date'] ?: null) ?></td>
                  <td>
                    <?php if (!empty($doc['upload_url'])): ?>
                      <a target="_blank" href="<?= e(url_public((string)$doc['upload_url'])) ?>">View</a>
                    <?php else: ?>
                      —
                    <?php endif; ?>
                  </td>
                  <td class="text-end">
                    <form method="post" class="d-inline">
                      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                      <input type="hidden" name="action" value="delete_doc">
                      <input type="hidden" name="doc_id" value="<?= (int)$doc['id'] ?>">
                      <button class="btn btn-sm btn-outline-danger"
                              onclick="return confirm('Delete this document?')">Delete</button>
                    </form>
                  </td>
                </tr>
              <?php endforeach; else: ?>
                <tr><td colspan="4" class="text-center text-muted">No documents uploaded.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
        <div class="text-muted small">
          Tip: Keep licenses, insurance, PCO and MOT up-to-date to avoid assignment issues.
        </div>
      </div>
    </div>
  </div>
</div>

<?php include dirname(__DIR__, 2) . '/includes/footer.php'; ?>

<script>
/* simple copy buttons on this page only */
document.addEventListener('click', function (e) {
  const btn = e.target.closest('.js-copy');
  if (!btn) return;
  const txt = btn.getAttribute('data-copy') || '';
  if (!txt) return;

  navigator.clipboard?.writeText(txt)
    .then(() => {
      const original = btn.textContent;
      btn.textContent = 'Copied';
      btn.classList.remove('btn-outline-secondary');
      btn.classList.add('btn-success');
      setTimeout(() => {
        btn.textContent = original || 'Copy';
        btn.classList.remove('btn-success');
        btn.classList.add('btn-outline-secondary');
      }, 1200);
    })
    .catch(() => alert('Copy failed'));
});
</script>
