<?php
declare(strict_types=1);
/**
 * modules/drivers/add.php
 *
 * Create a driver profile.
 * - Optional own vehicle fields (reg no, type, color) for self-employed drivers
 *   -> used to auto-fill assignments in bookings
 * - Bank details captured as JSON (bank_name, account_name, account_number, sort_code, iban, swift, notes)
 * - Optional photo upload to /public/uploads/drivers/
 *
 * Requires helpers from config/functions.php:
 *   db(), e(), csrf_token(), csrf_verify(), require_role(), url_modules()
 */
require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Admin','Ops']);

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

/** Vehicle type options for own vehicles (self-employed) */
$OWN_VEHICLE_TYPES = [
  'Saloon Car'       => 'Saloon Car',
  'Business Sedan'   => 'Business Sedan',
  'First Class Sedan'=> 'First Class Sedan',
  'Business Van'     => 'Business Van',
  'MPV5'             => 'MPV5',
  'MPV8'             => 'MPV8',
  'Mini Bus'         => 'Mini Bus',
  'Coach'            => 'Coach',
];

$errors = [];
$old    = $_POST ?? [];

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

    $name    = trim((string)($_POST['name'] ?? ''));
    $phone   = trim((string)($_POST['phone'] ?? ''));
    $email   = trim((string)($_POST['email'] ?? ''));
    $address = trim((string)($_POST['address'] ?? ''));

    $is_active = isset($_POST['is_active']) && (int)$_POST['is_active'] === 1 ? 1 : 0;

    // Own vehicle (optional)
    $own_reg   = trim((string)($_POST['own_vehicle_reg_no'] ?? ''));
    $own_type  = trim((string)($_POST['own_vehicle_type'] ?? ''));
    $own_color = trim((string)($_POST['own_vehicle_color'] ?? ''));

    if ($own_type !== '' && !isset($OWN_VEHICLE_TYPES[$own_type])) {
      // normalize to a safe value or mark error
      $errors[] = 'Invalid own vehicle type.';
    }

    // Bank details JSON
    $bank = [
      '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'] ?? '')),
      'swift'          => trim((string)($_POST['swift'] ?? '')),
      'notes'          => trim((string)($_POST['bank_notes'] ?? '')),
    ];
    $bankJson = json_encode($bank, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

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

    // Handle photo upload (optional)
    $photo_url = null;
    if (!empty($_FILES['photo']['name'])) {
      $err = $_FILES['photo']['error'] ?? UPLOAD_ERR_OK;
      if ($err !== UPLOAD_ERR_OK) {
        $errors[] = 'Photo upload failed.';
      } else {
        $tmp  = $_FILES['photo']['tmp_name'];
        $type = (string)mime_content_type($tmp);
        $allowed = ['image/jpeg','image/png','image/webp'];
        if (!in_array($type, $allowed, true)) {
          $errors[] = 'Photo must be a JPG, PNG, or WEBP.';
        } else {
          $uploadsDir = dirname(__DIR__, 2) . '/public/uploads/drivers/';
          if (!is_dir($uploadsDir)) { @mkdir($uploadsDir, 0775, true); }
          $ext  = match ($type) {
            'image/jpeg' => 'jpg',
            'image/png'  => 'png',
            'image/webp' => 'webp',
            default      => 'bin',
          };
          $safeBase = preg_replace('/[^a-zA-Z0-9_\-]/', '_', strtolower($name ?: 'driver'));
          $fileName = $safeBase . '_' . time() . '.' . $ext;
          $dest     = $uploadsDir . $fileName;

          if (!move_uploaded_file($tmp, $dest)) {
            $errors[] = 'Could not save uploaded photo.';
          } else {
            // store relative path (served under /public)
            $photo_url = 'uploads/drivers/' . $fileName;
          }
        }
      }
    }

    if (!$errors) {
      db()->beginTransaction();
      $ins = db()->prepare("
        INSERT INTO drivers
          (company_id, name, phone, email, bank_details, address, photo_url, is_active,
           own_vehicle_reg_no, own_vehicle_type, own_vehicle_color)
        VALUES
          (:cid, :name, :phone, :email, :bank, :addr, :photo, :active,
           :own_reg, :own_type, :own_color)
      ");
      $ins->execute([
        ':cid'       => $cid,
        ':name'      => $name,
        ':phone'     => ($phone !== '' ? $phone : null),
        ':email'     => ($email !== '' ? $email : null),
        ':bank'      => $bankJson,
        ':addr'      => ($address !== '' ? $address : null),
        ':photo'     => $photo_url,
        ':active'    => $is_active,
        ':own_reg'   => ($own_reg !== '' ? strtoupper($own_reg) : null),
        ':own_type'  => ($own_type !== '' ? $own_type : null),
        ':own_color' => ($own_color !== '' ? $own_color : null),
      ]);
      $driverId = (int)db()->lastInsertId();
      db()->commit();

      audit_log('driver.create', 'driver', $driverId, ['name'=>$name, 'own_vehicle'=>$own_reg ? $own_reg : null]);
      redirect(url_modules('drivers/list.php'));
    }

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

include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Add Driver</h1>
  <a href="<?= e(url_modules('drivers/list.php')) ?>" class="btn btn-outline-secondary">Back</a>
</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 $er) echo '<li>'.e($er).'</li>'; ?></ul>
      </div>
    <?php endif; ?>

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

      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label">Full Name <span class="text-danger">*</span></label>
          <input class="form-control" name="name" required value="<?= e($old['name'] ?? '') ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Phone</label>
          <input class="form-control" name="phone" value="<?= e($old['phone'] ?? '') ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Email</label>
          <input type="email" class="form-control" name="email" value="<?= e($old['email'] ?? '') ?>">
        </div>

        <div class="col-12">
          <label class="form-label">Address</label>
          <textarea class="form-control" name="address" rows="2"><?= e($old['address'] ?? '') ?></textarea>
        </div>

        <div class="col-md-4">
          <label class="form-label">Photo (JPG/PNG/WEBP)</label>
          <input type="file" class="form-control" name="photo" accept=".jpg,.jpeg,.png,.webp">
          <div class="form-text">Optional — used on Journey Sheets.</div>
        </div>

        <div class="col-md-2 d-flex align-items-center">
          <div class="form-check mt-4">
            <input class="form-check-input" type="checkbox" id="is_active" name="is_active" value="1" <?= isset($old['is_active']) ? 'checked' : 'checked' ?>>
            <label class="form-check-label" for="is_active">Active</label>
          </div>
        </div>
      </div>

      <hr class="hr-soft">

      <h5 class="mb-2">Own Vehicle (Self-employed) — Optional</h5>
      <div class="row g-3">
        <div class="col-md-4">
          <label class="form-label">Registration Number</label>
          <input class="form-control" name="own_vehicle_reg_no" placeholder="e.g., AB12 CDE" value="<?= e($old['own_vehicle_reg_no'] ?? '') ?>">
        </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 foreach ($OWN_VEHICLE_TYPES as $val => $label): ?>
              <option value="<?= e($val) ?>" <?= (($old['own_vehicle_type'] ?? '') === $val) ? 'selected' : '' ?>>
                <?= e($label) ?>
              </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($old['own_vehicle_color'] ?? '') ?>">
        </div>
      </div>

      <hr class="hr-soft">

      <h5 class="mb-2">Bank Details</h5>
      <div class="row g-3">
        <div class="col-md-4">
          <label class="form-label">Bank Name</label>
          <input class="form-control" name="bank_name" value="<?= e($old['bank_name'] ?? '') ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Account Holder</label>
          <input class="form-control" name="account_name" value="<?= e($old['account_name'] ?? '') ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Account Number</label>
          <input class="form-control" name="account_number" value="<?= e($old['account_number'] ?? '') ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Sort Code</label>
          <input class="form-control" name="sort_code" value="<?= e($old['sort_code'] ?? '') ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">IBAN</label>
          <input class="form-control" name="iban" value="<?= e($old['iban'] ?? '') ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">SWIFT/BIC</label>
          <input class="form-control" name="swift" value="<?= e($old['swift'] ?? '') ?>">
        </div>
        <div class="col-12">
          <label class="form-label">Payment Notes (optional)</label>
          <textarea class="form-control" name="bank_notes" rows="2"><?= e($old['bank_notes'] ?? '') ?></textarea>
        </div>
      </div>

      <div class="mt-3">
        <button class="btn btn-dark">Create Driver</button>
      </div>
    </form>
  </div>
</div>

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