<?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
$msg=$err=null;
$acc=$pdo->prepare("SELECT id, code, name FROM accounts WHERE company_id=? AND type IN ('REVENUE') AND is_active=1 ORDER BY code");
$acc->execute([$cid]);
$revAccounts=$acc->fetchAll(PDO::FETCH_ASSOC);

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $action=$_POST['action']??'';
  try{
    if($action==='create'){
      $st=$pdo->prepare("INSERT INTO services (company_id, name, kind, revenue_account_id, default_price) VALUES (?,?,?,?,?)");
      $st->execute([$cid, trim($_POST['name']), $_POST['kind'], (int)$_POST['revenue_account_id'], (float)$_POST['default_price']]);
      $msg='تمت الإضافة';
    } elseif($action==='update'){
      $st=$pdo->prepare("UPDATE services SET name=?, kind=?, revenue_account_id=?, default_price=? WHERE id=? AND company_id=?");
      $st->execute([trim($_POST['name']), $_POST['kind'], (int)$_POST['revenue_account_id'], (float)$_POST['default_price'], (int)$_POST['id'], $cid]);
      $msg='تم التعديل';
    } elseif($action==='delete'){
      $st=$pdo->prepare("DELETE FROM services WHERE id=? AND company_id=?");
      $st->execute([(int)$_POST['id'], $cid]);
      $msg='تم الحذف';
    }
  }catch(Throwable $e){ $err=$e->getMessage(); }
}
$rows=$pdo->prepare("SELECT s.*, a.code 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.id DESC");
$rows->execute([$cid]);
$list=$rows->fetchAll(PDO::FETCH_ASSOC);
$kinds=['HOTEL'=>'فندق','APARTMENT'=>'شقق','CAR'=>'سيارات','FLIGHT'=>'طيران','TOUR'=>'رحلات','UMRAH'=>'حج/عمرة','OTHER'=>'أخرى'];
render_layout('الخدمات','الحجوزات <span class="mx-1">/</span> الخدمات', function() use($list,$msg,$err,$kinds,$revAccounts){ ?>
<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 class="text-end">السعر الافتراضي</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['name']) ?></td>
            <td><?= h($kinds[$r['kind']] ?? $r['kind']) ?></td>
            <td class="text-secondary"><?= h(trim(($r['a_code']??'')." ".($r['a_name']??''))) ?></td>
            <td class="text-end"><?= nf($r['default_price']) ?></td>
            <td class="text-end">
              <button class="btn btn-outline-secondary btn-sm btnEdit"
                data-id="<?= (int)$r['id'] ?>"
                data-name="<?= h($r['name']) ?>"
                data-kind="<?= h($r['kind']) ?>"
                data-acc="<?= (int)($r['revenue_account_id']??0) ?>"
                data-price="<?= h($r['default_price']) ?>"
              ><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" id="mAdd" tabindex="-1">
  <div class="modal-dialog modal-lg"><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-6"><label class="form-label">اسم الخدمة</label><input name="name" class="form-control" required></div>
          <div class="col-md-3"><label class="form-label">النوع</label>
            <select name="kind" class="form-select selectpicker" data-live-search="true">
              <?php foreach($kinds as $k=>$v): ?><option value="<?=h($k)?>"><?=h($v)?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-3"><label class="form-label">السعر الافتراضي</label><input name="default_price" type="number" step="0.01" class="form-control" value="0"></div>
          <div class="col-12"><label class="form-label">حساب الإيراد</label>
            <select name="revenue_account_id" class="form-select selectpicker" data-live-search="true" required>
              <?php foreach($revAccounts as $a): ?>
                <option value="<?= (int)$a['id'] ?>"><?= h($a['code'].' - '.$a['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-dark">حفظ</button></div>
    </form>
  </div></div>
</div>

<div class="modal fade" id="mEdit" tabindex="-1">
  <div class="modal-dialog modal-lg"><div class="modal-content">
    <form method="post">
      <?= csrf_field() ?><input type="hidden" name="action" value="update"><input type="hidden" name="id" id="e_id">
      <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-6"><label class="form-label">اسم الخدمة</label><input name="name" id="e_name" class="form-control" required></div>
          <div class="col-md-3"><label class="form-label">النوع</label>
            <select name="kind" id="e_kind" class="form-select selectpicker" data-live-search="true">
              <?php foreach($kinds as $k=>$v): ?><option value="<?=h($k)?>"><?=h($v)?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-3"><label class="form-label">السعر الافتراضي</label><input name="default_price" id="e_price" type="number" step="0.01" class="form-control"></div>
          <div class="col-12"><label class="form-label">حساب الإيراد</label>
            <select name="revenue_account_id" id="e_acc" class="form-select selectpicker" data-live-search="true" required>
              <?php foreach($revAccounts as $a): ?>
                <option value="<?= (int)$a['id'] ?>"><?= h($a['code'].' - '.$a['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-dark">تحديث</button></div>
    </form>
  </div></div>
</div>

<script>
document.querySelectorAll('.btnEdit').forEach(btn=>{
  btn.addEventListener('click', ()=>{
    document.getElementById('e_id').value=btn.dataset.id;
    document.getElementById('e_name').value=btn.dataset.name;
    document.getElementById('e_price').value=btn.dataset.price;
    document.getElementById('e_kind').value=btn.dataset.kind;
    document.getElementById('e_acc').value=btn.dataset.acc;
    $('.selectpicker').selectpicker('refresh');
    new bootstrap.Modal(document.getElementById('mEdit')).show();
  });
});
</script>
<?php }); ?>
