<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_login();
$pdo = db();
$cid = (int)$_SESSION['company_id'];
csrf_bootstrap();
?>
<?php
// helpers
function next_no(PDO $pdo, int $cid, string $table, string $col, string $prefix): string {
  $st=$pdo->prepare("SELECT $col FROM $table WHERE company_id=? ORDER BY id DESC LIMIT 1");
  $st->execute([$cid]);
  $last=$st->fetchColumn();
  $n=1;
  if($last && preg_match('/(\d+)$/',$last,$m)) $n = (int)$m[1]+1;
  return $prefix . str_pad((string)$n, 5, '0', STR_PAD_LEFT);
}

$msg=$err=null;

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

$services=$pdo->prepare("SELECT s.id, s.name, s.default_price, s.revenue_account_id, a.code, a.name a_name FROM services s LEFT JOIN accounts a ON a.id=s.revenue_account_id WHERE s.company_id=? ORDER BY s.name");
$services->execute([$cid]); $services=$services->fetchAll(PDO::FETCH_ASSOC);

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

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $action=$_POST['action']??'';
  try{
    if($action==='create'){
      $pdo->beginTransaction();
      $booking_no = next_no($pdo,$cid,'bookings','booking_no','B-');
      $st=$pdo->prepare("INSERT INTO bookings (company_id, booking_no, customer_id, booking_date, status, notes) VALUES (?,?,?,?,?,?)");
      $st->execute([$cid, $booking_no, (int)$_POST['customer_id'], $_POST['booking_date'], 'CONFIRMED', trim($_POST['notes'])]);
      $bid=(int)$pdo->lastInsertId();

      $st=$pdo->prepare("INSERT INTO booking_items (booking_id, service_id, supplier_id, start_date, end_date, qty, unit_price, supplier_cost, notes) VALUES (?,?,?,?,?,?,?,?,?)");
      $st->execute([$bid, (int)$_POST['service_id'], (int)($_POST['supplier_id']?:0) ?: null, $_POST['start_date']?:null, $_POST['end_date']?:null,
                    (float)($_POST['qty']?:1), (float)($_POST['unit_price']?:0), (float)($_POST['supplier_cost']?:0), trim($_POST['item_notes'])]);
      $pdo->commit();
      $msg="تم إنشاء الحجز رقم $booking_no";
    }
  }catch(Throwable $e){
    if($pdo->inTransaction()) $pdo->rollBack();
    $err=$e->getMessage();
  }
}

