<?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);
fleet_ensure_schema($pdo);
csrf_bootstrap();

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

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

    if ($action === 'create' || $action === 'update') {
      $code = strtoupper(trim($_POST['code'] ?? ''));
      $name = trim($_POST['name'] ?? '');
      $revenueAccountId = (int)($_POST['revenue_account_id'] ?? 0) ?: null;
      $startNo = max(1, (int)($_POST['start_no'] ?? 1));
      $endNo = max($startNo, (int)($_POST['end_no'] ?? 1000));
      $currentNo = max(0, (int)($_POST['current_no'] ?? 0));
      $isActive = isset($_POST['is_active']) ? 1 : 0;

      if ($code === '' || $name === '') {
        throw new RuntimeException('اسم الأمر والكود مطلوبان.');
      }

      $chk = $pdo->prepare("SELECT COUNT(*) FROM vehicle_order_types WHERE company_id=? AND code=? AND id<>?");
      $chk->execute([$cid, $code, $id]);
      if ((int)$chk->fetchColumn() > 0) {
        throw new RuntimeException('كود الأمر مستخدم بالفعل.');
      }

      if ($action === 'create') {
        $pdo->prepare("INSERT INTO vehicle_order_types (company_id, code, name, revenue_account_id, start_no, end_no, current_no, is_system, is_active) VALUES (?,?,?,?,?,?,?,0,?)")
            ->execute([$cid, $code, $name, $revenueAccountId, $startNo, $endNo, $currentNo, $isActive]);
        $msg = 'تم إضافة أمر تشغيل جديد.';
      } else {
        $st = $pdo->prepare("SELECT is_system FROM vehicle_order_types WHERE id=? AND company_id=? LIMIT 1");
        $st->execute([$id, $cid]);
        $isSystem = (int)($st->fetchColumn() ?: 0);

        if ($isSystem === 1) {
          // الافتراضي: يسمح فقط بتعديل السريال والحساب والحالة والاسم
          $pdo->prepare("UPDATE vehicle_order_types SET name=?, revenue_account_id=?, start_no=?, end_no=?, current_no=?, is_active=?, updated_at=NOW() WHERE id=? AND company_id=?")
              ->execute([$name, $revenueAccountId, $startNo, $endNo, $currentNo, $isActive, $id, $cid]);
        } else {
          $pdo->prepare("UPDATE vehicle_order_types SET code=?, name=?, revenue_account_id=?, start_no=?, end_no=?, current_no=?, is_active=?, updated_at=NOW() WHERE id=? AND company_id=?")
              ->execute([$code, $name, $revenueAccountId, $startNo, $endNo, $currentNo, $isActive, $id, $cid]);
        }
        $msg = 'تم تعديل أمر التشغيل.';
      }
    }

    if ($action === 'delete') {
      $st = $pdo->prepare("SELECT is_system FROM vehicle_order_types WHERE id=? AND company_id=? LIMIT 1");
      $st->execute([$id, $cid]);
      $isSystem = (int)($st->fetchColumn() ?: 0);
      if ($isSystem === 1) {
        throw new RuntimeException('الأوامر الافتراضية غير قابلة للحذف.');
      }

      // عدم الحذف إذا كانت مرتبطة بجداول أخرى مستقبلاً
      if (fleet_table_exists($pdo, 'vehicle_contracts')) {
        $chk = $pdo->prepare("SELECT COUNT(*) FROM vehicle_contracts WHERE company_id=? AND order_type_id=?");
        $chk->execute([$cid, $id]);
        if ((int)$chk->fetchColumn() > 0) {
          throw new RuntimeException('لا يمكن حذف الأمر لأنه مرتبط ببيانات أخرى.');
        }
      }
      if (fleet_table_exists($pdo, 'vehicle_rental_contracts')) {
        $chk = $pdo->prepare("SELECT COUNT(*) FROM vehicle_rental_contracts WHERE company_id=? AND order_type_id=?");
        $chk->execute([$cid, $id]);
        if ((int)$chk->fetchColumn() > 0) {
          throw new RuntimeException('لا يمكن حذف الأمر لأنه مرتبط بعقود التأجير.');
        }
      }

      $pdo->prepare("DELETE FROM vehicle_order_types WHERE id=? AND company_id=?")->execute([$id, $cid]);
      $msg = 'تم حذف أمر التشغيل.';
    }
  } catch (Throwable $e) {
    $err = $e->getMessage();
  }
}

$rows = fleet_order_types($pdo, $cid);
$rev = $pdo->prepare("SELECT id, code, name, parent_id FROM accounts WHERE company_id=? AND type='REVENUE' AND is_active=1 ORDER BY CAST(code AS UNSIGNED), code, name");
$rev->execute([$cid]);
$allRevenueAccounts = $rev->fetchAll(PDO::FETCH_ASSOC);

