<?php
declare(strict_types=1);
/**
 * modules/drivers/edit.php
 *
 * Edit Driver Profile
 * - Core info (name, email, phone, address, active)
 * - Own vehicle (reg/type/colour) — used to auto-assign on bookings
 * - Bank details (stored as JSON) — editable anytime
 * - Audit log on save
 */
require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Admin','Ops']);

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

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

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

/* Decode bank details */
$bank = ['bank_name'=>'','account_name'=>'','account_number'=>'','sort_code'=>'','iban'=>'','notes'=>''];
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, $bank));
}

$errors = [];

/* Handle POST */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    $name   = trim((string)($_POST['name'] ?? ''));
    $email  = trim((string)($_POST['email'] ?? ''));
    $phone  = trim((string)($_POST['phone'] ?? ''));
    $addr   = trim((string)($_POST['address'] ?? ''));
    $active = isset($_POST['is_active']) ? 1 : 0;

    $own_reg   = strtoupper(trim((string)($_POST['own_vehicle_reg_no'] ?? '')));
    $own_type  = trim((string)($_POST['own_vehicle_type'] ?? ''));
    $own_color = trim((string)($_POST['own_vehicle_color'] ?? ''));

    // Bank details fields
    $bank_payload = [
      'bank_name'      => trim((string)($_POST['bank_name'] ?? '')),
      'account_name'   => trim((string)($_POST['account_name'] ?? '')),
      'account_number' => trim((string)($_POST['account_number'] ?? '')),
      'sort_code'      => trim((string)($_POST['sort_code'] ?? '')),
      'iban'           => trim((string)($_POST['iban'] ?? '')),
      'notes'          => trim((string)($_POST['bank_notes'] ?? '')),
    ];
    // If all bank fields empty, store NULL; else JSON
    $hasBank = array_filter($bank_payload, fn($v) => $v !== '');
    $bank_json = $hasBank ? json_encode($bank_payload, JSON_UNESCAPED_UNICODE) : null;

    if ($name === '') $errors[] = 'Name is required.';

    if (!$errors) {
      $upd = db()->prepare("
        UPDATE drivers
           SET name=:name,
               email=:email,
               phone=:phone,
               address=:addr,
               is_active=:act,
               own_vehicle_reg_no=:oreg,
               own_vehicle_type=:otype,
               own_vehicle_color=:ocolor,
               bank_details=:bank
         WHERE id=:id AND company_id=:cid
      ");
      $upd->execute([
        ':name'  => $name,
        ':email' => $email !== '' ? $email : null,
        ':phone' => $phone !== '' ? $phone : null,
        ':addr'  => $addr  !== '' ? $addr  : null,
        ':act'   => $active,
        ':oreg'  => $own_reg  !== '' ? $own_reg  : null,
        ':otype' => $own_type !== '' ? $own_type : null,
        ':ocolor'=> $own_color!== '' ? $own_color: null,
        ':bank'  => $bank_json,
        ':id'    => $id,
        ':cid'   => $cid,
      ]);

      audit_log('driver.update', 'driver', $id, [
        'fields' => ['profile','own_vehicle','bank_details']
      ]);

      redirect('list.php');
    }

  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unexpected error.';
  }
}

/* Re-read for display if errors? Use POST values directly below */
include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Edit Driver</h1>
  <div class="d-flex gap-2">
    <a href="view.php?id=<?= (int)$driver['id'] ?>" class="btn btn-outline-secondary">View</a>
    <a href="list.php" class="btn btn-outline-secondary">Back</a>
  </div>
</div>

<div class="card shadow-sm">
  <div class="card-body">
    <?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; ?>

    <form method="post" autocomplete="off">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">

      <div class="row g-3">
        <!-- Core -->
        <div class="col-md-6">
          <label class="form-label">Full Name</label>
          <input class="form-control" name="name" required
                 value="<?= e($_POST['name'] ?? $driver['name']) ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Email</label>
          <input type="email" class="form-control" name="email"
                 value="<?= e($_POST['email'] ?? $driver['email']) ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Phone</label>
          <input class="form-control" name="phone"
                 value="<?= e($_POST['phone'] ?? $driver['phone']) ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Address</label>
          <input class="form-control" name="address"
                 value="<?= e($_POST['address'] ?? $driver['address']) ?>">
        </div>

        <div class="col-12"><hr class="my-2"></div>

        <!-- Own Vehicle -->
        <div class="col-12"><h6 class="text-uppercase text-muted mb-2">Driver’s Own Vehicle</h6></div>
        <div class="col-md-4">
          <label class="form-label">Registration No.</label>
          <input class="form-control" name="own_vehicle_reg_no"
                 value="<?= e($_POST['own_vehicle_reg_no'] ?? $driver['own_vehicle_reg_no']) ?>">
          <div class="form-text">Used automatically when assigning this driver to a booking.</div>
        </div>
        <div class="col-md-4">
          <label class="form-label">Vehicle Type</label>
          <select class="form-select" name="own_vehicle_type">
            <option value="">—</option>
            <?php
              $currentType = $_POST['own_vehicle_type'] ?? ($driver['own_vehicle_type'] ?? '');
              foreach (VEHICLE_TYPES as $opt):
            ?>
              <option value="<?= e($opt) ?>" <?= ($currentType === $opt ? 'selected':'') ?>>
                <?= e($opt) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label">Colour (optional)</label>
          <input class="form-control" name="own_vehicle_color"
                 value="<?= e($_POST['own_vehicle_color'] ?? $driver['own_vehicle_color']) ?>">
        </div>

        <div class="col-12"><hr class="my-2"></div>

        <!-- Bank Details -->
        <div class="col-12"><h6 class="text-uppercase text-muted mb-2">Bank Details</h6></div>
        <div class="col-md-4">
          <label class="form-label">Bank Name</label>
          <input class="form-control" name="bank_name"
                 value="<?= e($_POST['bank_name'] ?? $bank['bank_name']) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Account Holder Name</label>
          <input class="form-control" name="account_name"
                 value="<?= e($_POST['account_name'] ?? $bank['account_name']) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Account Number</label>
          <input class="form-control" name="account_number"
                 value="<?= e($_POST['account_number'] ?? $bank['account_number']) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Sort Code</label>
          <input class="form-control" name="sort_code"
                 value="<?= e($_POST['sort_code'] ?? $bank['sort_code']) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">IBAN (optional)</label>
          <input class="form-control" name="iban"
                 value="<?= e($_POST['iban'] ?? $bank['iban']) ?>">
        </div>
        <div class="col-md-8">
          <label class="form-label">Bank Notes (optional)</label>
          <textarea class="form-control" name="bank_notes" rows="2"><?= e($_POST['bank_notes'] ?? $bank['notes']) ?></textarea>
        </div>

        <div class="col-12"><hr class="my-2"></div>

        <div class="col-md-6 form-check mt-2">
          <?php $isActivePost = isset($_POST['is_active']) ? 1 : null; ?>
          <input class="form-check-input" type="checkbox" name="is_active" id="is_active"
                 <?= ($isActivePost === 1 || ($isActivePost === null && (int)$driver['is_active'] === 1)) ? 'checked' : '' ?>>
          <label class="form-check-label" for="is_active">Active</label>
        </div>
      </div>

      <div class="mt-3 d-flex gap-2">
        <button class="btn btn-dark">Save Changes</button>
        <a class="btn btn-outline-secondary" href="view.php?id=<?= (int)$driver['id'] ?>">Manage Documents</a>
      </div>
    </form>
  </div>
</div>

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