<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_permission('treasury.receipts.manage');require __DIR__.'/app/layout.php';
$pdo=db();$companyId=company_id();$userId=(int)user()['id'];$currencyId=(int)scalar('SELECT base_currency_id FROM companies WHERE id=?',[$companyId]);
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();try{$action=(string)($_POST['action']??'');
 if($action==='bank_create'){$accountId=(int)$_POST['account_id'];$s=$pdo->prepare('INSERT INTO bank_accounts(company_id,branch_id,code,bank_name,account_name,iban,account_no,currency_id,account_id,opening_balance,is_active,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,1,NOW())');$s->execute([$companyId,(int)user()['branch_id'],trim((string)$_POST['code']),trim((string)$_POST['bank_name']),trim((string)($_POST['account_name']??''))?:null,trim((string)($_POST['iban']??''))?:null,trim((string)($_POST['account_no']??''))?:null,$currencyId,$accountId,(float)($_POST['opening_balance']??0)]);audit('bank_account.create','bank_account',(string)$pdo->lastInsertId());flash('success','تم إنشاء الحساب البنكي.');
 }elseif($action==='cashbox_create'){$s=$pdo->prepare('INSERT INTO cashboxes(company_id,branch_id,code,name_ar,currency_id,account_id,custodian_user_id,is_active) VALUES (?,?,?,?,?,?,?,1)');$s->execute([$companyId,(int)user()['branch_id'],trim((string)$_POST['code']),trim((string)$_POST['name_ar']),$currencyId,(int)$_POST['account_id'],$userId]);audit('cashbox.create','cashbox',(string)$pdo->lastInsertId());flash('success','تم إنشاء الصندوق.');
 }elseif(in_array($action,['receipt_create','payment_create'],true)){$isReceipt=$action==='receipt_create';$amount=round((float)($_POST['amount']??0),2);$partnerId=(int)($_POST['partner_id']??0);$method=(string)($_POST['payment_method']??'bank_transfer');$bankId=(int)($_POST['bank_account_id']??0);$cashboxId=(int)($_POST['cashbox_id']??0);if($amount<=0||!$partnerId)throw new RuntimeException('الطرف والمبلغ الموجب مطلوبان.');if($method==='bank_transfer'&&!$bankId)throw new RuntimeException('اختر الحساب البنكي.');if($method==='cash'&&!$cashboxId)throw new RuntimeException('اختر الصندوق.');$prefix=$isReceipt?'RV':'PV';$table=$isReceipt?'receipt_vouchers':'payment_vouchers';$dateField=$isReceipt?'receipt_date':'payment_date';$noField=$isReceipt?'receipt_no':'payment_no';$no=$prefix.'-'.date('Ym').'-'.str_pad((string)((int)scalar("SELECT COUNT(*)+1 FROM $table WHERE company_id=?",[$companyId])),5,'0',STR_PAD_LEFT);
  if($isReceipt){$s=$pdo->prepare("INSERT INTO receipt_vouchers(company_id,branch_id,partner_id,receipt_no,receipt_date,payment_method,bank_account_id,cashbox_id,currency_id,amount,reference_no,description,status,created_by,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?, 'draft',?,NOW())");}else{$s=$pdo->prepare("INSERT INTO payment_vouchers(company_id,branch_id,partner_id,payment_no,payment_date,payment_method,bank_account_id,cashbox_id,currency_id,amount,reference_no,description,status,created_by,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?, 'draft',?,NOW())");}$s->execute([$companyId,(int)user()['branch_id'],$partnerId,$no,(string)$_POST['voucher_date'],$method,$bankId?:null,$cashboxId?:null,$currencyId,$amount,trim((string)($_POST['reference_no']??''))?:null,trim((string)($_POST['description']??''))?:null,$userId]);$voucherId=(int)$pdo->lastInsertId();$certificateId=(int)($_POST['certificate_id']??0);if($certificateId){if($isReceipt){$pdo->prepare("INSERT INTO receipt_allocations(receipt_voucher_id,customer_certificate_id,allocation_type,allocated_amount,created_at) VALUES (?,?,'certificate',?,NOW())")->execute([$voucherId,$certificateId,$amount]);}else{$pdo->prepare("INSERT INTO payment_allocations(payment_voucher_id,subcontract_certificate_id,allocation_type,allocated_amount,created_at) VALUES (?,?,'subcontract_certificate',?,NOW())")->execute([$voucherId,$certificateId,$amount]);}}audit($isReceipt?'receipt.create':'payment.create',$isReceipt?'receipt_voucher':'payment_voucher',(string)$voucherId);flash('success','تم حفظ السند كمسودة: '.$no);
 }elseif(in_array($action,['receipt_approve','receipt_post','payment_approve','payment_post'],true)){$isReceipt=str_starts_with($action,'receipt');$post=str_ends_with($action,'post');$table=$isReceipt?'receipt_vouchers':'payment_vouchers';$id=(int)$_POST['id'];if($post){$q=$pdo->prepare("SELECT * FROM $table WHERE id=? AND company_id=? AND status='approved'");$q->execute([$id,$companyId]);$voucher=$q->fetch();if(!$voucher)throw new RuntimeException('السند غير متاح للترحيل.');$cashAccount=0;if($voucher['bank_account_id'])$cashAccount=(int)scalar('SELECT account_id FROM bank_accounts WHERE id=? AND company_id=?',[$voucher['bank_account_id'],$companyId]);elseif($voucher['cashbox_id'])$cashAccount=(int)scalar('SELECT account_id FROM cashboxes WHERE id=? AND company_id=?',[$voucher['cashbox_id'],$companyId]);if(!$cashAccount)throw new RuntimeException('لم يتم العثور على حساب البنك أو الصندوق المرتبط بالسند.');$counterAccount=mapped_account($isReceipt?'AR_CONTROL':'AP_CONTROL');$lines=$isReceipt?[['account_id'=>$cashAccount,'debit'=>$voucher['amount']],['account_id'=>$counterAccount,'credit'=>$voucher['amount']]]:[['account_id'=>$counterAccount,'debit'=>$voucher['amount']],['account_id'=>$cashAccount,'credit'=>$voucher['amount']]];$date=$voucher[$isReceipt?'receipt_date':'payment_date'];$pdo->beginTransaction();$journalId=post_system_journal($date,($isReceipt?'سند قبض ':'سند صرف ').$voucher[$isReceipt?'receipt_no':'payment_no'],$isReceipt?'receipt_voucher':'payment_voucher',$id,$lines);$s=$pdo->prepare("UPDATE $table SET status='posted',journal_entry_id=? WHERE id=?");$s->execute([$journalId,$id]);$pdo->commit();}else{$s=$pdo->prepare("UPDATE $table SET status='approved',approved_by=? WHERE id=? AND company_id=? AND status='draft'");$s->execute([$userId,$id,$companyId]);}if(!$s->rowCount())throw new RuntimeException('تعذر تغيير حالة السند.');audit($action,$isReceipt?'receipt_voucher':'payment_voucher',(string)$id);flash('success',$post?'تم ترحيل السند وإنشاء القيد الآلي.':'تم اعتماد السند.');}
 }catch(Throwable $e){flash('error',$e instanceof PDOException?'البيانات مكررة أو غير متوافقة مع السجلات الحالية.':$e->getMessage());}redirect('treasury.php');}