/*
  نعرض فقط حسابات السيارات/النقل.
  المنطق:
  1) نلتقط الحسابات النهائية أو الأساسية الخاصة بالسيارات والنقل:
     4210 و 4220 وأي حساب اسمه مرتبط بالسيارات/النقل/الليموزين/التأجير/الانتقالات
  2) نضيف الآباء الخاصة بها فقط للحفاظ على شكل الشجرة
*/
$byIdAll = [];
foreach ($allRevenueAccounts as $a) {
  $byIdAll[(int)$a['id']] = $a;
}

$matches = [];
foreach ($allRevenueAccounts as $a) {
  $id = (int)$a['id'];
  $code = trim((string)($a['code'] ?? ''));
  $name = mb_strtolower(trim((string)($a['name'] ?? '')), 'UTF-8');

  $isFleetLeaf =
    in_array($code, ['4210', '4220'], true)
    || str_contains($name, 'سيار')
    || str_contains($name, 'ليموزين')
    || str_contains($name, 'انتقال')
    || str_contains($name, 'تأجير سيارات')
    || str_contains($name, 'نقل');

  if ($isFleetLeaf) {
    $matches[$id] = true;

    $pid = (int)($a['parent_id'] ?? 0);
    while ($pid > 0 && isset($byIdAll[$pid])) {
      $matches[$pid] = true;
      $pid = (int)($byIdAll[$pid]['parent_id'] ?? 0);
    }
  }
}

$revenueAccounts = [];
foreach ($allRevenueAccounts as $a) {
  $id = (int)$a['id'];
  if (!isset($matches[$id])) continue;

  $code = trim((string)($a['code'] ?? ''));
  $name = mb_strtolower(trim((string)($a['name'] ?? '')), 'UTF-8');

  $keep =
    in_array($code, ['4210', '4220', '4200', '4000'], true)
    || str_contains($name, 'سيار')
    || str_contains($name, 'ليموزين')
    || str_contains($name, 'انتقال')
    || str_contains($name, 'تأجير')
    || str_contains($name, 'نقل')
    || isset($matches[(int)($a['parent_id'] ?? 0)]);

  if ($keep) {
    $revenueAccounts[] = $a;
  }
}

$revByParent = [];
$revIds = [];
foreach ($revenueAccounts as $a) {
  $revIds[(int)$a['id']] = true;
}
foreach ($revenueAccounts as $a) {
  $pid = (!empty($a['parent_id']) && isset($revIds[(int)$a['parent_id']])) ? (int)$a['parent_id'] : 0;
  $revByParent[$pid][] = $a;
}
$revParents = [];
foreach ($revByParent as $pid => $items) {
  foreach ($items as $item) {
    if (!empty($revByParent[(int)$item['id']])) {
      $revParents[(int)$item['id']] = true;
    }
  }
}
function render_revenue_account_options(array $byParent, array $parentIds, int $parentId = 0, int $level = 0, ?int $selectedId = null): void {
  foreach (($byParent[$parentId] ?? []) as $a) {
    $id = (int)$a['id'];
    $prefix = $level > 0 ? str_repeat('— ', $level) : '';
    $label = trim($prefix . ($a['code'] ?? '') . ' - ' . ($a['name'] ?? ''));
    $selected = $selectedId === $id ? ' selected' : '';
    $disabled = isset($parentIds[$id]) ? ' disabled data-icon="bi bi-diagram-3"' : '';
    echo '<option value="' . $id . '"' . $selected . $disabled . '>' . h($label) . '</option>';
    render_revenue_account_options($byParent, $parentIds, $id, $level + 1, $selectedId);
  }
}

