<?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_rooms (company_id, hotel_id, room_no, room_name, room_type, ownership_type, capacity_adults, capacity_children, base_cost, base_price, status, notes, created_by)
                     VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)")
          ->execute([$cid, (int)$_POST['hotel_id'], trim($_POST['room_no']), trim($_POST['room_name']), trim($_POST['room_type']),
                     $_POST['ownership_type'] ?? 'THIRD_PARTY', (int)($_POST['capacity_adults'] ?? 2), (int)($_POST['capacity_children'] ?? 0),
                     (float)($_POST['base_cost'] ?? 0), (float)($_POST['base_price'] ?? 0), $_POST['status'] ?? 'AVAILABLE', trim($_POST['notes'] ?? ''), $uid]);
      $msg='تمت إضافة الغرفة.';
    } elseif($action==='update'){
      $pdo->prepare("UPDATE hotel_rooms SET hotel_id=?, room_no=?, room_name=?, room_type=?, ownership_type=?, capacity_adults=?, capacity_children=?, base_cost=?, base_price=?, status=?, notes=? WHERE id=? AND company_id=?")
          ->execute([(int)$_POST['hotel_id'], trim($_POST['room_no']), trim($_POST['room_name']), trim($_POST['room_type']),
                     $_POST['ownership_type'] ?? 'THIRD_PARTY', (int)($_POST['capacity_adults'] ?? 2), (int)($_POST['capacity_children'] ?? 0),
                     (float)($_POST['base_cost'] ?? 0), (float)($_POST['base_price'] ?? 0), $_POST['status'] ?? 'AVAILABLE', trim($_POST['notes'] ?? ''), (int)$_POST['id'], $cid]);
      $msg='تم تعديل الغرفة.';
    } elseif($action==='delete'){
      $roomId = (int)$_POST['id'];
      $st = $pdo->prepare("SELECT COUNT(*) FROM hotel_bookings WHERE room_id=? AND company_id=?");
      $st->execute([$roomId, $cid]);
      if((int)$st->fetchColumn() > 0) throw new RuntimeException('لا يمكن حذف الغرفة لوجود حجوزات مرتبطة بها.');
      $pdo->prepare("DELETE FROM hotel_rooms WHERE id=? AND company_id=?")->execute([$roomId, $cid]);
      $msg='تم حذف الغرفة.';
    }
  }catch(Throwable $e){ $err=$e->getMessage(); }
}

$hotels = $pdo->prepare("SELECT id, name FROM hotel_hotels WHERE company_id=? ORDER BY name");
$hotels->execute([$cid]);
$hotelOptions = $hotels->fetchAll(PDO::FETCH_ASSOC);

