<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/audit.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();

$acc = hotel_default_accounts($pdo, $cid);
$msg=''; $err='';

$cashAccounts = $pdo->prepare("SELECT id, code, name FROM accounts WHERE company_id=? AND is_active=1 AND (is_cash=1 OR code IN ('1110','1120')) ORDER BY code");
$cashAccounts->execute([$cid]);
$cashOptions = $cashAccounts->fetchAll(PDO::FETCH_ASSOC);

$bookings = $pdo->prepare("SELECT b.id, b.request_no, c.full_name
                           FROM hotel_bookings b
                           LEFT JOIN customers c ON c.id=b.customer_id AND c.company_id=b.company_id
                           WHERE b.company_id=? ORDER BY b.id DESC");
$bookings->execute([$cid]);
$bookingOptions = $bookings->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);

$bookingNameById = [];
foreach ($bookingOptions as $bx) { $bookingNameById[(int)$bx['id']] = trim(($bx['request_no'] ?? '') . ' - ' . ($bx['full_name'] ?? '')); }
$customerNameById = [];
foreach ($customerOptions as $cx) { $customerNameById[(int)$cx['id']] = (string)($cx['full_name'] ?? ''); }


if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $action = $_POST['action'] ?? '';
  try{
    if($action==='create' || $action==='update'){
      $receiptNo = trim($_POST['receipt_no'] ?? '');
      if($receiptNo==='') $receiptNo = hotel_next_code($pdo, 'hotel_receipts', 'receipt_no', $cid, 'HR-');
      $bookingId = (int)($_POST['booking_id'] ?: 0) ?: null;
      $customerId = (int)($_POST['customer_id'] ?: 0) ?: null;
      if($bookingId && !$customerId){
        $st = $pdo->prepare("SELECT customer_id FROM hotel_bookings WHERE id=? AND company_id=?");
        $st->execute([$bookingId, $cid]);
        $customerId = (int)($st->fetchColumn() ?: 0) ?: null;
      }
      if($action==='create'){
        $receiptDate = trim($_POST['receipt_date'] ?? date('Y-m-d'));
        $cashAccountId = (int)($_POST['cash_account_id'] ?: $acc['cash_id']);
        $amount = (float)($_POST['amount'] ?? 0);
        $paymentMethod = $_POST['payment_method'] ?? 'CASH';
        $notes = trim($_POST['notes'] ?? '');
        $pdo->prepare("INSERT INTO hotel_receipts (company_id, receipt_no, booking_id, customer_id, receipt_date, cash_account_id, amount, payment_method, notes, created_by)
                       VALUES (?,?,?,?,?,?,?,?,?,?)")
            ->execute([$cid, $receiptNo, $bookingId, $customerId, $receiptDate, $cashAccountId,
                       $amount, $paymentMethod, $notes, $uid]);
        $newId = (int)$pdo->lastInsertId();
        audit_log($pdo, [
          'company_id' => $cid,
          'user_id' => $uid,
          'module' => 'hotel',
          'action' => 'CREATE_RECEIPT',
          'entity_type' => 'hotel_receipt',
          'entity_id' => (string)$newId,
          'description' => audit_compose_description('تسجيل تحصيل حجز فندقي', [
            'رقم التحصيل' => $receiptNo,
            'الحجز' => $bookingNameById[(int)$bookingId] ?? ((string)$bookingId ?: ''),
            'العميل' => $customerNameById[(int)$customerId] ?? ((string)$customerId ?: ''),
            'المبلغ' => audit_money($amount),
            'طريقة الدفع' => audit_payment_method_label($paymentMethod),
            'الخزنة/البنك' => audit_account_label($pdo, $cid, $cashAccountId),
            'التاريخ' => $receiptDate,
            'ملاحظات' => $notes,
          ]),
        ]);
        $msg = 'تم تسجيل التحصيل.';
      } else {
        $receiptDate = trim($_POST['receipt_date'] ?? date('Y-m-d'));
        $cashAccountId = (int)($_POST['cash_account_id'] ?: $acc['cash_id']);
        $amount = (float)($_POST['amount'] ?? 0);
        $paymentMethod = $_POST['payment_method'] ?? 'CASH';
        $notes = trim($_POST['notes'] ?? '');
        $editId = (int)$_POST['id'];
        $pdo->prepare("UPDATE hotel_receipts SET receipt_no=?, booking_id=?, customer_id=?, receipt_date=?, cash_account_id=?, amount=?, payment_method=?, notes=? WHERE id=? AND company_id=?")
            ->execute([$receiptNo, $bookingId, $customerId, $receiptDate, $cashAccountId,
                       $amount, $paymentMethod, $notes, $editId, $cid]);
        audit_log($pdo, [
          'company_id' => $cid,
          'user_id' => $uid,
          'module' => 'hotel',
          'action' => 'UPDATE_RECEIPT',
          'entity_type' => 'hotel_receipt',
          'entity_id' => (string)$editId,
          'description' => audit_compose_description('تعديل تحصيل حجز فندقي', [
            'رقم التحصيل' => $receiptNo,
            'الحجز' => $bookingNameById[(int)$bookingId] ?? ((string)$bookingId ?: ''),
            'العميل' => $customerNameById[(int)$customerId] ?? ((string)$customerId ?: ''),
            'المبلغ' => audit_money($amount),
            'طريقة الدفع' => audit_payment_method_label($paymentMethod),
            'الخزنة/البنك' => audit_account_label($pdo, $cid, $cashAccountId),
            'التاريخ' => $receiptDate,
            'ملاحظات' => $notes,
          ]),
        ]);
        $msg = 'تم تعديل التحصيل.';
      }
    } elseif($action==='delete'){
      $delId = (int)$_POST['id'];
      $stDel = $pdo->prepare("SELECT * FROM hotel_receipts WHERE id=? AND company_id=? LIMIT 1");
      $stDel->execute([$delId, $cid]);
      $rowDel = $stDel->fetch(PDO::FETCH_ASSOC) ?: null;
      $pdo->prepare("DELETE FROM hotel_receipts WHERE id=? AND company_id=?")->execute([$delId, $cid]);
      if ($rowDel) {
        audit_log($pdo, [
          'company_id' => $cid,
          'user_id' => $uid,
          'module' => 'hotel',
          'action' => 'DELETE_RECEIPT',
          'entity_type' => 'hotel_receipt',
          'entity_id' => (string)$delId,
          'description' => audit_compose_description('حذف تحصيل حجز فندقي', [
            'رقم التحصيل' => (string)($rowDel['receipt_no'] ?? ''),
            'رقم الحجز' => (string)($rowDel['booking_id'] ?? ''),
            'رقم العميل' => (string)($rowDel['customer_id'] ?? ''),
            'المبلغ' => audit_money($rowDel['amount'] ?? 0),
            'طريقة الدفع' => audit_payment_method_label((string)($rowDel['payment_method'] ?? '')),
            'الخزنة/البنك' => audit_account_label($pdo, $cid, (int)($rowDel['cash_account_id'] ?? 0)),
            'التاريخ' => (string)($rowDel['receipt_date'] ?? ''),
          ]),
        ]);
      }
      $msg = 'تم حذف التحصيل.';
    } elseif($action==='post_journal'){
      $actId = (int)$_POST['id'];
      $stAct = $pdo->prepare("SELECT * FROM hotel_receipts WHERE id=? AND company_id=? LIMIT 1");
      $stAct->execute([$actId, $cid]);
      $rowAct = $stAct->fetch(PDO::FETCH_ASSOC) ?: null;
      hotel_create_receipt_journal($pdo, $cid, $actId, $uid);
      if ($rowAct) {
        audit_log($pdo, [
          'company_id' => $cid,
          'user_id' => $uid,
          'module' => 'journal',
          'action' => 'POST_RECEIPT',
          'entity_type' => 'hotel_receipt',
          'entity_id' => (string)$actId,
          'description' => audit_compose_description('ترحيل تحصيل حجز فندقي', [
            'رقم التحصيل' => (string)($rowAct['receipt_no'] ?? ''),
            'المبلغ' => audit_money($rowAct['amount'] ?? 0),
            'طريقة الدفع' => audit_payment_method_label((string)($rowAct['payment_method'] ?? '')),
            'التاريخ' => (string)($rowAct['receipt_date'] ?? ''),
          ]),
        ]);
      }
      $msg = 'تم إنشاء قيد يومية للتحصيل.';
    } elseif($action==='unpost_journal'){
      $actId = (int)$_POST['id'];
      $stAct = $pdo->prepare("SELECT * FROM hotel_receipts WHERE id=? AND company_id=? LIMIT 1");
      $stAct->execute([$actId, $cid]);
      $rowAct = $stAct->fetch(PDO::FETCH_ASSOC) ?: null;
      hotel_unpost_receipt_journal($pdo, $cid, $actId);
      if ($rowAct) {
        audit_log($pdo, [
          'company_id' => $cid,
          'user_id' => $uid,
          'module' => 'journal',
          'action' => 'UNPOST_RECEIPT',
          'entity_type' => 'hotel_receipt',
          'entity_id' => (string)$actId,
          'description' => audit_compose_description('إلغاء ترحيل تحصيل حجز فندقي', [
            'رقم التحصيل' => (string)($rowAct['receipt_no'] ?? ''),
            'المبلغ' => audit_money($rowAct['amount'] ?? 0),
            'طريقة الدفع' => audit_payment_method_label((string)($rowAct['payment_method'] ?? '')),
            'التاريخ' => (string)($rowAct['receipt_date'] ?? ''),
          ]),
        ]);
      }
      $msg = 'تم إلغاء قيد التحصيل.';
    }
  }catch(Throwable $e){ $err = $e->getMessage(); }
}