render_layout('سريال أوامر التشغيل', 'إدارة السيارات <span class="mx-1">/</span> سريال أوامر التشغيل', function() use ($rows, $revenueAccounts, $revByParent, $revParents, $msg, $err) { ?>
<style>
#orderTypeModal .bootstrap-select{width:100% !important;max-width:100% !important;}
#orderTypeModal .dropdown-menu{max-width:100% !important;}
#orderTypeModal .dropdown-menu.inner{max-height:none !important;}
#orderTypeModal .dropdown-menu li.disabled a{font-weight:700;color:#495057 !important;background:#f8f9fa;}
</style>
<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">4 أوامر افتراضية: انتقالات/ليموزين، تأجير، صيانة، توقف. ويقتصر اختيار حساب الإيراد على حسابات النقل والسيارات فقط مثل 4210 و4220 وفروعهما داخل شجرة الإيرادات.</div>
    </div>
    <button class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#orderTypeModal"><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; ?>

  <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): ?>
            <tr>
              <td><?= (int)$r['id'] ?></td>
              <td class="fw-semibold"><?= h($r['code']) ?></td>
              <td>
                <?= h($r['name']) ?>
                <?php if(!empty($r['is_system'])): ?>
                  <span class="badge bg-dark-subtle text-dark border me-1">افتراضي</span>
                <?php endif; ?>
              </td>
              <td><?= h(trim(($r['acc_code'] ?? '') . ' - ' . ($r['acc_name'] ?? ''))) ?: 'بدون عائد' ?></td>
              <td><?= (int)$r['start_no'] ?> - <?= (int)$r['end_no'] ?></td>
              <td><?= (int)$r['current_no'] ?></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-order-type"
                  data-id="<?= (int)$r['id'] ?>"
                  data-code="<?= h($r['code']) ?>"
                  data-name="<?= h($r['name']) ?>"
                  data-revenue="<?= (int)$r['revenue_account_id'] ?>"
                  data-start="<?= (int)$r['start_no'] ?>"
                  data-end="<?= (int)$r['end_no'] ?>"
                  data-current="<?= (int)$r['current_no'] ?>"
                  data-active="<?= (int)$r['is_active'] ?>"
                  data-system="<?= (int)$r['is_system'] ?>">
                  تعديل
                </button>

                <?php if(empty($r['is_system'])): ?>
                  <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>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade modal-erp" id="orderTypeModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post" id="orderTypeForm">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="create" id="ot_action">
        <input type="hidden" name="id" value="0" id="ot_id">
        <div class="modal-header">
          <h5 class="modal-title" id="ot_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-12">
              <label class="form-label">الكود</label>
              <input class="form-control" name="code" id="ot_code" required>
            </div>
            <div class="col-12">
              <label class="form-label">اسم الأمر</label>
              <input class="form-control" name="name" id="ot_name" required>
            </div>
            <div class="col-12">
              <label class="form-label">حساب الإيراد</label>
              <select name="revenue_account_id" id="ot_revenue" class="form-select selectpicker" data-live-search="true" data-size="false" data-width="100%">
                <option value="">بدون عائد</option>
                <?php render_revenue_account_options($revByParent, $revParents); ?>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label">من رقم</label>
              <input type="number" min="1" name="start_no" id="ot_start" class="form-control" value="1" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">إلى رقم</label>
              <input type="number" min="1" name="end_no" id="ot_end" class="form-control" value="1000" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">آخر رقم</label>
              <input type="number" min="0" name="current_no" id="ot_current" class="form-control" value="0" required>
            </div>
            <div class="col-12">
              <div class="form-check">
                <input class="form-check-input" type="checkbox" name="is_active" id="ot_active" checked>
                <label class="form-check-label" for="ot_active">مفعل</label>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer"><button class="btn btn-dark">حفظ</button></div>
      </form>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
  const modalEl = document.getElementById('orderTypeModal');
  const modal = bootstrap.Modal.getOrCreateInstance(modalEl);

  function setPickerValue(id, value){
    const el = document.getElementById(id);
    if (!el) return;
    el.value = value || '';
    if (window.jQuery && jQuery.fn && jQuery.fn.selectpicker) {
      jQuery(el).selectpicker('val', el.value);
      jQuery(el).selectpicker('refresh');
    }
  }

  function resetForm(){
    document.getElementById('orderTypeForm').reset();
    document.getElementById('ot_action').value = 'create';
    document.getElementById('ot_id').value = '0';
    document.getElementById('ot_title').textContent = 'إضافة أمر تشغيل';
    document.getElementById('ot_code').readOnly = false;
    document.getElementById('ot_start').value = '1';
    document.getElementById('ot_end').value = '1000';
    document.getElementById('ot_current').value = '0';
    document.getElementById('ot_active').checked = true;
    setPickerValue('ot_revenue', '');
  }

  modalEl.addEventListener('hidden.bs.modal', resetForm);

  document.querySelectorAll('.js-edit-order-type').forEach(function(btn){
    btn.addEventListener('click', function(){
      document.getElementById('ot_action').value = 'update';
      document.getElementById('ot_id').value = this.dataset.id || '0';
      document.getElementById('ot_title').textContent = 'تعديل أمر التشغيل';
      document.getElementById('ot_code').value = this.dataset.code || '';
      document.getElementById('ot_name').value = this.dataset.name || '';
      document.getElementById('ot_start').value = this.dataset.start || '1';
      document.getElementById('ot_end').value = this.dataset.end || '1000';
      document.getElementById('ot_current').value = this.dataset.current || '0';
      document.getElementById('ot_active').checked = (this.dataset.active || '0') === '1';
      document.getElementById('ot_code').readOnly = (this.dataset.system || '0') === '1';
      setPickerValue('ot_revenue', this.dataset.revenue || '');
      modal.show();
    });
  });

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