<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/_lib.php';
require_login();

$pdo = db();
$cid = (int)($_SESSION['company_id'] ?? 0);
$uid = (int)($_SESSION['user_id'] ?? 0);
csrf_bootstrap();
fleet_ensure_schema($pdo);
fleet_ensure_vehicle_catalog_schema($pdo);

$msg = '';
$err = '';

function vehicle_catalog_value(array $row, string $nameKey, string $arKey=''): string {
  $ar = $arKey !== '' ? trim((string)($row[$arKey] ?? '')) : '';
  $nm = trim((string)($row[$nameKey] ?? ''));
  return $ar !== '' ? $ar : $nm;
}

function vehicle_usage_exists(PDO $pdo, int $companyId, int $vehicleId): bool {
  $checks = [
    ['vehicle_rental_contracts', 'vehicle_id'],
    ['fleet_limo_trips', 'vehicle_id'],
    ['vehicle_operation_contracts', 'vehicle_id'],
  ];
  foreach ($checks as [$table, $col]) {
    if (!fleet_table_exists($pdo, $table)) continue;
    $st = $pdo->prepare("SELECT COUNT(*) FROM {$table} WHERE company_id=? AND {$col}=?");
    $st->execute([$companyId, $vehicleId]);
    if ((int)$st->fetchColumn() > 0) return true;
  }
  return false;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  try {
    $action = trim((string)($_POST['action'] ?? ''));
    $id = (int)($_POST['id'] ?? 0);

    if ($action === 'save') {
      $plateNo = trim((string)($_POST['plate_no'] ?? ''));
      $makeId = (int)($_POST['make_id'] ?? 0);
      $modelId = (int)($_POST['model_id'] ?? 0);
      $trimId = (int)($_POST['trim_id'] ?? 0);
      $ownershipType = trim((string)($_POST['ownership_type'] ?? 'company'));
      $externalOwnerName = trim((string)($_POST['external_owner_name'] ?? ''));
      $modelYear = trim((string)($_POST['model_year'] ?? ''));
      $color = trim((string)($_POST['color'] ?? ''));
      $chassisNo = trim((string)($_POST['chassis_no'] ?? ''));
      $engineNo = trim((string)($_POST['engine_no'] ?? ''));
      $notes = trim((string)($_POST['notes'] ?? ''));
      $isActive = isset($_POST['is_active']) ? 1 : 0;

      if ($plateNo === '') throw new RuntimeException('رقم اللوحة مطلوب.');
      if ($makeId <= 0 || $modelId <= 0 || $trimId <= 0) throw new RuntimeException('يجب اختيار الشركة والموديل والفئة.');
      if (!in_array($ownershipType, ['company','external'], true)) $ownershipType = 'company';
      if ($ownershipType === 'external' && $externalOwnerName === '') throw new RuntimeException('اسم المالك الخارجي مطلوب للسيارة غير المملوكة.');

      $st = $pdo->prepare("SELECT mk.id AS make_id,mk.name AS make_name,mk.name_ar AS make_name_ar,vm.id AS model_id,vm.name AS model_name,vm.name_ar AS model_name_ar,vt.id AS trim_id,vt.name AS trim_name,vt.name_ar AS trim_name_ar
                           FROM vehicle_trims vt
                           INNER JOIN vehicle_models vm ON vm.id=vt.model_id
                           INNER JOIN vehicle_makes mk ON mk.id=vm.make_id
                           WHERE vt.id=? AND vm.id=? AND mk.id=? LIMIT 1");
      $st->execute([$trimId,$modelId,$makeId]);
      $catalog = $st->fetch(PDO::FETCH_ASSOC);
      if (!$catalog) throw new RuntimeException('الفئة المختارة غير صحيحة.');

      $brand = vehicle_catalog_value($catalog, 'make_name', 'make_name_ar');
      $model = trim(vehicle_catalog_value($catalog, 'model_name', 'model_name_ar') . ' ' . vehicle_catalog_value($catalog, 'trim_name', 'trim_name_ar'));

      $chk = $pdo->prepare("SELECT COUNT(*) FROM vehicles WHERE company_id=? AND plate_no=? AND id<>?");
      $chk->execute([$cid,$plateNo,$id]);
      if ((int)$chk->fetchColumn() > 0) throw new RuntimeException('رقم اللوحة مستخدم بالفعل.');

      if ($id > 0) {
        $sql = "UPDATE vehicles SET plate_no=?, make_id=?, model_id=?, trim_id=?, ownership_type=?, external_owner_name=?, brand=?, model=?, model_year=?, color=?, chassis_no=?, engine_no=?, notes=?, is_active=? WHERE id=? AND company_id=?";
        $pdo->prepare($sql)->execute([$plateNo,$makeId,$modelId,$trimId,$ownershipType,($externalOwnerName ?: null),$brand,$model,$modelYear ?: null,$color ?: null,$chassisNo ?: null,$engineNo ?: null,$notes ?: null,$isActive,$id,$cid]);
        $msg = 'تم تعديل السيارة.';
      } else {
        $sql = "INSERT INTO vehicles (company_id,plate_no,make_id,model_id,trim_id,ownership_type,external_owner_name,brand,model,model_year,color,chassis_no,engine_no,notes,is_active,created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $pdo->prepare($sql)->execute([$cid,$plateNo,$makeId,$modelId,$trimId,$ownershipType,($externalOwnerName ?: null),$brand,$model,$modelYear ?: null,$color ?: null,$chassisNo ?: null,$engineNo ?: null,$notes ?: null,$isActive,$uid ?: null]);
        $msg = 'تم إضافة السيارة.';
      }
    }

    if ($action === 'delete') {
      if ($id <= 0) throw new RuntimeException('السيارة غير صحيحة.');
      if (vehicle_usage_exists($pdo, $cid, $id)) throw new RuntimeException('لا يمكن حذف السيارة لأنها مرتبطة بعمليات أخرى.');
      $pdo->prepare("DELETE FROM vehicles WHERE id=? AND company_id=?")->execute([$id,$cid]);
      $msg = 'تم حذف السيارة.';
    }
  } catch (Throwable $e) {
    $err = $e->getMessage();
  }
}

$makes = [];
$models = [];
$trims = [];
if (fleet_table_exists($pdo, 'vehicle_makes')) {
  $st = $pdo->query("SELECT id, company_id, name, name_ar, is_active, sort_order FROM vehicle_makes WHERE is_active=1 AND company_id IS NULL ORDER BY sort_order, name");
  $makes = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
}
if (fleet_table_exists($pdo, 'vehicle_models')) {
  $st = $pdo->query("SELECT id, make_id, name, name_ar, is_active, sort_order FROM vehicle_models WHERE is_active=1 ORDER BY make_id, sort_order, name");
  $models = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
}
if (fleet_table_exists($pdo, 'vehicle_trims')) {
  $st = $pdo->query("SELECT id, model_id, name, name_ar, full_name, is_active, sort_order FROM vehicle_trims WHERE is_active=1 ORDER BY model_id, sort_order, name");
  $trims = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
}

$rows = [];
$select = "SELECT v.*, mk.name AS make_name, mk.name_ar AS make_name_ar, vm.name AS model_name, vm.name_ar AS model_name_ar, vt.name AS trim_name, vt.name_ar AS trim_name_ar, vt.full_name AS trim_full_name
           FROM vehicles v
           LEFT JOIN vehicle_makes mk ON mk.id=v.make_id
           LEFT JOIN vehicle_models vm ON vm.id=v.model_id
           LEFT JOIN vehicle_trims vt ON vt.id=v.trim_id
           WHERE v.company_id=?
           ORDER BY v.id DESC";
$st = $pdo->prepare($select);
$st->execute([$cid]);
$rows = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

$catalogReady = !empty($makes) && !empty($models) && !empty($trims);

render_layout('أسطول السيارات','إدارة السيارات <span class="mx-1">/</span> أسطول السيارات', function() use($rows,$makes,$models,$trims,$msg,$err,$catalogReady){ ?>
<div class="container-fluid mt-3">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <div class="fw-bold fs-4">أسطول السيارات</div>
      <div class="text-secondary small">إضافة السيارات المملوكة للشركة أو غير المملوكة مع الربط على كتالوج أنواع السيارات.</div>
    </div>
    <button class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#vehicleModal" <?= $catalogReady ? '' : 'disabled' ?>><i class="bi bi-plus-lg"></i> إضافة سيارة</button>
  </div>

  <?php if($msg): ?><div class="alert alert-success mt-3"><?= h($msg) ?></div><?php endif; ?>
  <?php if($err): ?><div class="alert alert-danger mt-3"><?= h($err) ?></div><?php endif; ?>
  <?php if(!$catalogReady): ?><div class="alert alert-warning mt-3">كتالوج أنواع السيارات غير جاهز بعد. شغّل ملف تحديث قاعدة البيانات الخاص بكتالوج السيارات أولًا.</div><?php endif; ?>

  <div class="card cardx mt-3"><div class="table-responsive p-3">
    <table class="table align-middle mb-0">
      <thead>
        <tr class="text-secondary small">
          <th>#</th>
          <th>رقم اللوحة</th>
          <th>نوع الملكية</th>
          <th>الشركة / الموديل / الفئة</th>
          <th>سنة الصنع</th>
          <th>اللون</th>
          <th>الحالة</th>
          <th class="text-end">الإجراءات</th>
        </tr>
      </thead>
      <tbody>
      <?php if(!$rows): ?><tr><td colspan="8" class="text-center text-secondary py-4">لا توجد سيارات مسجلة.</td></tr><?php endif; ?>
      <?php foreach($rows as $r):
        $makeLabel = vehicle_catalog_value($r, 'make_name', 'make_name_ar') ?: trim((string)($r['brand'] ?? ''));
        $modelLabel = vehicle_catalog_value($r, 'model_name', 'model_name_ar');
        $trimLabel = vehicle_catalog_value($r, 'trim_name', 'trim_name_ar');
        $ownershipLabel = ($r['ownership_type'] ?? 'company') === 'external' ? 'غير مملوكة' : 'مملوكة';
        $ownerText = ($r['ownership_type'] ?? 'company') === 'external' ? trim((string)($r['external_owner_name'] ?? '')) : '';
      ?>
        <tr>
          <td><?= (int)$r['id'] ?></td>
          <td class="fw-semibold"><?= h($r['plate_no']) ?></td>
          <td>
            <div><?= h($ownershipLabel) ?></div>
            <?php if($ownerText !== ''): ?><div class="small text-secondary"><?= h($ownerText) ?></div><?php endif; ?>
          </td>
          <td>
            <div class="fw-semibold"><?= h(trim($makeLabel . ' / ' . $modelLabel . ' / ' . $trimLabel, ' /')) ?></div>
            <?php if(!empty($r['chassis_no']) || !empty($r['engine_no'])): ?>
              <div class="small text-secondary">
                <?php if(!empty($r['chassis_no'])): ?>شاسيه: <?= h($r['chassis_no']) ?><?php endif; ?>
                <?php if(!empty($r['chassis_no']) && !empty($r['engine_no'])): ?> · <?php endif; ?>
                <?php if(!empty($r['engine_no'])): ?>موتور: <?= h($r['engine_no']) ?><?php endif; ?>
              </div>
            <?php endif; ?>
          </td>
          <td><?= h($r['model_year'] ?: '—') ?></td>
          <td><?= h($r['color'] ?: '—') ?></td>
          <td><?= !empty($r['is_active']) ? '<span class="badge bg-success-subtle text-success border">مفعلة</span>' : '<span class="badge bg-secondary-subtle text-secondary border">غير مفعلة</span>' ?></td>
          <td class="text-end">
            <button type="button" class="btn btn-outline-secondary btn-sm js-edit"
              data-id="<?= (int)$r['id'] ?>"
              data-plate="<?= h($r['plate_no']) ?>"
              data-make="<?= (int)($r['make_id'] ?? 0) ?>"
              data-model="<?= (int)($r['model_id'] ?? 0) ?>"
              data-trim="<?= (int)($r['trim_id'] ?? 0) ?>"
              data-ownership="<?= h($r['ownership_type'] ?: 'company') ?>"
              data-owner="<?= h($r['external_owner_name'] ?? '') ?>"
              data-year="<?= h($r['model_year'] ?? '') ?>"
              data-color="<?= h($r['color'] ?? '') ?>"
              data-chassis="<?= h($r['chassis_no'] ?? '') ?>"
              data-engine="<?= h($r['engine_no'] ?? '') ?>"
              data-notes="<?= h($r['notes'] ?? '') ?>"
              data-active="<?= (int)($r['is_active'] ?? 1) ?>">تعديل</button>
            <form method="post" class="d-inline" onsubmit="return confirm('حذف السيارة؟');">
              <?= csrf_field() ?>
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
              <button class="btn btn-outline-danger btn-sm">حذف</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div></div>
</div>

<div class="modal fade modal-erp" id="vehicleModal" tabindex="-1">
  <div class="modal-dialog modal-lg"><div class="modal-content">
    <form method="post" id="vehicleForm">
      <?= csrf_field() ?>
      <input type="hidden" name="action" value="save">
      <input type="hidden" name="id" id="v_id" value="0">
      <div class="modal-header"><h5 class="modal-title" id="vehicle_title">إضافة سيارة</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-4"><label class="form-label">رقم اللوحة</label><input class="form-control" name="plate_no" id="v_plate" required></div>
          <div class="col-md-4"><label class="form-label">نوع الملكية</label><select class="form-select" name="ownership_type" id="v_ownership"><option value="company">مملوكة للشركة</option><option value="external">غير مملوكة للشركة</option></select></div>
          <div class="col-md-4" id="external_owner_wrap" style="display:none;"><label class="form-label">اسم المالك الخارجي</label><input class="form-control" name="external_owner_name" id="v_owner"></div>

          <div class="col-md-4"><label class="form-label">الشركة</label><select class="form-select selectpicker" data-live-search="true" data-width="100%" name="make_id" id="v_make" required><option value="">اختر الشركة</option><?php foreach($makes as $mk): ?><option value="<?= (int)$mk['id'] ?>"><?= h(vehicle_catalog_value($mk, 'name', 'name_ar')) ?></option><?php endforeach; ?></select></div>
          <div class="col-md-4"><label class="form-label">الموديل</label><select class="form-select selectpicker" data-live-search="true" data-width="100%" name="model_id" id="v_model" required><option value="">اختر الموديل</option></select></div>
          <div class="col-md-4"><label class="form-label">الفئة</label><select class="form-select selectpicker" data-live-search="true" data-width="100%" name="trim_id" id="v_trim" required><option value="">اختر الفئة</option></select></div>

          <div class="col-md-4"><label class="form-label">سنة الصنع</label><input class="form-control" name="model_year" id="v_year"></div>
          <div class="col-md-4"><label class="form-label">اللون</label><input class="form-control" name="color" id="v_color"></div>
          <div class="col-md-4 d-flex align-items-end"><div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="is_active" id="v_active" checked><label class="form-check-label" for="v_active">مفعلة</label></div></div>

          <div class="col-md-6"><label class="form-label">رقم الشاسيه</label><input class="form-control" name="chassis_no" id="v_chassis"></div>
          <div class="col-md-6"><label class="form-label">رقم الموتور</label><input class="form-control" name="engine_no" id="v_engine"></div>
          <div class="col-12"><label class="form-label">ملاحظات</label><textarea class="form-control" rows="3" name="notes" id="v_notes"></textarea></div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-dark">حفظ</button></div>
    </form>
  </div></div>
</div>

<script>
const VEHICLE_MODELS = <?= json_encode(array_map(function($r){ return ['id'=>(int)$r['id'],'make_id'=>(int)$r['make_id'],'name'=>vehicle_catalog_value($r,'name','name_ar')]; }, $models), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
const VEHICLE_TRIMS = <?= json_encode(array_map(function($r){ return ['id'=>(int)$r['id'],'model_id'=>(int)$r['model_id'],'name'=>vehicle_catalog_value($r,'name','name_ar')]; }, $trims), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;

document.addEventListener('DOMContentLoaded', function(){
  const modalEl = document.getElementById('vehicleModal');
  const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
  const form = document.getElementById('vehicleForm');
  const makeSel = document.getElementById('v_make');
  const modelSel = document.getElementById('v_model');
  const trimSel = document.getElementById('v_trim');
  const ownershipSel = document.getElementById('v_ownership');
  const ownerWrap = document.getElementById('external_owner_wrap');
  const ownerInput = document.getElementById('v_owner');

  function refreshPicker(el){
    if (window.jQuery && jQuery(el).selectpicker) {
      jQuery(el).selectpicker('destroy');
      jQuery(el).selectpicker();
    }
  }

  function setOwnership(){
    const external = ownershipSel.value === 'external';
    ownerWrap.style.display = external ? '' : 'none';
    ownerInput.required = external;
    if (!external) ownerInput.value = '';
  }

  function fillModels(selectedModelId){
    const makeId = parseInt(makeSel.value || '0', 10);
    modelSel.innerHTML = '<option value="">اختر الموديل</option>';
    trimSel.innerHTML = '<option value="">اختر الفئة</option>';
    VEHICLE_MODELS.filter(x => x.make_id === makeId).forEach(function(item){
      const opt = document.createElement('option');
      opt.value = item.id;
      opt.textContent = item.name;
      modelSel.appendChild(opt);
    });
    if (selectedModelId) modelSel.value = String(selectedModelId);
    refreshPicker(modelSel);
    refreshPicker(trimSel);
  }

  function fillTrims(selectedTrimId){
    const modelId = parseInt(modelSel.value || '0', 10);
    trimSel.innerHTML = '<option value="">اختر الفئة</option>';
    VEHICLE_TRIMS.filter(x => x.model_id === modelId).forEach(function(item){
      const opt = document.createElement('option');
      opt.value = item.id;
      opt.textContent = item.name;
      trimSel.appendChild(opt);
    });
    if (selectedTrimId) trimSel.value = String(selectedTrimId);
    refreshPicker(trimSel);
  }

  function resetForm(){
    form.reset();
    document.getElementById('v_id').value = '0';
    document.getElementById('vehicle_title').textContent = 'إضافة سيارة';
    document.getElementById('v_active').checked = true;
    makeSel.value = '';
    fillModels('');
    fillTrims('');
    setOwnership();
    refreshPicker(makeSel);
  }

  makeSel.addEventListener('change', function(){ fillModels(''); });
  modelSel.addEventListener('change', function(){ fillTrims(''); });
  ownershipSel.addEventListener('change', setOwnership);
  modalEl.addEventListener('hidden.bs.modal', resetForm);

  document.querySelectorAll('.js-edit').forEach(function(btn){
    btn.addEventListener('click', function(){
      document.getElementById('v_id').value = this.dataset.id || '0';
      document.getElementById('vehicle_title').textContent = 'تعديل سيارة';
      document.getElementById('v_plate').value = this.dataset.plate || '';
      document.getElementById('v_ownership').value = this.dataset.ownership || 'company';
      document.getElementById('v_owner').value = this.dataset.owner || '';
      document.getElementById('v_year').value = this.dataset.year || '';
      document.getElementById('v_color').value = this.dataset.color || '';
      document.getElementById('v_chassis').value = this.dataset.chassis || '';
      document.getElementById('v_engine').value = this.dataset.engine || '';
      document.getElementById('v_notes').value = this.dataset.notes || '';
      document.getElementById('v_active').checked = (this.dataset.active || '1') === '1';
      makeSel.value = this.dataset.make || '';
      fillModels(this.dataset.model || '');
      fillTrims(this.dataset.trim || '');
      setOwnership();
      refreshPicker(makeSel);
      modal.show();
    });
  });

  resetForm();
});
</script>
<?php });