$accounts=$pdo->prepare("SELECT id,code,name_ar FROM accounts WHERE company_id=? AND is_postable=1 AND status='active' ORDER BY code");$accounts->execute([$companyId]);$accounts=$accounts->fetchAll();$banks=$pdo->prepare('SELECT * FROM bank_accounts WHERE company_id=? AND is_active=1 ORDER BY code');$banks->execute([$companyId]);$banks=$banks->fetchAll();$cashboxes=$pdo->prepare('SELECT * FROM cashboxes WHERE company_id=? AND is_active=1 ORDER BY code');$cashboxes->execute([$companyId]);$cashboxes=$cashboxes->fetchAll();$partners=$pdo->prepare("SELECT id,partner_code,legal_name_ar FROM business_partners WHERE company_id=? AND status='active' AND deleted_at IS NULL ORDER BY legal_name_ar");$partners->execute([$companyId]);$partners=$partners->fetchAll();
$customerCerts=$pdo->prepare("SELECT cc.id,cc.certificate_no,p.name_ar,cc.net_due_amount FROM customer_certificates cc JOIN projects p ON p.id=cc.project_id WHERE p.company_id=? AND cc.status IN ('certified','invoiced','partially_collected') ORDER BY cc.id DESC");$customerCerts->execute([$companyId]);$customerCerts=$customerCerts->fetchAll();$subCerts=$pdo->prepare("SELECT sc.id,sc.certificate_no,p.name_ar,sc.net_payable_amount FROM subcontract_certificates sc JOIN projects p ON p.id=sc.project_id JOIN subcontracts s ON s.id=sc.subcontract_id WHERE s.company_id=? AND sc.status IN ('approved','invoiced','partially_paid') ORDER BY sc.id DESC");$subCerts->execute([$companyId]);$subCerts=$subCerts->fetchAll();
$receipts=$pdo->prepare("SELECT rv.*,bp.legal_name_ar partner_name FROM receipt_vouchers rv LEFT JOIN business_partners bp ON bp.id=rv.partner_id WHERE rv.company_id=? ORDER BY rv.id DESC LIMIT 100");$receipts->execute([$companyId]);$receipts=$receipts->fetchAll();$payments=$pdo->prepare("SELECT pv.*,bp.legal_name_ar partner_name FROM payment_vouchers pv LEFT JOIN business_partners bp ON bp.id=pv.partner_id WHERE pv.company_id=? ORDER BY pv.id DESC LIMIT 100");$payments->execute([$companyId]);$payments=$payments->fetchAll();
render_header('treasury','الخزينة وسندات القبض والصرف','الحسابات البنكية والصناديق وحركة المقبوضات والمدفوعات.');?>
<div class="settings-grid"><?php foreach([['bank_create','حساب بنكي','bank'],['cashbox_create','صندوق نقدي','cash']] as [$act,$title,$type]):?><details class="panel quick-add"><summary>＋ <?= e($title) ?></summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="<?= e($act) ?>"><label>الكود<input name="code" required></label><?php if($type==='bank'):?><label>اسم البنك<input name="bank_name" required></label><label>اسم الحساب<input name="account_name"></label><label>IBAN<input name="iban"></label><label>رقم الحساب<input name="account_no"></label><label>الرصيد الافتتاحي<input type="number" step="0.01" name="opening_balance" value="0"></label><?php else:?><label>اسم الصندوق<input name="name_ar" required></label><?php endif;?><label>حساب الأستاذ<select name="account_id"><?php foreach($accounts as $a):?><option value="<?= (int)$a['id'] ?>"><?= e($a['code'].' — '.$a['name_ar']) ?></option><?php endforeach;?></select></label><button class="primary-btn">حفظ</button></form></details><?php endforeach;?></div>
<div class="settings-grid"><?php foreach([['receipt_create','سند قبض',$customerCerts],['payment_create','سند صرف',$subCerts]] as [$act,$title,$certs]):?><details class="panel quick-add" open><summary>＋ <?= e($title) ?></summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="<?= e($act) ?>"><label>الطرف<select name="partner_id"><?php foreach($partners as $p):?><option value="<?= (int)$p['id'] ?>"><?= e($p['partner_code'].' — '.$p['legal_name_ar']) ?></option><?php endforeach;?></select></label><label>التاريخ<input type="date" name="voucher_date" value="<?= date('Y-m-d') ?>"></label><label>طريقة الدفع<select name="payment_method"><option value="bank_transfer">تحويل بنكي</option><option value="cash">نقدي</option><option value="cheque">شيك</option><option value="card">بطاقة</option><option value="other">أخرى</option></select></label><label>الحساب البنكي<select name="bank_account_id"><option value="0">—</option><?php foreach($banks as $b):?><option value="<?= (int)$b['id'] ?>"><?= e($b['code'].' — '.$b['bank_name']) ?></option><?php endforeach;?></select></label><label>الصندوق<select name="cashbox_id"><option value="0">—</option><?php foreach($cashboxes as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['code'].' — '.$c['name_ar']) ?></option><?php endforeach;?></select></label><label>المبلغ<input type="number" step="0.01" min="0.01" name="amount" required></label><label>ربط بمستخلص<select name="certificate_id"><option value="0">غير مخصص</option><?php foreach($certs as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['certificate_no'].' — '.$c['name_ar']) ?></option><?php endforeach;?></select></label><label>المرجع<input name="reference_no"></label><label>البيان<input name="description"></label><button class="primary-btn">حفظ كمسودة</button></form></details><?php endforeach;?></div>
<?php foreach([['سندات القبض',$receipts,'receipt'],['سندات الصرف',$payments,'payment']] as [$title,$rows,$kind]):?><section class="panel data-card"><header><h2><?= e($title) ?></h2></header><div class="responsive-table"><table><thead><tr><th>الرقم</th><th>التاريخ</th><th>الطرف</th><th>الطريقة</th><th>المبلغ</th><th>الحالة</th><th>الإجراء</th></tr></thead><tbody><?php foreach($rows as $r):$no=$r[$kind==='receipt'?'receipt_no':'payment_no'];$date=$r[$kind==='receipt'?'receipt_date':'payment_date'];?><tr><td><?= e($no) ?></td><td><?= e($date) ?></td><td><?= e($r['partner_name']) ?></td><td><?= e($r['payment_method']) ?></td><td><?= number_format((float)$r['amount'],2) ?></td><td><span class="chip"><?= e($r['status']) ?></span></td><td><?php if($r['status']==='draft'):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="<?= $kind ?>_approve"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button>اعتماد</button></form><?php elseif($r['status']==='approved'):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="<?= $kind ?>_post"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button>ترحيل</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section><?php endforeach;render_footer();
