<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_permission('projects.budgets.manage');require __DIR__.'/app/layout.php';
$pdo=db();$companyId=company_id();$userId=(int)user()['id'];
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();try{$action=(string)($_POST['action']??'');
 if($action==='cost_code_create'){$code=trim((string)$_POST['code']);$name=trim((string)$_POST['name_ar']);if(!$code||!$name)throw new RuntimeException('الكود والاسم مطلوبان.');$s=$pdo->prepare('INSERT INTO cost_codes(company_id,code,name_ar,cost_category,is_postable,is_active,created_at,updated_at) VALUES (?,?,?,?,1,1,NOW(),NOW())');$s->execute([$companyId,$code,$name,(string)$_POST['cost_category']]);audit('cost_code.create','cost_code',(string)$pdo->lastInsertId());flash('success','تم إنشاء كود التكلفة.');
 }elseif($action==='budget_create'){$projectId=(int)$_POST['project_id'];$codes=$_POST['cost_code_id']??[];$amounts=$_POST['budget_amount']??[];$contingencies=$_POST['contingency_amount']??[];$lines=[];$total=0;foreach($codes as $i=>$codeId){$amount=round((float)($amounts[$i]??0),2);$cont=round((float)($contingencies[$i]??0),2);if(!$codeId||$amount<0)continue;$lines[]=[(int)$codeId,$amount,$cont];$total+=$amount+$cont;}if(!$projectId||!$lines)throw new RuntimeException('اختر المشروع وأضف بند موازنة.');$versionNo=(int)scalar('SELECT COALESCE(MAX(version_no),0)+1 FROM project_budget_versions WHERE project_id=?',[$projectId]);$pdo->beginTransaction();$s=$pdo->prepare("INSERT INTO project_budget_versions(project_id,version_no,version_name,version_type,status,total_budget,effective_from,notes,created_by,created_at) VALUES (?,?,?,'baseline','draft',?,?,?,?,NOW())");$s->execute([$projectId,$versionNo,trim((string)$_POST['version_name']),$total,($_POST['effective_from']??'')?:null,trim((string)($_POST['notes']??''))?:null,$userId]);$versionId=(int)$pdo->lastInsertId();$s=$pdo->prepare('INSERT INTO project_budget_lines(budget_version_id,cost_code_id,budget_amount,contingency_amount) VALUES (?,?,?,?)');foreach($lines as $line)$s->execute([$versionId,$line[0],$line[1],$line[2]]);$pdo->commit();audit('project_budget.create','project_budget_version',(string)$versionId,['total'=>$total]);flash('success','تم حفظ الموازنة كمسودة.');
 }elseif(in_array($action,['submit','approve'],true)){$id=(int)$_POST['id'];if($action==='submit'){$s=$pdo->prepare("UPDATE project_budget_versions pbv JOIN projects p ON p.id=pbv.project_id SET pbv.status='submitted',pbv.submitted_by=? WHERE pbv.id=? AND p.company_id=? AND pbv.status='draft'");$s->execute([$userId,$id,$companyId]);}else{$s=$pdo->prepare("UPDATE project_budget_versions pbv JOIN projects p ON p.id=pbv.project_id SET pbv.status='approved',pbv.approved_by=?,pbv.approved_at=NOW() WHERE pbv.id=? AND p.company_id=? AND pbv.status='submitted'");$s->execute([$userId,$id,$companyId]);}if(!$s->rowCount())throw new RuntimeException('تعذر تغيير حالة الموازنة.');audit('project_budget.'.$action,'project_budget_version',(string)$id);flash('success','تم تحديث حالة الموازنة.');}
 }catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash('error',$e instanceof PDOException?'الكود مكرر أو البيانات غير صالحة.':$e->getMessage());}redirect('budgets.php?project_id='.(int)($_POST['project_id']??$_GET['project_id']??0));}
