<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../fleet/_lib.php';
require_login();
$pdo = db();
$cid = (int)$_SESSION['company_id'];
fleet_ensure_schema($pdo);
csrf_bootstrap();
$msg=$err=null;
if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $action=$_POST['action']??'';
  try{
    if($action==='create'){
      $pdo->prepare("INSERT INTO customers (company_id, code, full_name, phone, email, address, status, notes, opening_balance) VALUES (?,?,?,?,?,?,?,?,?)")
          ->execute([$cid, trim($_POST['code']??''), trim($_POST['full_name']), trim($_POST['phone']), trim($_POST['email']), trim($_POST['address']), $_POST['status']??'ACTIVE', trim($_POST['notes']), (float)($_POST['opening_balance']??0)]);
      $id=(int)$pdo->lastInsertId();
      if(!empty($_POST['auto_account'])) fleet_ensure_customer_account($pdo,$cid,$id,trim($_POST['full_name']));
      $msg='تمت إضافة العميل';
    } elseif($action==='update'){
      $pdo->prepare("UPDATE customers SET code=?, full_name=?, phone=?, email=?, address=?, status=?, notes=?, opening_balance=? WHERE id=? AND company_id=?")
          ->execute([trim($_POST['code']??''), trim($_POST['full_name']), trim($_POST['phone']), trim($_POST['email']), trim($_POST['address']), $_POST['status']??'ACTIVE', trim($_POST['notes']), (float)($_POST['opening_balance']??0), (int)$_POST['id'], $cid]);
      if(!empty($_POST['auto_account'])) fleet_ensure_customer_account($pdo,$cid,(int)$_POST['id'],trim($_POST['full_name']));
      $msg='تم تعديل العميل';
    } elseif($action==='delete'){
      $pdo->prepare("DELETE FROM customers WHERE id=? AND company_id=?")->execute([(int)$_POST['id'], $cid]);
      $msg='تم حذف العميل';
    }
  }catch(Throwable $e){ $err=$e->getMessage(); }
}
$rows=$pdo->prepare("SELECT c.*, a.code a_code, a.name a_name,
  (SELECT COUNT(*) FROM customer_service_logs sl WHERE sl.customer_id=c.id AND sl.company_id=c.company_id) service_count
  FROM customers c LEFT JOIN accounts a ON a.id=c.account_id WHERE c.company_id=? ORDER BY c.id DESC");
$rows->execute([$cid]);
$customers=$rows->fetchAll(PDO::FETCH_ASSOC);
render_layout('تسجيل العملاء','إدارة العملاء <span class="mx-1">/</span> تسجيل العملاء', function() use($customers,$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>الخدمات</th><th>الحالة</th><th class="text-end">إجراءات</th></tr></thead><tbody><?php foreach($customers as $c): ?><tr><td><?= (int)$c['id'] ?></td><td><?= h($c['code'] ?: '-') ?></td><td class="fw-semibold"><?= h($c['full_name']) ?></td><td class="small"><?= h($c['phone']) ?><br><?= h($c['email']) ?></td><td class="small text-secondary"><?= h(trim(($c['a_code']??'').' '.($c['a_name']??''))) ?: 'غير مربوط' ?></td><td><?= (int)$c['service_count'] ?></td><td><span class="badge bg-light text-dark border"><?= h($c['status']==='ACTIVE'?'نشط':'موقوف') ?></span></td><td class="text-end"><a class="btn btn-outline-dark btn-sm" href="<?= url('/tourism/customer_ledger.php?customer_id='.(int)$c['id']) ?>"><i class="bi bi-journal-text"></i></a> <button class="btn btn-outline-secondary btn-sm btnEdit" data-id="<?= (int)$c['id'] ?>" data-code="<?= h($c['code']) ?>" data-name="<?= h($c['full_name']) ?>" data-phone="<?= h($c['phone']) ?>" data-email="<?= h($c['email']) ?>" data-address="<?= h($c['address']) ?>" data-status="<?= h($c['status']) ?>" data-notes="<?= h($c['notes']) ?>" data-opening="<?= h($c['opening_balance']) ?>"><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)$c['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="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-3 modal-inline-grid"><div class="col-md-4"><label class="form-label">الكود</label><input name="code" class="form-control"></div><div class="col-md-8"><label class="form-label">الاسم</label><input name="full_name" class="form-control" required></div><div class="col-md-6"><label class="form-label">الهاتف</label><input name="phone" class="form-control"></div><div class="col-md-6"><label class="form-label">البريد</label><input name="email" class="form-control"></div><div class="col-md-8"><label class="form-label">العنوان</label><input name="address" class="form-control"></div><div class="col-md-4"><label class="form-label">الحالة</label><select name="status" class="form-select selectpicker"><option value="ACTIVE">نشط</option><option value="INACTIVE">موقوف</option></select></div><div class="col-md-6"><label class="form-label">رصيد افتتاحي</label><input type="number" step="0.01" name="opening_balance" class="form-control" value="0"></div><div class="col-md-6"><div class="form-check mt-2"><input class="form-check-input" type="checkbox" name="auto_account" id="c_auto_account" checked><label class="form-check-label" for="c_auto_account">إنشاء/ربط حساب عميل تلقائيًا</label></div></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 modal-erp" 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-3 modal-inline-grid"><div class="col-md-4"><label class="form-label">الكود</label><input name="code" id="e_code" class="form-control"></div><div class="col-md-8"><label class="form-label">الاسم</label><input name="full_name" id="e_name" class="form-control" required></div><div class="col-md-6"><label class="form-label">الهاتف</label><input name="phone" id="e_phone" class="form-control"></div><div class="col-md-6"><label class="form-label">البريد</label><input name="email" id="e_email" class="form-control"></div><div class="col-md-8"><label class="form-label">العنوان</label><input name="address" id="e_address" class="form-control"></div><div class="col-md-4"><label class="form-label">الحالة</label><select name="status" id="e_status" class="form-select selectpicker"><option value="ACTIVE">نشط</option><option value="INACTIVE">موقوف</option></select></div><div class="col-md-6"><label class="form-label">رصيد افتتاحي</label><input type="number" step="0.01" name="opening_balance" id="e_opening" class="form-control" value="0"></div><div class="col-md-6"><div class="form-check mt-2"><input class="form-check-input" type="checkbox" name="auto_account" id="e_auto_account"><label class="form-check-label" for="e_auto_account">ربط حساب عميل تلقائيًا</label></div></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', ()=>{
  e_id.value=btn.dataset.id; e_code.value=btn.dataset.code; e_name.value=btn.dataset.name; e_phone.value=btn.dataset.phone; e_email.value=btn.dataset.email; e_address.value=btn.dataset.address; e_status.value=btn.dataset.status; e_notes.value=btn.dataset.notes; e_opening.value=btn.dataset.opening; e_auto_account.checked=true; $('.selectpicker').selectpicker('refresh'); new bootstrap.Modal(document.getElementById('mEdit')).show();
}));
</script>
<?php }); ?>