// list bookings
$rows=$pdo->prepare("SELECT b.*, c.full_name customer_name
                     FROM bookings b JOIN customers c ON c.id=b.customer_id
                     WHERE b.company_id=? ORDER BY b.id DESC LIMIT 200");
$rows->execute([$cid]);
$list=$rows->fetchAll(PDO::FETCH_ASSOC);

render_layout('الحجوزات','الحجوزات <span class="mx-1">/</span> قائمة الحجوزات', function() use($list,$customers,$services,$suppliers,$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="#mAdd"><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>
        </tr></thead>
        <tbody>
          <?php foreach($list as $r): ?>
          <tr>
            <td class="text-secondary"><?= (int)$r['id'] ?></td>
            <td class="fw-semibold"><?= h($r['booking_no']) ?></td>
            <td><?= h($r['customer_name']) ?></td>
            <td class="text-secondary"><?= h($r['booking_date']) ?></td>
            <td><span class="badge bg-success-subtle text-success border border-success-subtle"><?= h($r['status']) ?></span></td>
            <td class="text-end">
              <a class="btn btn-outline-dark btn-sm" href="/tourism/invoice_create.php?booking_id=<?= (int)$r['id'] ?>"><i class="bi bi-receipt"></i> إصدار فاتورة</a>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade" id="mAdd" tabindex="-1">
  <div class="modal-dialog modal-xl"><div class="modal-content">
    <form method="post">
      <?= csrf_field() ?><input type="hidden" name="action" value="create">
      <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-2">
          <div class="col-md-4">
            <label class="form-label">العميل</label>
            <div class="picker-with-action"><select id="booking_customer_id" name="customer_id" class="form-select selectpicker" data-live-search="true" required>
              <?php foreach($customers as $c): ?><option value="<?= (int)$c['id'] ?>"><?= h($c['full_name']) ?></option><?php endforeach; ?>
            </select><button type="button" class="btn btn-outline-dark picker-action-btn js-open-ajax-modal" data-entity="customer" data-target="#booking_customer_id" title="إضافة عميل"><i class="bi bi-plus-lg"></i></button></div>
          </div>
          <div class="col-md-2">
            <label class="form-label">تاريخ الحجز</label>
            <input type="date" name="booking_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">ملاحظات</label>
            <input name="notes" class="form-control">
          </div>

          <div class="col-md-4">
            <label class="form-label">الخدمة</label>
            <div class="picker-with-action"><select name="service_id" id="service_id" class="form-select selectpicker" data-live-search="true" required>
              <?php foreach($services as $s): ?>
                <option value="<?= (int)$s['id'] ?>" data-price="<?= h($s['default_price']) ?>"><?= h($s['name']) ?></option>
              <?php endforeach; ?>
            </select><button type="button" class="btn btn-outline-dark picker-action-btn js-open-ajax-modal" data-entity="service" data-target="#service_id" title="إضافة خدمة"><i class="bi bi-plus-lg"></i></button></div>
          </div>
          <div class="col-md-4">
            <label class="form-label">المورد</label>
            <div class="picker-with-action"><select id="booking_supplier_id" name="supplier_id" class="form-select selectpicker" data-live-search="true">
              <option value="">—</option>
              <?php foreach($suppliers as $sp): ?><option value="<?= (int)$sp['id'] ?>"><?= h($sp['name']) ?></option><?php endforeach; ?>
            </select><button type="button" class="btn btn-outline-dark picker-action-btn js-open-ajax-modal" data-entity="supplier" data-target="#booking_supplier_id" title="إضافة مورد"><i class="bi bi-plus-lg"></i></button></div>
          </div>
          <div class="col-md-2">
            <label class="form-label">من</label>
            <input type="date" name="start_date" class="form-control">
          </div>
          <div class="col-md-2">
            <label class="form-label">إلى</label>
            <input type="date" name="end_date" class="form-control">
          </div>

          <div class="col-md-2">
            <label class="form-label">الكمية</label>
            <input type="number" step="0.01" name="qty" class="form-control" value="1">
          </div>
          <div class="col-md-2">
            <label class="form-label">سعر البيع</label>
            <input type="number" step="0.01" name="unit_price" id="unit_price" class="form-control" value="0">
          </div>
          <div class="col-md-2">
            <label class="form-label">تكلفة المورد</label>
            <input type="number" step="0.01" name="supplier_cost" class="form-control" value="0">
          </div>
          <div class="col-md-6">
            <label class="form-label">ملاحظات البند</label>
            <input name="item_notes" class="form-control">
          </div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-dark">حفظ الحجز</button></div>
    </form>
  </div></div>
</div>

<script>
(function(){
  const sel = document.getElementById('service_id');
  const price = document.getElementById('unit_price');
  function sync(){
    const opt = sel?.selectedOptions?.[0];
    if(!opt) return;
    const p = opt.getAttribute('data-price');
    if(p && (!price.value || Number(price.value)===0)) price.value = p;
  }
  sel?.addEventListener('change', sync);
  sync();
})();
</script>
<script>
window.quickSources = window.quickSources || {};
window.quickSources.accounts_optional = [<?php foreach($services as $s): ?><?php if(!empty($s['revenue_account_id'])): ?>{value:'<?= (int)$s['revenue_account_id'] ?>', text:'<?= h(($s['code']??'').' - '.($s['a_name']??'')) ?>'},<?php endif; ?><?php endforeach; ?>];
window.quickSources.revenue_accounts = window.quickSources.accounts_optional;
</script>
<?php }); ?>
