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

$msg = ''; $err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $action = $_POST['action'] ?? '';
  try {
    if ($action === 'create') {
      $pdo->prepare("INSERT INTO hotel_hotels (company_id, code, name, ownership_type, city, address, contact_person, phone, email, status, notes, created_by)
                     VALUES (?,?,?,?,?,?,?,?,?,?,?,?)")
          ->execute([$cid, trim($_POST['code'] ?? ''), trim($_POST['name'] ?? ''), $_POST['ownership_type'] ?? 'THIRD_PARTY',
                     trim($_POST['city'] ?? ''), trim($_POST['address'] ?? ''), trim($_POST['contact_person'] ?? ''),
                     trim($_POST['phone'] ?? ''), trim($_POST['email'] ?? ''), $_POST['status'] ?? 'ACTIVE', trim($_POST['notes'] ?? ''), $uid]);
      $msg = 'تمت إضافة الفندق بنجاح.';
    } elseif ($action === 'update') {
      $pdo->prepare("UPDATE hotel_hotels SET code=?, name=?, ownership_type=?, city=?, address=?, contact_person=?, phone=?, email=?, status=?, notes=? WHERE id=? AND company_id=?")
          ->execute([trim($_POST['code'] ?? ''), trim($_POST['name'] ?? ''), $_POST['ownership_type'] ?? 'THIRD_PARTY',
                     trim($_POST['city'] ?? ''), trim($_POST['address'] ?? ''), trim($_POST['contact_person'] ?? ''),
                     trim($_POST['phone'] ?? ''), trim($_POST['email'] ?? ''), $_POST['status'] ?? 'ACTIVE', trim($_POST['notes'] ?? ''), (int)$_POST['id'], $cid]);
      $msg = 'تم تعديل الفندق بنجاح.';
    } elseif ($action === 'delete') {
      $hotelId = (int)($_POST['id'] ?? 0);
      $st = $pdo->prepare("SELECT COUNT(*) FROM hotel_rooms WHERE company_id=? AND hotel_id=?");
      $st->execute([$cid, $hotelId]);
      if ((int)$st->fetchColumn() > 0) throw new RuntimeException('لا يمكن حذف الفندق قبل حذف الغرف التابعة له.');
      $st = $pdo->prepare("SELECT COUNT(*) FROM hotel_bookings WHERE company_id=? AND hotel_id=?");
      $st->execute([$cid, $hotelId]);
      if ((int)$st->fetchColumn() > 0) throw new RuntimeException('لا يمكن حذف الفندق لوجود طلبات حجز مرتبطة به.');
      $pdo->prepare("DELETE FROM hotel_hotels WHERE id=? AND company_id=?")->execute([$hotelId, $cid]);
      $msg = 'تم حذف الفندق.';
    }
  } catch (Throwable $e) {
    $err = $e->getMessage();
  }
}

