<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_permission('system.settings.manage');require __DIR__.'/app/layout.php';$pdo=db();$companyId=company_id();$userId=(int)user()['id'];
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();try{$pdo->beginTransaction();$pdo->prepare('DELETE FROM company_account_mappings WHERE company_id=? AND branch_id IS NULL AND project_id IS NULL')->execute([$companyId]);$s=$pdo->prepare('INSERT INTO company_account_mappings(company_id,account_role_id,account_id,effective_from,created_by,created_at) VALUES (?,?,?,?,?,NOW())');foreach(($_POST['mapping']??[]) as $roleId=>$accountId)if((int)$accountId>0)$s->execute([$companyId,(int)$roleId,(int)$accountId,date('Y-m-d'),$userId]);$pdo->commit();audit('account_mappings.update','company',(string)$companyId);flash('success','تم حفظ الربط المحاسبي.');}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash('error',$e->getMessage());}redirect('accounting_setup.php');}
$roles=$pdo->query("SELECT * FROM account_roles WHERE role_code IN ('AR_CONTROL','AP_CONTROL','BANK','CASH','VAT_INPUT','VAT_OUTPUT','CONSTRUCTION_REVENUE','CUSTOMER_ADVANCES','RETENTION_RECEIVABLE','RETENTION_PAYABLE','INVENTORY','GRNI','PROJECT_MATERIAL_COST','PROJECT_SUBCONTRACT_COST','DEPRECIATION_EXPENSE','ACCUMULATED_DEPRECIATION') ORDER BY id")->fetchAll();$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();$current=$pdo->prepare('SELECT account_role_id,account_id FROM company_account_mappings WHERE company_id=? AND branch_id IS NULL AND project_id IS NULL AND effective_to IS NULL');$current->execute([$companyId]);$current=$current->fetchAll(PDO::FETCH_KEY_PAIR);
render_header('accounting_setup','الربط المحاسبي','حدد حساب الأستاذ المقابل لكل وظيفة نظامية قبل الترحيل الآلي.');?>
<form class="panel form-card" method="post"><?= csrf_field() ?><div class="responsive-table"><table><thead><tr><th>الوظيفة</th><th>الحساب المرتبط</th></tr></thead><tbody><?php foreach($roles as $r):?><tr><td><strong><?= e($r['name_ar']) ?></strong><small><?= e($r['role_code']) ?></small></td><td><select name="mapping[<?= (int)$r['id'] ?>]"><option value="0">غير مربوط</option><?php foreach($accounts as $a):?><option value="<?= (int)$a['id'] ?>" <?= (int)($current[$r['id']]??0)===(int)$a['id']?'selected':'' ?>><?= e($a['code'].' — '.$a['name_ar']) ?></option><?php endforeach;?></select></td></tr><?php endforeach;?></tbody></table></div><button class="primary-btn">حفظ الربط</button></form><?php render_footer();