$list = $pdo->prepare("SELECT r.*, b.request_no, c.full_name AS customer_name, a.code AS cash_code, a.name AS cash_name
                       FROM hotel_receipts r
                       LEFT JOIN hotel_bookings b ON b.id=r.booking_id AND b.company_id=r.company_id
                       LEFT JOIN customers c ON c.id=r.customer_id AND c.company_id=r.company_id
                       LEFT JOIN accounts a ON a.id=r.cash_account_id
                       WHERE r.company_id=? ORDER BY r.id DESC");
$list->execute([$cid]);
$rows = $list->fetchAll(PDO::FETCH_ASSOC);

render_layout('تحصيلات الحجوزات','حجوزات الفنادق <span class="mx-1">/</span> التحصيلات', function() use($rows,$bookingOptions,$customerOptions,$cashOptions,$msg,$err,$acc){ ?>
<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="#mReceipt"><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>القيد</th><th class="text-end">إجراءات</th></tr></thead>
        <tbody>
          <?php if(!$rows): ?><tr><td colspan="9" 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['receipt_no']) ?></td>
            <td><?= h($r['request_no'] ?: '-') ?></td>
            <td><?= h($r['customer_name'] ?: '-') ?></td>
            <td><?= h($r['receipt_date']) ?></td>
            <td class="small"><?= h(trim(($r['cash_code'] ?: '').' - '.($r['cash_name'] ?: ''))) ?></td>
            <td class="text-end"><?= nf($r['amount']) ?></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">
              <button class="btn btn-outline-secondary btn-sm btnEdit"
                data-id="<?= (int)$r['id'] ?>" data-receiptno="<?= h($r['receipt_no']) ?>" data-booking="<?= (int)$r['booking_id'] ?>"
                data-customer="<?= (int)$r['customer_id'] ?>" data-date="<?= h($r['receipt_date']) ?>" data-cash="<?= (int)$r['cash_account_id'] ?>"
                data-amount="<?= h($r['amount']) ?>" data-method="<?= h($r['payment_method']) ?>" data-notes="<?= h($r['notes']) ?>">
                <i class="bi bi-pencil"></i>
              </button>
              <?php if(empty($r['posted_entry_id'])): ?>
              <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 else: ?>
              <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="mReceipt" 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><input name="receipt_no" class="form-control" placeholder="تلقائي"></div>
          <div class="col-md-4"><label class="form-label">التاريخ</label><input type="date" name="receipt_date" class="form-control" value="<?= date('Y-m-d') ?>"></div>
          <div class="col-md-4"><label class="form-label">طريقة الدفع</label><select name="payment_method" class="form-select"><option value="CASH">نقدي</option><option value="BANK">بنك</option></select></div>
          <div class="col-md-6"><label class="form-label">الحجز</label><select name="booking_id" class="form-select"><option value="">— بدون —</option><?php foreach($bookingOptions as $b): ?><option value="<?= (int)$b['id'] ?>"><?= h($b['request_no'].' - '.($b['full_name'] ?: 'بدون عميل')) ?></option><?php endforeach; ?></select></div>
          <div class="col-md-6"><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-6"><label class="form-label">الخزنة/البنك</label><select name="cash_account_id" class="form-select"><?php foreach($cashOptions as $a): ?><option value="<?= (int)$a['id'] ?>"><?= h($a['code'].' - '.$a['name']) ?></option><?php endforeach; ?></select></div>
          <div class="col-md-6"><label class="form-label">المبلغ</label><input type="number" step="0.01" name="amount" 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('mReceipt');
    m.querySelector('.modal-title').textContent = 'تعديل التحصيل';
    m.querySelector('[name=action]').value = 'update';
    m.querySelector('[name=id]').value = this.dataset.id || '';
    m.querySelector('[name=receipt_no]').value = this.dataset.receiptno || '';
    m.querySelector('[name=booking_id]').value = this.dataset.booking || '';
    m.querySelector('[name=customer_id]').value = this.dataset.customer || '';
    m.querySelector('[name=receipt_date]').value = this.dataset.date || '<?= date('Y-m-d') ?>';
    m.querySelector('[name=cash_account_id]').value = this.dataset.cash || '<?= (int)$acc['cash_id'] ?>';
    m.querySelector('[name=amount]').value = this.dataset.amount || 0;
    m.querySelector('[name=payment_method]').value = this.dataset.method || 'CASH';
    m.querySelector('[name=notes]').value = this.dataset.notes || '';
    bootstrap.Modal.getOrCreateInstance(m).show();
  });
});
document.getElementById('mReceipt').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=receipt_date]').value = '<?= date('Y-m-d') ?>';
  this.querySelector('[name=cash_account_id]').value = '<?= (int)$acc['cash_id'] ?>';
});
</script>
<?php }); ?>