$projects=$pdo->prepare("SELECT id,project_no,name_ar FROM projects WHERE company_id=? AND deleted_at IS NULL ORDER BY project_no");$projects->execute([$companyId]);$projects=$projects->fetchAll();$codes=$pdo->prepare('SELECT * FROM cost_codes WHERE company_id=? AND is_active=1 ORDER BY code');$codes->execute([$companyId]);$codes=$codes->fetchAll();$versions=$pdo->prepare("SELECT pbv.*,p.project_no,p.name_ar project_name FROM project_budget_versions pbv JOIN projects p ON p.id=pbv.project_id WHERE p.company_id=? ORDER BY pbv.id DESC");$versions->execute([$companyId]);$versions=$versions->fetchAll();
$projectId=(int)($_GET['project_id']??($projects[0]['id']??0));$comparison=[];$approvedVersion=(int)scalar("SELECT pbv.id FROM project_budget_versions pbv JOIN projects p ON p.id=pbv.project_id WHERE pbv.project_id=? AND p.company_id=? AND pbv.status='approved' ORDER BY pbv.version_no DESC LIMIT 1",[$projectId,$companyId]);if($approvedVersion){$s=$pdo->prepare("SELECT cc.code,cc.name_ar,pbl.budget_amount+pbl.contingency_amount budget,COALESCE((SELECT SUM(jl.debit_amount-jl.credit_amount) FROM journal_lines jl JOIN journal_entries je ON je.id=jl.journal_entry_id WHERE jl.cost_code_id=cc.id AND jl.project_id=? AND je.status='posted'),0) actual,COALESCE((SELECT SUM(poi.total_amount) FROM purchase_order_items poi JOIN purchase_orders po ON po.id=poi.purchase_order_id WHERE poi.cost_code_id=cc.id AND po.project_id=? AND po.status NOT IN ('draft','cancelled','closed')),0) committed FROM project_budget_lines pbl JOIN cost_codes cc ON cc.id=pbl.cost_code_id WHERE pbl.budget_version_id=? ORDER BY cc.code");$s->execute([$projectId,$projectId,$approvedVersion]);$comparison=$s->fetchAll();}
render_header('budgets','موازنات المشاريع','أكواد التكلفة والموازنة المعتمدة ومقارنتها بالفعلي والمرتبط.');?>
<details class="panel quick-add"><summary>＋ كود تكلفة</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="cost_code_create"><div class="form-grid"><label>الكود<input name="code" required></label><label>الاسم<input name="name_ar" required></label><label>التصنيف<select name="cost_category"><option value="material">مواد</option><option value="labor">عمالة</option><option value="subcontract">مقاول باطن</option><option value="equipment">معدات</option><option value="overhead">مصاريف غير مباشرة</option><option value="other">أخرى</option></select></label></div><button class="primary-btn">حفظ الكود</button></form></details>
<details class="panel quick-add" open><summary>＋ موازنة مشروع</summary><form method="post" id="budgetForm"><?= csrf_field() ?><input type="hidden" name="action" value="budget_create"><div class="form-grid"><label>المشروع<select name="project_id"><?php foreach($projects as $p):?><option value="<?= (int)$p['id'] ?>"><?= e($p['project_no'].' — '.$p['name_ar']) ?></option><?php endforeach;?></select></label><label>اسم النسخة<input name="version_name" value="الموازنة الأساسية" required></label><label>سارية من<input type="date" name="effective_from"></label><label>ملاحظات<input name="notes"></label></div><div class="responsive-table"><table id="budgetLines"><thead><tr><th>كود التكلفة</th><th>الموازنة</th><th>احتياطي</th><th></th></tr></thead><tbody><tr><td><select name="cost_code_id[]"><?php foreach($codes as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['code'].' — '.$c['name_ar']) ?></option><?php endforeach;?></select></td><td><input type="number" step="0.01" min="0" name="budget_amount[]" value="0"></td><td><input type="number" step="0.01" min="0" name="contingency_amount[]" value="0"></td><td><button type="button" onclick="this.closest('tr').remove()">×</button></td></tr></tbody></table></div><button type="button" class="secondary-btn" id="addBudgetLine">إضافة بند</button> <button class="primary-btn">حفظ كمسودة</button></form></details>
<section class="panel data-card"><header><h2>نسخ الموازنات</h2></header><div class="responsive-table"><table><thead><tr><th>المشروع</th><th>النسخة</th><th>الإجمالي</th><th>الحالة</th><th>الإجراء</th></tr></thead><tbody><?php foreach($versions as $v):?><tr><td><?= e($v['project_no'].' — '.$v['project_name']) ?></td><td><?= e($v['version_name'].' #'.$v['version_no']) ?></td><td><?= number_format((float)$v['total_budget'],2) ?></td><td><span class="chip"><?= e($v['status']) ?></span></td><td><?php if($v['status']==='draft'):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="submit"><input type="hidden" name="id" value="<?= (int)$v['id'] ?>"><input type="hidden" name="project_id" value="<?= (int)$v['project_id'] ?>"><button>تقديم</button></form><?php elseif($v['status']==='submitted'):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="approve"><input type="hidden" name="id" value="<?= (int)$v['id'] ?>"><input type="hidden" name="project_id" value="<?= (int)$v['project_id'] ?>"><button>اعتماد</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<section class="panel data-card"><header><h2>الرقابة على التكلفة</h2><form method="get"><select name="project_id" onchange="this.form.submit()"><?php foreach($projects as $p):?><option value="<?= (int)$p['id'] ?>" <?= $projectId===(int)$p['id']?'selected':'' ?>><?= e($p['project_no'].' — '.$p['name_ar']) ?></option><?php endforeach;?></select></form></header><div class="responsive-table"><table><thead><tr><th>كود التكلفة</th><th>الموازنة</th><th>الفعلي</th><th>الارتباطات</th><th>المتبقي</th><th>الاستهلاك</th></tr></thead><tbody><?php foreach($comparison as $r):$used=(float)$r['actual']+(float)$r['committed'];$remaining=(float)$r['budget']-$used;$pct=(float)$r['budget']?($used/(float)$r['budget']*100):0;?><tr><td><?= e($r['code'].' — '.$r['name_ar']) ?></td><td><?= number_format((float)$r['budget'],2) ?></td><td><?= number_format((float)$r['actual'],2) ?></td><td><?= number_format((float)$r['committed'],2) ?></td><td><?= number_format($remaining,2) ?></td><td><span class="chip <?= $pct>100?'danger':($pct>80?'warning':'success') ?>"><?= number_format($pct,1) ?>%</span></td></tr><?php endforeach;?></tbody></table></div></section>
<template id="budgetTemplate"><tr><td><select name="cost_code_id[]"><?php foreach($codes as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['code'].' — '.$c['name_ar']) ?></option><?php endforeach;?></select></td><td><input type="number" step="0.01" min="0" name="budget_amount[]" value="0"></td><td><input type="number" step="0.01" min="0" name="contingency_amount[]" value="0"></td><td><button type="button" onclick="this.closest('tr').remove()">×</button></td></tr></template><script>addBudgetLine.onclick=()=>document.querySelector('#budgetLines tbody').append(budgetTemplate.content.cloneNode(true));</script>
<?php render_footer();
