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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  try {
    $action = $_POST['action'] ?? '';
    $id = (int)($_POST['id'] ?? 0);
    if ($action === 'save') {
      $name = trim($_POST['name'] ?? '');
      $isPickup = isset($_POST['is_pickup']) ? 1 : 0;
      $isDropoff = isset($_POST['is_dropoff']) ? 1 : 0;
      $isActive = isset($_POST['is_active']) ? 1 : 0;
      if ($name === '') throw new RuntimeException('اسم المنطقة مطلوب.');
      if ($id > 0) {
        $pdo->prepare("UPDATE fleet_locations SET name=?, is_pickup=?, is_dropoff=?, is_active=?, updated_at=NOW() WHERE id=? AND company_id=?")
            ->execute([$name,$isPickup,$isDropoff,$isActive,$id,$cid]);
        $msg = 'تم تعديل المنطقة.';
      } else {
        $pdo->prepare("INSERT INTO fleet_locations (company_id,name,is_pickup,is_dropoff,is_active,created_by) VALUES (?,?,?,?,?,?)")
            ->execute([$cid,$name,$isPickup,$isDropoff,$isActive,$uid]);
        $msg = 'تم إضافة المنطقة.';
      }
    }
    if ($action === 'delete') {
      $pdo->prepare("DELETE FROM fleet_locations WHERE id=? AND company_id=?")->execute([$id,$cid]);
      $msg = 'تم حذف المنطقة.';
    }
  } catch (Throwable $e) { $err = $e->getMessage(); }
}

$st = $pdo->prepare("SELECT * FROM fleet_locations WHERE company_id=? ORDER BY name");
$st->execute([$cid]);
$rows = $st->fetchAll(PDO::FETCH_ASSOC);

render_layout('مناطق الليموزين','إدارة السيارات <span class="mx-1">/</span> مناطق الليموزين', function() use($rows,$msg,$err){ ?>
<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="#locationModal"><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 class="text-end">الإجراءات</th></tr></thead>
      <tbody>
      <?php if(!$rows): ?><tr><td colspan="6" 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['name']) ?></td>
          <td><?= !empty($r['is_pickup']) ? 'نعم' : '—' ?></td>
          <td><?= !empty($r['is_dropoff']) ? 'نعم' : '—' ?></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-name="<?= h($r['name']) ?>" data-pickup="<?= (int)$r['is_pickup'] ?>" data-dropoff="<?= (int)$r['is_dropoff'] ?>" data-active="<?= (int)$r['is_active'] ?>">تعديل</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="locationModal" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <form method="post" id="locationForm">
      <?= csrf_field() ?><input type="hidden" name="action" value="save"><input type="hidden" name="id" id="loc_id" value="0">
      <div class="modal-header"><h5 class="modal-title" id="loc_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="name" id="loc_name" required></div>
          <div class="col-12 d-flex flex-column gap-2">
            <div class="form-check"><input class="form-check-input" type="checkbox" name="is_pickup" id="loc_pickup" checked><label class="form-check-label" for="loc_pickup">مكان تحرك</label></div>
            <div class="form-check"><input class="form-check-input" type="checkbox" name="is_dropoff" id="loc_dropoff" checked><label class="form-check-label" for="loc_dropoff">مكان وجهة</label></div>
            <div class="form-check"><input class="form-check-input" type="checkbox" name="is_active" id="loc_active" checked><label class="form-check-label" for="loc_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('locationModal');
  const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
  function resetForm(){
    document.getElementById('locationForm').reset();
    document.getElementById('loc_id').value = '0';
    document.getElementById('loc_title').textContent = 'إضافة منطقة';
    document.getElementById('loc_pickup').checked = true;
    document.getElementById('loc_dropoff').checked = true;
    document.getElementById('loc_active').checked = true;
  }
  modalEl.addEventListener('hidden.bs.modal', resetForm);
  document.querySelectorAll('.js-edit').forEach(function(btn){
    btn.addEventListener('click', function(){
      document.getElementById('loc_id').value = this.dataset.id || '0';
      document.getElementById('loc_title').textContent = 'تعديل منطقة';
      document.getElementById('loc_name').value = this.dataset.name || '';
      document.getElementById('loc_pickup').checked = (this.dataset.pickup || '0') === '1';
      document.getElementById('loc_dropoff').checked = (this.dataset.dropoff || '0') === '1';
      document.getElementById('loc_active').checked = (this.dataset.active || '0') === '1';
      modal.show();
    });
  });
  resetForm();
});
</script>
<?php }); ?>
