<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/audit.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_vehicle_types_schema($pdo);

$err = '';
$msg = '';
$editingId = (int)($_GET['edit'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $action = trim((string)($_POST['action'] ?? ''));
  try {
    if ($action === 'create') {
      $name = trim((string)($_POST['name'] ?? ''));
      $category = trim((string)($_POST['category'] ?? ''));
      if ($name === '') throw new RuntimeException('اسم نوع المركبة مطلوب.');
      $chk = $pdo->prepare("SELECT id FROM vehicle_types WHERE company_id=? AND name=? LIMIT 1");
      $chk->execute([$cid, $name]);
      if ($chk->fetchColumn()) throw new RuntimeException('نوع المركبة مسجل بالفعل.');
      $pdo->prepare("INSERT INTO vehicle_types (company_id, name, category, is_system, is_active, created_by) VALUES (?,?,?,?,?,?)")
          ->execute([$cid, $name, $category ?: null, 0, 1, $uid ?: null]);
      $id = (int)$pdo->lastInsertId();
      audit_log($pdo, ['company_id'=>$cid,'user_id'=>$uid,'module'=>'fleet','action'=>'CREATE_VEHICLE_TYPE','entity_type'=>'vehicle_type','entity_id'=>(string)$id,'description'=>'إضافة نوع مركبة '.$name]);
      flash_set('تم إضافة نوع المركبة بنجاح.');
      header('Location: vehicle_types.php'); exit;
    }

    if ($action === 'update') {
      $id = (int)($_POST['id'] ?? 0);
      $name = trim((string)($_POST['name'] ?? ''));
      $category = trim((string)($_POST['category'] ?? ''));
      if ($id <= 0) throw new RuntimeException('العنصر غير صالح.');
      if ($name === '') throw new RuntimeException('اسم نوع المركبة مطلوب.');
      $chk = $pdo->prepare("SELECT id FROM vehicle_types WHERE company_id=? AND name=? AND id<>? LIMIT 1");
      $chk->execute([$cid, $name, $id]);
      if ($chk->fetchColumn()) throw new RuntimeException('يوجد نوع آخر بنفس الاسم.');
      $pdo->prepare("UPDATE vehicle_types SET name=?, category=?, updated_at=NOW() WHERE id=? AND company_id=?")
          ->execute([$name, $category ?: null, $id, $cid]);
      audit_log($pdo, ['company_id'=>$cid,'user_id'=>$uid,'module'=>'fleet','action'=>'UPDATE_VEHICLE_TYPE','entity_type'=>'vehicle_type','entity_id'=>(string)$id,'description'=>'تعديل نوع مركبة '.$name]);
      flash_set('تم تعديل نوع المركبة.');
      header('Location: vehicle_types.php'); exit;
    }

    if ($action === 'delete') {
      $id = (int)($_POST['id'] ?? 0);
      $st = $pdo->prepare("SELECT name, is_system FROM vehicle_types WHERE id=? AND company_id=? LIMIT 1");
      $st->execute([$id, $cid]);
      $row = $st->fetch(PDO::FETCH_ASSOC);
      if (!$row) throw new RuntimeException('نوع المركبة غير موجود.');
      $use = $pdo->prepare("SELECT COUNT(*) FROM vehicles WHERE company_id=? AND vehicle_type_id=?");
      $use->execute([$cid, $id]);
      if ((int)$use->fetchColumn() > 0) throw new RuntimeException('لا يمكن حذف النوع لأنه مستخدم في صفحة المركبات.');
      $pdo->prepare("DELETE FROM vehicle_types WHERE id=? AND company_id=?")->execute([$id, $cid]);
      audit_log($pdo, ['company_id'=>$cid,'user_id'=>$uid,'module'=>'fleet','action'=>'DELETE_VEHICLE_TYPE','entity_type'=>'vehicle_type','entity_id'=>(string)$id,'description'=>'حذف نوع مركبة '.$row['name']]);
      flash_set('تم حذف نوع المركبة.');
      header('Location: vehicle_types.php'); exit;
    }
  } catch (Throwable $e) {
    $err = $e->getMessage();
    $editingId = (int)($_POST['id'] ?? $editingId);
  }
}

$rows = $pdo->prepare("SELECT vt.*, (SELECT COUNT(*) FROM vehicles v WHERE v.company_id=vt.company_id AND v.vehicle_type_id=vt.id) AS vehicles_count FROM vehicle_types vt WHERE vt.company_id=? ORDER BY vt.category IS NULL, vt.category, vt.name");
$rows->execute([$cid]);
$rows = $rows->fetchAll(PDO::FETCH_ASSOC) ?: [];

$editRow = null;
if ($editingId > 0) {
  foreach ($rows as $r) {
    if ((int)$r['id'] === $editingId) { $editRow = $r; break; }
  }
}

render_layout('أنواع المركبات','إدارة السيارات <span class="mx-1">/</span> أنواع المركبات', function() use ($rows, $err, $editRow) {
?>
<div class="container-fluid mt-3">
  <div class="d-flex align-items-start align-items-md-center justify-content-between flex-column flex-md-row gap-2 mb-3">
    <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="#createVehicleTypeModal"><i class="bi bi-plus-lg"></i> إضافة نوع جديد</button>
  </div>

  <?php if($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>

  <div class="card cardx">
    <div class="p-3 d-flex align-items-center justify-content-between">
      <div class="fw-bold">القائمة الحالية</div>
      <span class="text-secondary small"><?= count($rows) ?> نوع</span>
    </div>
    <div class="table-responsive px-3 pb-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 class="text-end">إجراءات</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($rows as $r): ?>
          <tr>
            <td class="text-secondary"><?= (int)$r['id'] ?></td>
            <td class="fw-semibold"><?= h($r['name']) ?></td>
            <td><?= h($r['category'] ?: '-') ?></td>
            <td>
              <?php if((int)$r['is_system'] === 1): ?>
                <span class="badge bg-primary-subtle text-primary border">افتراضي</span>
              <?php else: ?>
                <span class="badge bg-secondary-subtle text-secondary border">مخصص</span>
              <?php endif; ?>
            </td>
            <td><?= (int)$r['vehicles_count'] ?> مركبة</td>
            <td class="text-end">
              <a class="btn btn-sm btn-outline-primary" href="?edit=<?= (int)$r['id'] ?>"><i class="bi bi-pencil-square"></i> تعديل</a>
              <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-sm btn-outline-danger"><i class="bi bi-trash"></i> حذف</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if(!$rows): ?>
          <tr><td colspan="6" class="text-center text-secondary py-4">لا توجد أنواع مركبات بعد.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade modal-erp" id="createVehicleTypeModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="create">
        <div class="modal-header">
          <h5 class="modal-title">إضافة نوع مركبة</h5>
          <button type="button" class="btn-close m-0" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <div class="row g-3 modal-inline-grid">
            <div class="col-md-6">
              <label class="form-label">اسم النوع</label>
              <input class="form-control" name="name" required value="<?= h($_POST['action'] ?? '' === 'create' ? ($_POST['name'] ?? '') : '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">التصنيف</label>
              <input class="form-control" name="category" value="<?= h($_POST['action'] ?? '' === 'create' ? ($_POST['category'] ?? '') : '') ?>" placeholder="مثال: سيارات ركوب أو شاحنات">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-dark"><i class="bi bi-check2-circle"></i> حفظ</button>
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إغلاق</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php if($editRow): ?>
<div class="modal fade modal-erp" id="editVehicleTypeModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="update">
        <input type="hidden" name="id" value="<?= (int)$editRow['id'] ?>">
        <div class="modal-header">
          <h5 class="modal-title">تعديل نوع المركبة</h5>
          <button type="button" class="btn-close m-0" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <div class="row g-3 modal-inline-grid">
            <div class="col-md-6">
              <label class="form-label">اسم النوع</label>
              <input class="form-control" name="name" required value="<?= h($editRow['name']) ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">التصنيف</label>
              <input class="form-control" name="category" value="<?= h($editRow['category'] ?? '') ?>">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-dark"><i class="bi bi-check2-circle"></i> حفظ التعديلات</button>
          <a class="btn btn-outline-secondary" href="vehicle_types.php">إغلاق</a>
        </div>
      </form>
    </div>
  </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function(){
  const el = document.getElementById('editVehicleTypeModal');
  if (el && window.bootstrap) new bootstrap.Modal(el).show();
});
</script>
<?php endif; ?>

<?php if(!$editRow && $err && (($_POST['action'] ?? '') === 'create')): ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
  const el = document.getElementById('createVehicleTypeModal');
  if (el && window.bootstrap) new bootstrap.Modal(el).show();
});
</script>
<?php endif; ?>
<?php }); ?>
