<?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;
if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $action=$_POST['action']??'';
  try{
    if($action==='create'){
      $st=$pdo->prepare("INSERT INTO suppliers (company_id, name, kind, phone, notes) VALUES (?,?,?,?,?)");
      $st->execute([$cid, trim($_POST['name']), $_POST['kind'], trim($_POST['phone']), trim($_POST['notes'])]);
      $msg='تمت الإضافة';
    } elseif($action==='update'){
      $st=$pdo->prepare("UPDATE suppliers SET name=?, kind=?, phone=?, notes=? WHERE id=? AND company_id=?");
      $st->execute([trim($_POST['name']), $_POST['kind'], trim($_POST['phone']), trim($_POST['notes']), (int)$_POST['id'], $cid]);
      $msg='تم التعديل';
    } elseif($action==='delete'){
      $st=$pdo->prepare("DELETE FROM suppliers WHERE id=? AND company_id=?");
      $st->execute([(int)$_POST['id'], $cid]);
      $msg='تم الحذف';
    }
  }catch(Throwable $e){ $err=$e->getMessage(); }
}
$rows=$pdo->prepare("SELECT * FROM suppliers WHERE company_id=? ORDER BY 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){ ?>
<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></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><?= h($r['phone']) ?></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-phone="<?= h($r['phone']) ?>"
                data-notes="<?= h($r['notes']) ?>"
              ><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="phone" class="form-control"></div>
          <div class="col-12"><label class="form-label">ملاحظات</label><textarea name="notes" class="form-control" rows="2"></textarea></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="phone" id="e_phone" class="form-control"></div>
          <div class="col-12"><label class="form-label">ملاحظات</label><textarea name="notes" id="e_notes" class="form-control" rows="2"></textarea></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_phone').value=btn.dataset.phone;
    document.getElementById('e_notes').value=btn.dataset.notes;
    document.getElementById('e_kind').value=btn.dataset.kind;
    $('.selectpicker').selectpicker('refresh');
    new bootstrap.Modal(document.getElementById('mEdit')).show();
  });
});
</script>
<?php }); ?>
