<?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 = '';
$editingId = (int)($_GET['edit'] ?? 0);

function vehicle_type_node_label(string $type): string {
  return match (strtoupper($type)) {
    'BRAND' => 'شركة',
    'MODEL' => 'موديل',
    default => 'فئة',
  };
}

function vehicle_type_expected_child(string $type): ?string {
  return match (strtoupper($type)) {
    'BRAND' => 'MODEL',
    'MODEL' => 'TRIM',
    default => null,
  };
}

function vehicle_type_can_delete(PDO $pdo, int $companyId, array $row): bool {
  if ((int)($row['children_count'] ?? 0) > 0) return false;
  if ((int)($row['vehicles_count'] ?? 0) > 0) return false;
  return true;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $action = trim((string)($_POST['action'] ?? ''));
  try {
    if ($action === 'create') {
      $parentId = (int)($_POST['parent_id'] ?? 0) ?: null;
      $nodeType = strtoupper(trim((string)($_POST['node_type'] ?? 'BRAND')));
      $name = trim((string)($_POST['name'] ?? ''));
      if ($name === '') throw new RuntimeException('الاسم مطلوب.');
      if (!in_array($nodeType, ['BRAND','MODEL','TRIM'], true)) throw new RuntimeException('نوع العنصر غير صالح.');

      if ($parentId) {
        $pst = $pdo->prepare("SELECT * FROM vehicle_types WHERE id=? AND company_id=? LIMIT 1");
        $pst->execute([$parentId, $cid]);
        $parent = $pst->fetch(PDO::FETCH_ASSOC);
        if (!$parent) throw new RuntimeException('العنصر الأب غير موجود.');
        $expected = vehicle_type_expected_child((string)$parent['node_type']);
        if (!$expected || $expected !== $nodeType) throw new RuntimeException('لا يمكن إضافة هذا النوع تحت العنصر المختار.');
      } else {
        if ($nodeType !== 'BRAND') throw new RuntimeException('العنصر الجذري يجب أن يكون شركة سيارة.');
      }

      $chk = $parentId
        ? $pdo->prepare("SELECT id FROM vehicle_types WHERE company_id=? AND parent_id=? AND name=? LIMIT 1")
        : $pdo->prepare("SELECT id FROM vehicle_types WHERE company_id=? AND parent_id IS NULL AND name=? LIMIT 1");
      $chk->execute($parentId ? [$cid, $parentId, $name] : [$cid, $name]);
      if ($chk->fetchColumn()) throw new RuntimeException('هذا العنصر مسجل بالفعل تحت نفس المستوى.');

      $sortOrder = 10;
      if ($parentId) {
        $st = $pdo->prepare("SELECT COALESCE(MAX(sort_order),0)+10 FROM vehicle_types WHERE company_id=? AND parent_id=?");
        $st->execute([$cid, $parentId]);
      } else {
        $st = $pdo->prepare("SELECT COALESCE(MAX(sort_order),0)+10 FROM vehicle_types WHERE company_id=? AND parent_id IS NULL");
        $st->execute([$cid]);
      }
      $sortOrder = max(10, (int)$st->fetchColumn());

      $id = fleet_vehicle_type_insert($pdo, $cid, $parentId, $nodeType, $name, $sortOrder, 0, $uid ?: null);
      audit_log($pdo, ['company_id'=>$cid,'user_id'=>$uid,'module'=>'fleet','action'=>'CREATE_VEHICLE_TYPE_NODE','entity_type'=>'vehicle_type','entity_id'=>(string)$id,'description'=>'إضافة '.vehicle_type_node_label($nodeType).' '.$name]);
      flash_set('تمت الإضافة بنجاح.');
      header('Location: vehicle_types.php'); exit;
    }

    if ($action === 'update') {
      $id = (int)($_POST['id'] ?? 0);
      $name = trim((string)($_POST['name'] ?? ''));
      if ($id <= 0 || $name === '') throw new RuntimeException('البيانات غير مكتملة.');
      $st = $pdo->prepare("SELECT * 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('العنصر غير موجود.');
      $parentId = $row['parent_id'] !== null ? (int)$row['parent_id'] : null;
      $chk = $parentId
        ? $pdo->prepare("SELECT id FROM vehicle_types WHERE company_id=? AND parent_id=? AND name=? AND id<>? LIMIT 1")
        : $pdo->prepare("SELECT id FROM vehicle_types WHERE company_id=? AND parent_id IS NULL AND name=? AND id<>? LIMIT 1");
      $chk->execute($parentId ? [$cid, $parentId, $name, $id] : [$cid, $name, $id]);
      if ($chk->fetchColumn()) throw new RuntimeException('يوجد عنصر آخر بنفس الاسم في نفس المستوى.');

      $display = fleet_vehicle_type_compose_display_name($pdo, $cid, $parentId, $name);
      $pdo->prepare("UPDATE vehicle_types SET name=?, display_name=?, updated_at=NOW() WHERE id=? AND company_id=?")
          ->execute([$name, $display, $id, $cid]);

      $children = $pdo->prepare("SELECT id, name FROM vehicle_types WHERE company_id=? AND parent_id=?");
      $children->execute([$cid, $id]);
      foreach ($children->fetchAll(PDO::FETCH_ASSOC) ?: [] as $child) {
        $childDisplay = fleet_vehicle_type_compose_display_name($pdo, $cid, $id, (string)$child['name']);
        $pdo->prepare("UPDATE vehicle_types SET display_name=?, updated_at=NOW() WHERE id=? AND company_id=?")
            ->execute([$childDisplay, (int)$child['id'], $cid]);
        $grand = $pdo->prepare("SELECT id, name FROM vehicle_types WHERE company_id=? AND parent_id=?");
        $grand->execute([$cid, (int)$child['id']]);
        foreach ($grand->fetchAll(PDO::FETCH_ASSOC) ?: [] as $g) {
          $gDisplay = fleet_vehicle_type_compose_display_name($pdo, $cid, (int)$child['id'], (string)$g['name']);
          $pdo->prepare("UPDATE vehicle_types SET display_name=?, updated_at=NOW() WHERE id=? AND company_id=?")
              ->execute([$gDisplay, (int)$g['id'], $cid]);
        }
      }

      audit_log($pdo, ['company_id'=>$cid,'user_id'=>$uid,'module'=>'fleet','action'=>'UPDATE_VEHICLE_TYPE_NODE','entity_type'=>'vehicle_type','entity_id'=>(string)$id,'description'=>'تعديل '.vehicle_type_node_label((string)$row['node_type']).' '.$name]);
      flash_set('تم التعديل بنجاح.');
      header('Location: vehicle_types.php'); exit;
    }

    if ($action === 'delete') {
      $id = (int)($_POST['id'] ?? 0);
      $st = $pdo->prepare("SELECT vt.*, (SELECT COUNT(*) FROM vehicle_types c WHERE c.company_id=vt.company_id AND c.parent_id=vt.id AND c.is_active=1) AS children_count, (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.id=? AND vt.company_id=? LIMIT 1");
      $st->execute([$id, $cid]);
      $row = $st->fetch(PDO::FETCH_ASSOC);
      if (!$row) throw new RuntimeException('العنصر غير موجود.');
      if (!vehicle_type_can_delete($pdo, $cid, $row)) 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_NODE','entity_type'=>'vehicle_type','entity_id'=>(string)$id,'description'=>'حذف '.$row['display_name']]);
      flash_set('تم الحذف بنجاح.');
      header('Location: vehicle_types.php'); exit;
    }
  } catch (Throwable $e) {
    $err = $e->getMessage();
    $editingId = (int)($_POST['id'] ?? $editingId);
  }
}

[$rows, $byParent] = fleet_vehicle_type_tree($pdo, $cid);
$editRow = null;
foreach ($rows as $r) if ((int)$r['id'] === $editingId) { $editRow = $r; break; }

function render_vehicle_type_tree(array $byParent, int $parentId = 0, int $level = 0): void {
  if (empty($byParent[$parentId])) return;
  foreach ($byParent[$parentId] as $row) {
    $id = (int)$row['id'];
    $canDelete = ((int)($row['children_count'] ?? 0) === 0 && (int)($row['vehicles_count'] ?? 0) === 0);
    $pad = 18 + ($level * 28);
    $icon = match (strtoupper((string)$row['node_type'])) {
      'BRAND' => 'bi-building',
      'MODEL' => 'bi-diagram-3',
      default => 'bi-car-front-fill',
    };
    $nextType = vehicle_type_expected_child((string)$row['node_type']);
    echo '<tr>';
    echo '<td class="text-secondary">'. $id .'</td>';
    echo '<td><div class="d-flex align-items-center gap-2" style="padding-right:'. $pad .'px">';
    echo '<span class="text-primary"><i class="bi '. $icon .'"></i></span>';
    echo '<div><div class="fw-semibold">'. h($row['name']) .'</div>';
    echo '<div class="small text-secondary">'. h($row['display_name'] ?: $row['name']) .'</div></div></div></td>';
    echo '<td><span class="badge bg-light text-dark border">'. h(vehicle_type_node_label((string)$row['node_type'])) .'</span></td>';
    echo '<td>'. (int)($row['children_count'] ?? 0) .'</td>';
    echo '<td>'. (int)($row['vehicles_count'] ?? 0) .'</td>';
    echo '<td>'. ((int)($row['is_system'] ?? 0) === 1 ? '<span class="badge bg-primary-subtle text-primary border">افتراضي</span>' : '<span class="badge bg-secondary-subtle text-secondary border">مخصص</span>') .'</td>';
    echo '<td class="text-end">';
    if ($nextType) {
      echo '<button type="button" class="btn btn-sm btn-outline-dark me-1 js-open-create-child" data-parent-id="'. $id .'" data-node-type="'. h($nextType) .'" data-parent-name="'. h($row['display_name'] ?: $row['name']) .'"><i class="bi bi-plus-lg"></i> إضافة '. h(vehicle_type_node_label($nextType)) .'</button>';
    }
    echo '<a class="btn btn-sm btn-outline-primary me-1" href="?edit='. $id .'"><i class="bi bi-pencil-square"></i> تعديل</a>';
    if ($canDelete) {
      echo '<form method="post" class="d-inline" onsubmit="return confirm(\'حذف هذا العنصر؟\');">'. csrf_field();
      echo '<input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="'. $id .'"><button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i> حذف</button></form>';
    }
    echo '</td></tr>';
    render_vehicle_type_tree($byParent, $id, $level + 1);
  }
}

render_layout('أنواع السيارات','إدارة السيارات <span class="mx-1">/</span> أنواع السيارات', function() use ($rows, $byParent, $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="#createBrandModal"><i class="bi bi-plus-lg"></i> إضافة شركة سيارة</button>
  </div>

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

  <div class="row g-3 mb-3">
    <div class="col-md-4"><div class="card cardx p-3"><div class="text-secondary small">إجمالي العناصر</div><div class="fs-4 fw-bold"><?= count($rows) ?></div></div></div>
    <div class="col-md-4"><div class="card cardx p-3"><div class="text-secondary small">الشركات المصنعة</div><div class="fs-4 fw-bold"><?= count($byParent[0] ?? []) ?></div></div></div>
    <div class="col-md-4"><div class="card cardx p-3"><div class="text-secondary small">الفئات النهائية المتاحة للتسجيل</div><div class="fs-4 fw-bold"><?php $leafCount=0; foreach($rows as $r){ if((int)($r['children_count'] ?? 0)===0 && (int)($r['is_active'] ?? 1)===1) $leafCount++; } echo $leafCount; ?></div></div></div>
  </div>

  <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">المسار يظهر مثل: الشركة / الموديل / الفئة</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>الحالة</th>
            <th class="text-end">إجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php render_vehicle_type_tree($byParent); ?>
          <?php if(!$rows): ?><tr><td colspan="7" class="text-center text-secondary py-4">لا توجد بيانات بعد.</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade modal-erp" id="createBrandModal" 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">
      <input type="hidden" name="node_type" value="BRAND">
      <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">
        <label class="form-label">اسم الشركة</label>
        <input class="form-control" name="name" required placeholder="مثال: Mercedes-Benz أو Toyota">
      </div>
      <div class="modal-footer"><button class="btn btn-dark">حفظ</button><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إغلاق</button></div>
    </form>
  </div></div>
</div>

<div class="modal fade modal-erp" id="createChildModal" 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">
      <input type="hidden" name="parent_id" id="create_parent_id" value="">
      <input type="hidden" name="node_type" id="create_node_type" value="MODEL">
      <div class="modal-header"><h5 class="modal-title" id="createChildTitle">إضافة عنصر جديد</h5><button type="button" class="btn-close m-0" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <div class="alert alert-light border small mb-3">العنصر الأب: <span class="fw-semibold" id="create_parent_name">-</span></div>
        <label class="form-label">الاسم</label>
        <input class="form-control" name="name" required id="create_child_name" placeholder="">
      </div>
      <div class="modal-footer"><button class="btn btn-dark">حفظ</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">تعديل <?= h(vehicle_type_node_label((string)$editRow['node_type'])) ?></h5><button type="button" class="btn-close m-0" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <div class="alert alert-light border small mb-3">المسار الحالي: <span class="fw-semibold"><?= h($editRow['display_name'] ?: $editRow['name']) ?></span></div>
        <label class="form-label">الاسم</label>
        <input class="form-control" name="name" required value="<?= h($editRow['name']) ?>">
      </div>
      <div class="modal-footer"><button class="btn btn-dark">حفظ التعديلات</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; ?>

<script>
document.addEventListener('DOMContentLoaded', function(){
  document.querySelectorAll('.js-open-create-child').forEach(function(btn){
    btn.addEventListener('click', function(){
      const parentId = this.getAttribute('data-parent-id') || '';
      const nodeType = this.getAttribute('data-node-type') || 'MODEL';
      const parentName = this.getAttribute('data-parent-name') || '-';
      document.getElementById('create_parent_id').value = parentId;
      document.getElementById('create_node_type').value = nodeType;
      document.getElementById('create_parent_name').textContent = parentName;
      const label = nodeType === 'TRIM' ? 'فئة' : 'موديل';
      document.getElementById('createChildTitle').textContent = 'إضافة ' + label + ' جديد';
      document.getElementById('create_child_name').placeholder = nodeType === 'TRIM' ? 'مثال: E200 أو V250' : 'مثال: E-Class أو Corolla';
      if (window.bootstrap) new bootstrap.Modal(document.getElementById('createChildModal')).show();
    });
  });
});
</script>
<?php
});