$rows = $pdo->prepare("SELECT r.*, h.name AS hotel_name
                       FROM hotel_rooms r
                       JOIN hotel_hotels h ON h.id=r.hotel_id AND h.company_id=r.company_id
                       WHERE r.company_id=? ORDER BY r.id DESC");
$rows->execute([$cid]);
$list = $rows->fetchAll(PDO::FETCH_ASSOC);

render_layout('تسجيل الغرف','حجوزات الفنادق <span class="mx-1">/</span> تسجيل الغرف', function() use($list,$hotelOptions,$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="#mRoom"><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 class="text-end">تكلفة</th><th class="text-end">سعر بيع</th><th>الحالة</th><th class="text-end">إجراءات</th></tr></thead>
        <tbody>
          <?php if(!$list): ?><tr><td colspan="10" class="text-center text-secondary py-4">لا توجد غرف مسجلة.</td></tr><?php endif; ?>
          <?php foreach($list as $r): ?>
          <tr>
            <td><?= (int)$r['id'] ?></td>
            <td><?= h($r['hotel_name']) ?></td>
            <td class="fw-semibold"><?= h(trim(($r['room_no'] ?: '').' '.($r['room_name'] ?: ''))) ?></td>
            <td><?= h($r['room_type']) ?></td>
            <td><?= h(hotel_ownership_label($r['ownership_type'])) ?></td>
            <td><?= (int)$r['capacity_adults'] ?> / <?= (int)$r['capacity_children'] ?></td>
            <td class="text-end"><?= nf($r['base_cost']) ?></td>
            <td class="text-end"><?= nf($r['base_price']) ?></td>
            <td><span class="badge bg-light text-dark border"><?= h(hotel_room_status_label($r['status'])) ?></span></td>
            <td class="text-end">
              <button class="btn btn-outline-secondary btn-sm btnEdit"
                data-id="<?= (int)$r['id'] ?>" data-hotel="<?= (int)$r['hotel_id'] ?>" data-roomno="<?= h($r['room_no']) ?>"
                data-roomname="<?= h($r['room_name']) ?>" data-roomtype="<?= h($r['room_type']) ?>" data-ownership="<?= h($r['ownership_type']) ?>"
                data-adults="<?= (int)$r['capacity_adults'] ?>" data-children="<?= (int)$r['capacity_children'] ?>"
                data-cost="<?= h($r['base_cost']) ?>" data-price="<?= h($r['base_price']) ?>" 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="mRoom" 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-4"><label class="form-label">الفندق</label><select name="hotel_id" class="form-select" required><?php foreach($hotelOptions as $h): ?><option value="<?= (int)$h['id'] ?>"><?= h($h['name']) ?></option><?php endforeach; ?></select></div>
          <div class="col-md-4"><label class="form-label">رقم الغرفة</label><input name="room_no" class="form-control" required></div>
          <div class="col-md-4"><label class="form-label">اسم الغرفة</label><input name="room_name" class="form-control"></div>
          <div class="col-md-4"><label class="form-label">نوع الغرفة</label><input name="room_type" class="form-control" placeholder="Double / Suite"></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><select name="status" class="form-select"><option value="AVAILABLE">متاحة</option><option value="OUT_OF_SERVICE">خارج الخدمة</option><option value="INACTIVE">موقوفة</option></select></div>
          <div class="col-md-3"><label class="form-label">بالغين</label><input type="number" name="capacity_adults" class="form-control" value="2"></div>
          <div class="col-md-3"><label class="form-label">أطفال</label><input type="number" name="capacity_children" class="form-control" value="0"></div>
          <div class="col-md-3"><label class="form-label">تكلفة الأساس</label><input type="number" step="0.01" name="base_cost" class="form-control" value="0"></div>
          <div class="col-md-3"><label class="form-label">سعر البيع</label><input type="number" step="0.01" name="base_price" class="form-control" value="0"></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 m = document.getElementById('mRoom');
    m.querySelector('.modal-title').textContent = 'تعديل غرفة';
    m.querySelector('[name=action]').value = 'update';
    m.querySelector('[name=id]').value = this.dataset.id || '';
    m.querySelector('[name=hotel_id]').value = this.dataset.hotel || '';
    m.querySelector('[name=room_no]').value = this.dataset.roomno || '';
    m.querySelector('[name=room_name]').value = this.dataset.roomname || '';
    m.querySelector('[name=room_type]').value = this.dataset.roomtype || '';
    m.querySelector('[name=ownership_type]').value = this.dataset.ownership || 'THIRD_PARTY';
    m.querySelector('[name=capacity_adults]').value = this.dataset.adults || 2;
    m.querySelector('[name=capacity_children]').value = this.dataset.children || 0;
    m.querySelector('[name=base_cost]').value = this.dataset.cost || 0;
    m.querySelector('[name=base_price]').value = this.dataset.price || 0;
    m.querySelector('[name=status]').value = this.dataset.status || 'AVAILABLE';
    m.querySelector('[name=notes]').value = this.dataset.notes || '';
    bootstrap.Modal.getOrCreateInstance(m).show();
  });
});
document.getElementById('mRoom').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 }); ?>
