<?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' || $action==='update'){
      $requestNo = trim($_POST['request_no'] ?? '');
      if($requestNo==='') $requestNo = hotel_next_code($pdo, 'hotel_bookings', 'request_no', $cid, 'HB-');
      $checkin = trim($_POST['checkin_date'] ?? date('Y-m-d'));
      $checkout = trim($_POST['checkout_date'] ?? $checkin);
      $nights = max(1, (int)($_POST['nights'] ?? 1));
      if ($checkin && $checkout && $checkout >= $checkin) {
        $days = (strtotime($checkout) - strtotime($checkin)) / 86400;
        if ($days >= 1) $nights = (int)$days;
      }
      $salePrice = (float)($_POST['sale_price'] ?? 0);
      $costPrice = (float)($_POST['cost_price'] ?? 0);
      $totalSale = (float)($_POST['total_sale'] ?? 0);
      $totalCost = (float)($_POST['total_cost'] ?? 0);
      if ($totalSale <= 0) $totalSale = $salePrice * $nights;
      if ($totalCost <= 0) $totalCost = $costPrice * $nights;

      if($action==='create'){
        $pdo->prepare("INSERT INTO hotel_bookings (company_id, request_no, customer_id, hotel_id, room_id, request_date, checkin_date, checkout_date, nights, adults_count, children_count, meal_plan, booking_type, payment_type, status, cost_price, sale_price, total_cost, total_sale, voucher_notes, notes, created_by)
                       VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
            ->execute([$cid, $requestNo, (int)($_POST['customer_id'] ?: 0) ?: null, (int)$_POST['hotel_id'], (int)($_POST['room_id'] ?: 0) ?: null,
                       trim($_POST['request_date'] ?? date('Y-m-d')), $checkin, $checkout, $nights, (int)($_POST['adults_count'] ?? 1), (int)($_POST['children_count'] ?? 0),
                       trim($_POST['meal_plan'] ?? ''), $_POST['booking_type'] ?? 'ROOM', $_POST['payment_type'] ?? 'CREDIT', $_POST['status'] ?? 'PENDING',
                       $costPrice, $salePrice, $totalCost, $totalSale, trim($_POST['voucher_notes'] ?? ''), trim($_POST['notes'] ?? ''), $uid]);
        $msg = 'تم تسجيل طلب الحجز.';
      } else {
        $pdo->prepare("UPDATE hotel_bookings SET request_no=?, customer_id=?, hotel_id=?, room_id=?, request_date=?, checkin_date=?, checkout_date=?, nights=?, adults_count=?, children_count=?, meal_plan=?, booking_type=?, payment_type=?, status=?, cost_price=?, sale_price=?, total_cost=?, total_sale=?, voucher_notes=?, notes=?, updated_at=NOW() WHERE id=? AND company_id=?")
            ->execute([$requestNo, (int)($_POST['customer_id'] ?: 0) ?: null, (int)$_POST['hotel_id'], (int)($_POST['room_id'] ?: 0) ?: null, trim($_POST['request_date'] ?? date('Y-m-d')),
                       $checkin, $checkout, $nights, (int)($_POST['adults_count'] ?? 1), (int)($_POST['children_count'] ?? 0), trim($_POST['meal_plan'] ?? ''), $_POST['booking_type'] ?? 'ROOM',
                       $_POST['payment_type'] ?? 'CREDIT', $_POST['status'] ?? 'PENDING', $costPrice, $salePrice, $totalCost, $totalSale, trim($_POST['voucher_notes'] ?? ''), trim($_POST['notes'] ?? ''), (int)$_POST['id'], $cid]);
        $msg = 'تم تعديل طلب الحجز.';
      }
    } elseif($action==='delete'){
      $pdo->prepare("DELETE FROM hotel_bookings WHERE id=? AND company_id=?")->execute([(int)$_POST['id'], $cid]);
      $msg = 'تم حذف طلب الحجز.';
    } elseif($action==='post_journal'){
      hotel_create_booking_journal($pdo, $cid, (int)$_POST['id'], $uid);
      $msg = 'تم إنشاء قيد يومية للحجز.';
    } elseif($action==='unpost_journal'){
      hotel_unpost_booking_journal($pdo, $cid, (int)$_POST['id']);
      $msg = 'تم إلغاء قيد الحجز.';
    }
  }catch(Throwable $e){ $err=$e->getMessage(); }
}

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

$rooms = $pdo->prepare("SELECT r.id, r.hotel_id, CONCAT(h.name,' - ',r.room_no, IFNULL(CONCAT(' / ', r.room_name), '')) AS room_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=? AND r.status<>'INACTIVE' ORDER BY h.name, r.room_no");
$rooms->execute([$cid]);
$roomOptions = $rooms->fetchAll(PDO::FETCH_ASSOC);

$customers = $pdo->prepare("SELECT id, full_name FROM customers WHERE company_id=? ORDER BY full_name");
$customers->execute([$cid]);
$customerOptions = $customers->fetchAll(PDO::FETCH_ASSOC);