$st = $pdo->prepare("SELECT h.*,
  (SELECT COUNT(*) FROM hotel_rooms r WHERE r.hotel_id=h.id AND r.company_id=h.company_id) room_count,
  (SELECT COUNT(*) FROM hotel_bookings b WHERE b.hotel_id=h.id AND b.company_id=h.company_id) booking_count
  FROM hotel_hotels h WHERE h.company_id=? ORDER BY h.id DESC");
$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="#mHotel"><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>الحجوزات</th><th>الحالة</th><th class="text-end">إجراءات</th>
          </tr>
        </thead>
        <tbody>
        <?php if(!$rows): ?><tr><td colspan="10" class="text-center text-secondary py-4">لا توجد فنادق مسجلة.</td></tr><?php endif; ?>
        <?php foreach($rows as $r): ?>
          <tr>
            <td><?= (int)$r['id'] ?></td>
            <td><?= h($r['code'] ?: '-') ?></td>
            <td class="fw-semibold"><?= h($r['name']) ?></td>
            <td><?= h(hotel_ownership_label($r['ownership_type'])) ?></td>
            <td><?= h($r['city']) ?></td>
            <td class="small"><?= h($r['contact_person']) ?><br><?= h($r['phone']) ?></td>
            <td><?= (int)$r['room_count'] ?></td>
            <td><?= (int)$r['booking_count'] ?></td>
            <td><span class="badge bg-light text-dark border"><?= $r['status'] === 'ACTIVE' ? 'نشط' : 'موقوف' ?></span></td>
            <td class="text-end">
              <button class="btn btn-outline-secondary btn-sm btnEdit"
                data-id="<?= (int)$r['id'] ?>"
                data-code="<?= h($r['code']) ?>"
                data-name="<?= h($r['name']) ?>"
                data-ownership="<?= h($r['ownership_type']) ?>"
                data-city="<?= h($r['city']) ?>"
                data-address="<?= h($r['address']) ?>"
                data-contact="<?= h($r['contact_person']) ?>"
                data-phone="<?= h($r['phone']) ?>"
                data-email="<?= h($r['email']) ?>"
                data-status="<?= h($r['status']) ?>"
                data-notes="<?= h($r['notes']) ?>">
                <i class="bi bi-pencil"></i>
              </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"><i class="bi bi-trash"></i></button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade modal-erp" id="mHotel" tabindex="-1">
  <div class="modal-dialog modal-lg"><div class="modal-content">
    <form method="post">
      <?= csrf_field() ?>
      <input type="hidden" name="action" value="create">
      <input type="hidden" name="id" value="">
      <div class="modal-header"><h5 class="modal-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-3"><label class="form-label">الكود</label><input name="code" class="form-control"></div>
          <div class="col-md-5"><label class="form-label">اسم الفندق</label><input name="name" class="form-control" required></div>
          <div class="col-md-4"><label class="form-label">نوع الملكية</label><select name="ownership_type" class="form-select"><option value="OWNED">مملوكة</option><option value="THIRD_PARTY">غير مملوكة</option></select></div>
          <div class="col-md-4"><label class="form-label">المدينة</label><input name="city" class="form-control"></div>
          <div class="col-md-4"><label class="form-label">الشخص المسؤول</label><input name="contact_person" class="form-control"></div>
          <div class="col-md-4"><label class="form-label">الهاتف</label><input name="phone" class="form-control"></div>
          <div class="col-md-6"><label class="form-label">البريد</label><input name="email" class="form-control"></div>
          <div class="col-md-6"><label class="form-label">الحالة</label><select name="status" class="form-select"><option value="ACTIVE">نشط</option><option value="INACTIVE">موقوف</option></select></div>
          <div class="col-12"><label class="form-label">العنوان</label><input name="address" class="form-control"></div>
          <div class="col-12"><label class="form-label">ملاحظات</label><textarea name="notes" class="form-control" rows="3"></textarea></div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-dark">حفظ</button></div>
    </form>
  </div></div>
</div>

<script>
document.querySelectorAll('.btnEdit').forEach(function(btn){
  btn.addEventListener('click', function(){
    const modal = document.getElementById('mHotel');
    modal.querySelector('.modal-title').textContent = 'تعديل فندق';
    modal.querySelector('[name=action]').value = 'update';
    modal.querySelector('[name=id]').value = this.dataset.id || '';
    modal.querySelector('[name=code]').value = this.dataset.code || '';
    modal.querySelector('[name=name]').value = this.dataset.name || '';
    modal.querySelector('[name=ownership_type]').value = this.dataset.ownership || 'THIRD_PARTY';
    modal.querySelector('[name=city]').value = this.dataset.city || '';
    modal.querySelector('[name=address]').value = this.dataset.address || '';
    modal.querySelector('[name=contact_person]').value = this.dataset.contact || '';
    modal.querySelector('[name=phone]').value = this.dataset.phone || '';
    modal.querySelector('[name=email]').value = this.dataset.email || '';
    modal.querySelector('[name=status]').value = this.dataset.status || 'ACTIVE';
    modal.querySelector('[name=notes]').value = this.dataset.notes || '';
    bootstrap.Modal.getOrCreateInstance(modal).show();
  });
});
document.getElementById('mHotel').addEventListener('hidden.bs.modal', function(){
  const f = this.querySelector('form');
  f.reset();
  this.querySelector('.modal-title').textContent = 'إضافة فندق';
  this.querySelector('[name=action]').value = 'create';
  this.querySelector('[name=id]').value = '';
});
</script>
<?php }); ?>
