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

$from = $_GET['from'] ?? date('Y-m-01');
$to = $_GET['to'] ?? date('Y-m-d');
$status = $_GET['status'] ?? '';
$hotelId = (int)($_GET['hotel_id'] ?? 0);

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

$where = " WHERE b.company_id=? AND b.request_date BETWEEN ? AND ? ";
$params = [$cid, $from, $to];
if($status !== ''){ $where .= " AND b.status=? "; $params[] = $status; }
if($hotelId > 0){ $where .= " AND b.hotel_id=? "; $params[] = $hotelId; }

$sum = $pdo->prepare("SELECT COUNT(*) cnt, IFNULL(SUM(total_sale),0) sale_total, IFNULL(SUM(total_cost),0) cost_total
                      FROM hotel_bookings b {$where}");
$sum->execute($params);
$summary = $sum->fetch(PDO::FETCH_ASSOC) ?: ['cnt'=>0,'sale_total'=>0,'cost_total'=>0];

$list = $pdo->prepare("SELECT b.*, c.full_name customer_name, h.name hotel_name, r.room_no
                       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}
                       ORDER BY b.request_date DESC, b.id DESC");
$list->execute($params);
$rows = $list->fetchAll(PDO::FETCH_ASSOC);

$receipts = $pdo->prepare("SELECT COUNT(*) cnt, IFNULL(SUM(amount),0) total_amount FROM hotel_receipts WHERE company_id=? AND receipt_date BETWEEN ? AND ?");
$receipts->execute([$cid, $from, $to]);
$rcp = $receipts->fetch(PDO::FETCH_ASSOC) ?: ['cnt'=>0,'total_amount'=>0];

render_layout('تقارير الحجوزات','حجوزات الفنادق <span class="mx-1">/</span> التقارير', function() use($from,$to,$status,$hotelId,$hotelOptions,$summary,$rows,$rcp){ ?>
<div class="container-fluid mt-3">
  <div class="fw-bold fs-4">تقارير حجوزات الفنادق</div>
  <div class="text-secondary small">تقارير الطلبات والتسعير والتأكيد والتحصيل ضمن الفترة المختارة.</div>

  <div class="card cardx mt-3 p-3">
    <form method="get" class="row g-3 align-items-end">
      <div class="col-md-3"><label class="form-label">من</label><input type="date" name="from" class="form-control" value="<?= h($from) ?>"></div>
      <div class="col-md-3"><label class="form-label">إلى</label><input type="date" name="to" class="form-control" value="<?= h($to) ?>"></div>
      <div class="col-md-3"><label class="form-label">الفندق</label><select name="hotel_id" class="form-select"><option value="0">الكل</option><?php foreach($hotelOptions as $h): ?><option value="<?= (int)$h['id'] ?>" <?= $hotelId===(int)$h['id']?'selected':'' ?>><?= h($h['name']) ?></option><?php endforeach; ?></select></div>
      <div class="col-md-3"><label class="form-label">الحالة</label><select name="status" class="form-select"><option value="">الكل</option><option value="PENDING" <?= $status==='PENDING'?'selected':'' ?>>طلب جديد</option><option value="PRICED" <?= $status==='PRICED'?'selected':'' ?>>تم التسعير</option><option value="CONFIRMED" <?= $status==='CONFIRMED'?'selected':'' ?>>مؤكد</option><option value="CHECKED_IN" <?= $status==='CHECKED_IN'?'selected':'' ?>>تم الدخول</option><option value="CHECKED_OUT" <?= $status==='CHECKED_OUT'?'selected':'' ?>>تم الخروج</option><option value="CANCELLED" <?= $status==='CANCELLED'?'selected':'' ?>>ملغي</option></select></div>
      <div class="col-md-2"><button class="btn btn-dark w-100">عرض</button></div>
    </form>
  </div>

  <div class="row g-3 mt-1">
    <div class="col-md-3"><div class="card cardx p-3 h-100"><div class="text-secondary small">عدد الحجوزات</div><div class="fs-3 fw-bold mt-1"><?= (int)$summary['cnt'] ?></div></div></div>
    <div class="col-md-3"><div class="card cardx p-3 h-100"><div class="text-secondary small">إجمالي البيع</div><div class="fs-3 fw-bold mt-1"><?= nf($summary['sale_total']) ?></div></div></div>
    <div class="col-md-3"><div class="card cardx p-3 h-100"><div class="text-secondary small">إجمالي التكلفة</div><div class="fs-3 fw-bold mt-1"><?= nf($summary['cost_total']) ?></div></div></div>
    <div class="col-md-3"><div class="card cardx p-3 h-100"><div class="text-secondary small">إجمالي التحصيلات</div><div class="fs-3 fw-bold mt-1"><?= nf($rcp['total_amount']) ?></div><div class="small text-secondary"><?= (int)$rcp['cnt'] ?> عملية</div></div></div>
  </div>

  <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>الحالة</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 class="fw-semibold"><?= h($r['request_no']) ?></td>
            <td><?= h($r['customer_name'] ?: '-') ?></td>
            <td><?= h($r['hotel_name']) ?></td>
            <td><?= h($r['room_no'] ?: '-') ?></td>
            <td><?= h($r['checkin_date']) ?></td>
            <td><?= h($r['checkout_date']) ?></td>
            <td class="text-end"><?= nf($r['total_sale']) ?></td>
            <td class="text-end"><?= nf($r['total_cost']) ?></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>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php }); ?>