$list = $pdo->prepare("SELECT b.*, c.full_name AS customer_name, h.name AS hotel_name, r.room_no, r.room_name
                       FROM hotel_bookings b
                       LEFT JOIN customers c ON c.id=b.customer_id AND c.company_id=b.company_id
                       JOIN hotel_hotels h ON h.id=b.hotel_id AND h.company_id=b.company_id
                       LEFT JOIN hotel_rooms r ON r.id=b.room_id AND r.company_id=b.company_id
                       WHERE b.company_id=?
                       ORDER BY b.id DESC");
$list->execute([$cid]);
$rows = $list->fetchAll(PDO::FETCH_ASSOC);

render_layout('طلبات الحجز','حجوزات الفنادق <span class="mx-1">/</span> طلبات الحجز', function() use($rows,$hotelOptions,$roomOptions,$customerOptions,$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="#mBooking"><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><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 class="fw-semibold"><?= h($r['request_no']) ?></td>
            <td><?= h($r['customer_name'] ?: '-') ?></td>
            <td><?= h($r['hotel_name']) ?><div class="small text-secondary"><?= h(trim(($r['room_no'] ?: '').' '.($r['room_name'] ?: ''))) ?></div></td>
            <td class="small"><?= h($r['checkin_date']) ?> → <?= h($r['checkout_date']) ?><br><?= (int)$r['nights'] ?> ليلة</td>
            <td class="text-end"><?= nf($r['total_sale']) ?></td>
            <td><?= ($r['payment_type'] ?? 'CREDIT') === 'CASH' ? 'نقدي' : 'آجل' ?></td>
            <td><span class="badge <?= hotel_status_badge($r['status']) ?>"><?= h(hotel_status_label($r['status'])) ?></span></td>
            <td><?php if(!empty($r['posted_entry_id'])): ?><span class="badge bg-success-subtle text-success border">مرحّل</span><?php else: ?><span class="badge bg-warning-subtle text-warning border">Draft</span><?php endif; ?></td>
            <td class="text-end">
              <a class="btn btn-outline-dark btn-sm" target="_blank" href="<?= url('/hotel/voucher.php?id='.(int)$r['id']) ?>"><i class="bi bi-printer"></i></a>
              <button class="btn btn-outline-secondary btn-sm btnEdit"
                data-id="<?= (int)$r['id'] ?>" data-requestno="<?= h($r['request_no']) ?>" data-customer="<?= (int)$r['customer_id'] ?>"
                data-hotel="<?= (int)$r['hotel_id'] ?>" data-room="<?= (int)$r['room_id'] ?>" data-requestdate="<?= h($r['request_date']) ?>"
                data-checkin="<?= h($r['checkin_date']) ?>" data-checkout="<?= h($r['checkout_date']) ?>" data-nights="<?= (int)$r['nights'] ?>"
                data-adults="<?= (int)$r['adults_count'] ?>" data-children="<?= (int)$r['children_count'] ?>" data-meal="<?= h($r['meal_plan']) ?>"
                data-bookingtype="<?= h($r['booking_type']) ?>" data-payment="<?= h($r['payment_type']) ?>" data-status="<?= h($r['status']) ?>"
                data-cost="<?= h($r['cost_price']) ?>" data-price="<?= h($r['sale_price']) ?>" data-totalcost="<?= h($r['total_cost']) ?>" data-totalsale="<?= h($r['total_sale']) ?>"
                data-voucher="<?= h($r['voucher_notes']) ?>" data-notes="<?= h($r['notes']) ?>">
                <i class="bi bi-pencil"></i>
              </button>
              <?php if(empty($r['posted_entry_id']) && in_array($r['status'], ['CONFIRMED','CHECKED_IN','CHECKED_OUT'], true)): ?>
              <form method="post" class="d-inline" onsubmit="return confirm('إنشاء قيد يومية للحجز؟');">
                <?= csrf_field() ?><input type="hidden" name="action" value="post_journal"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                <button class="btn btn-outline-success btn-sm"><i class="bi bi-journal-check"></i></button>
              </form>
              <?php elseif(!empty($r['posted_entry_id'])): ?>
              <form method="post" class="d-inline" onsubmit="return confirm('إلغاء قيد الحجز؟');">
                <?= csrf_field() ?><input type="hidden" name="action" value="unpost_journal"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                <button class="btn btn-outline-warning btn-sm"><i class="bi bi-arrow-counterclockwise"></i></button>
              </form>
              <?php endif; ?>
              <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="mBooking" tabindex="-1">
  <div class="modal-dialog modal-xl"><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="request_no" class="form-control" placeholder="تلقائي"></div>
          <div class="col-md-3"><label class="form-label">تاريخ الطلب</label><input type="date" name="request_date" class="form-control" value="<?= date('Y-m-d') ?>"></div>
          <div class="col-md-3"><label class="form-label">العميل</label><select name="customer_id" class="form-select"><option value="">— بدون —</option><?php foreach($customerOptions as $c): ?><option value="<?= (int)$c['id'] ?>"><?= h($c['full_name']) ?></option><?php endforeach; ?></select></div>
          <div class="col-md-3"><label class="form-label">نوع الحجز</label><select name="booking_type" class="form-select"><option value="ROOM">حجز غرفة</option><option value="PACKAGE">باكدج</option></select></div>
          <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><select name="room_id" class="form-select"><option value="">— بدون —</option><?php foreach($roomOptions as $r): ?><option value="<?= (int)$r['id'] ?>" data-hotel="<?= (int)$r['hotel_id'] ?>"><?= h($r['room_name']) ?></option><?php endforeach; ?></select></div>
          <div class="col-md-4"><label class="form-label">الوجبات</label><input name="meal_plan" class="form-control" placeholder="BB / HB / AI"></div>
          <div class="col-md-3"><label class="form-label">الدخول</label><input type="date" name="checkin_date" class="form-control" value="<?= date('Y-m-d') ?>"></div>
          <div class="col-md-3"><label class="form-label">الخروج</label><input type="date" name="checkout_date" class="form-control" value="<?= date('Y-m-d', strtotime('+1 day')) ?>"></div>
          <div class="col-md-2"><label class="form-label">الليالي</label><input type="number" name="nights" class="form-control" value="1"></div>
          <div class="col-md-2"><label class="form-label">بالغين</label><input type="number" name="adults_count" class="form-control" value="1"></div>
          <div class="col-md-2"><label class="form-label">أطفال</label><input type="number" name="children_count" class="form-control" value="0"></div>
          <div class="col-md-3"><label class="form-label">تكلفة الليلة</label><input type="number" step="0.01" name="cost_price" class="form-control" value="0"></div>
          <div class="col-md-3"><label class="form-label">سعر الليلة</label><input type="number" step="0.01" name="sale_price" class="form-control" value="0"></div>
          <div class="col-md-3"><label class="form-label">إجمالي التكلفة</label><input type="number" step="0.01" name="total_cost" class="form-control" value="0"></div>
          <div class="col-md-3"><label class="form-label">إجمالي البيع</label><input type="number" step="0.01" name="total_sale" class="form-control" value="0"></div>
          <div class="col-md-4"><label class="form-label">السداد</label><select name="payment_type" class="form-select"><option value="CREDIT">آجل</option><option value="CASH">نقدي</option></select></div>
          <div class="col-md-4"><label class="form-label">الحالة</label><select name="status" class="form-select"><option value="PENDING">طلب جديد</option><option value="PRICED">تم التسعير</option><option value="CONFIRMED">مؤكد</option><option value="CHECKED_IN">تم الدخول</option><option value="CHECKED_OUT">تم الخروج</option><option value="CANCELLED">ملغي</option></select></div>
          <div class="col-md-4"><label class="form-label">ملاحظات الفاوتشر</label><input name="voucher_notes" 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>
function filterRoomsByHotel(){
  const modal = document.getElementById('mBooking');
  const hotelId = modal.querySelector('[name=hotel_id]').value;
  modal.querySelectorAll('[name=room_id] option').forEach(function(op){
    if (!op.value) { op.hidden = false; return; }
    op.hidden = op.dataset.hotel && op.dataset.hotel !== hotelId;
  });
}
document.querySelector('#mBooking [name=hotel_id]').addEventListener('change', filterRoomsByHotel);
document.querySelectorAll('.btnEdit').forEach(function(btn){
  btn.addEventListener('click', function(){
    const m = document.getElementById('mBooking');
    m.querySelector('.modal-title').textContent = 'تعديل طلب حجز';
    m.querySelector('[name=action]').value = 'update';
    ['id','requestno','customer','hotel','room','requestdate','checkin','checkout','nights','adults','children','meal','bookingtype','payment','status','cost','price','totalcost','totalsale','voucher','notes']
      .forEach(function(key){
        const fieldMap = {
          id:'id', requestno:'request_no', customer:'customer_id', hotel:'hotel_id', room:'room_id', requestdate:'request_date', checkin:'checkin_date',
          checkout:'checkout_date', nights:'nights', adults:'adults_count', children:'children_count', meal:'meal_plan', bookingtype:'booking_type',
          payment:'payment_type', status:'status', cost:'cost_price', price:'sale_price', totalcost:'total_cost', totalsale:'total_sale', voucher:'voucher_notes', notes:'notes'
        };
        m.querySelector('[name="'+fieldMap[key]+'"]').value = btn.dataset[key] || '';
      });
    filterRoomsByHotel();
    bootstrap.Modal.getOrCreateInstance(m).show();
  });
});
document.getElementById('mBooking').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 = '';
  this.querySelector('[name=request_date]').value = '<?= date('Y-m-d') ?>';
  this.querySelector('[name=checkin_date]').value = '<?= date('Y-m-d') ?>';
  this.querySelector('[name=checkout_date]').value = '<?= date('Y-m-d', strtotime('+1 day')) ?>';
  filterRoomsByHotel();
});
filterRoomsByHotel();
</script>
<?php }); ?>
