<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_permission('procurement.requests.create');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==='request_create'){$projectId=(int)($_POST['project_id']??0);$descs=$_POST['description']??[];$qtys=$_POST['qty']??[];$costs=$_POST['estimated_cost']??[];$codes=$_POST['cost_code_id']??[];$lines=[];foreach($descs as $i=>$desc){$desc=trim((string)$desc);$qty=round((float)($qtys[$i]??0),4);$cost=round((float)($costs[$i]??0),4);if(!$desc||$qty<=0)continue;$lines[]=[$desc,$qty,$cost,(int)($codes[$i]??0)?:null];}if(!$lines)throw new RuntimeException('أضف بندًا صحيحًا على الأقل.');$no='PR-'.date('Ym').'-'.str_pad((string)((int)scalar('SELECT COUNT(*)+1 FROM purchase_requests WHERE company_id=?',[$companyId])),5,'0',STR_PAD_LEFT);$pdo->beginTransaction();$pdo->prepare("INSERT INTO purchase_requests(company_id,branch_id,project_id,request_no,request_date,required_by_date,purpose,priority,status,requested_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?, 'draft',?,NOW(),NOW())")->execute([$companyId,(int)user()['branch_id'],$projectId?:null,$no,$_POST['request_date'],($_POST['required_by_date']??'')?:null,trim((string)($_POST['purpose']??''))?:null,(string)($_POST['priority']??'normal'),$userId]);$requestId=(int)$pdo->lastInsertId();$s=$pdo->prepare('INSERT INTO purchase_request_items(purchase_request_id,description,unit_code,requested_qty,estimated_unit_cost,cost_code_id) VALUES (?,?,?,?,?,?)');foreach($lines as $l)$s->execute([$requestId,$l[0],'وحدة',$l[1],$l[2],$l[3]]);$pdo->commit();audit('purchase_request.create','purchase_request',(string)$requestId,['request_no'=>$no]);flash('success','تم حفظ طلب الشراء: '.$no);
 }elseif(in_array($action,['submit','approve','reject'],true)){$id=(int)$_POST['id'];if($action==='submit'){$s=$pdo->prepare("UPDATE purchase_requests SET status='submitted' WHERE id=? AND company_id=? AND status='draft'");$s->execute([$id,$companyId]);}elseif($action==='approve'){$s=$pdo->prepare("UPDATE purchase_requests SET status='approved',approved_by=?,approved_at=NOW() WHERE id=? AND company_id=? AND status='submitted'");$s->execute([$userId,$id,$companyId]);}else{$s=$pdo->prepare("UPDATE purchase_requests SET status='rejected',approved_by=?,approved_at=NOW() WHERE id=? AND company_id=? AND status='submitted'");$s->execute([$userId,$id,$companyId]);}if(!$s->rowCount())throw new RuntimeException('تعذر تغيير حالة الطلب.');audit('purchase_request.'.$action,'purchase_request',(string)$id);flash('success','تم تحديث حالة طلب الشراء.');}
 }catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash('error',$e->getMessage());}redirect('procurement.php');}
$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 id,code,name_ar FROM cost_codes WHERE company_id=? AND is_active=1 AND is_postable=1 ORDER BY code");$codes->execute([$companyId]);$codes=$codes->fetchAll();$requests=$pdo->prepare("SELECT pr.*,p.name_ar project_name,u.full_name requester,(SELECT SUM(pri.requested_qty*pri.estimated_unit_cost) FROM purchase_request_items pri WHERE pri.purchase_request_id=pr.id) estimated_total FROM purchase_requests pr JOIN users u ON u.id=pr.requested_by LEFT JOIN projects p ON p.id=pr.project_id WHERE pr.company_id=? ORDER BY pr.id DESC");$requests->execute([$companyId]);$requests=$requests->fetchAll();
render_header('procurement','طلبات الشراء','دورة الطلب الداخلي قبل طلب العرض وأمر الشراء.');?>
<details class="panel quick-add" open><summary>＋ طلب شراء</summary><form method="post" id="requestForm"><?= csrf_field() ?><input type="hidden" name="action" value="request_create"><div class="form-grid"><label>المشروع<select name="project_id"><option value="0">عام</option><?php foreach($projects as $p):?><option value="<?= (int)$p['id'] ?>"><?= e($p['project_no'].' — '.$p['name_ar']) ?></option><?php endforeach;?></select></label><label>تاريخ الطلب<input type="date" name="request_date" value="<?= date('Y-m-d') ?>"></label><label>مطلوب قبل<input type="date" name="required_by_date"></label><label>الأولوية<select name="priority"><option value="normal">عادية</option><option value="high">عالية</option><option value="urgent">عاجلة</option><option value="low">منخفضة</option></select></label><label class="wide">الغرض<input name="purpose"></label></div><div class="responsive-table"><table id="requestLines"><thead><tr><th>الوصف</th><th>الكمية</th><th>التكلفة التقديرية</th><th>كود التكلفة</th><th></th></tr></thead><tbody><tr><td><input name="description[]" required></td><td><input type="number" step="0.0001" min="0.0001" name="qty[]" value="1"></td><td><input type="number" step="0.0001" min="0" name="estimated_cost[]" value="0"></td><td><select name="cost_code_id[]"><option value="0">—</option><?php foreach($codes as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['code'].' — '.$c['name_ar']) ?></option><?php endforeach;?></select></td><td><button type="button" onclick="this.closest('tr').remove()">×</button></td></tr></tbody></table></div><button type="button" id="addRequestLine" class="secondary-btn">إضافة بند</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><th>التقديري</th><th>الحالة</th><th>الإجراء</th></tr></thead><tbody><?php foreach($requests as $r):?><tr><td><?= e($r['request_no']) ?></td><td><?= e($r['project_name']?:'عام') ?></td><td><?= e($r['requester']) ?></td><td><?= e($r['request_date']) ?></td><td><?= e($r['priority']) ?></td><td><?= number_format((float)$r['estimated_total'],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="submit"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button>تقديم</button></form><?php elseif($r['status']==='submitted'):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="approve"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button>اعتماد</button></form><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="reject"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button>رفض</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<template id="requestTemplate"><tr><td><input name="description[]" required></td><td><input type="number" step="0.0001" min="0.0001" name="qty[]" value="1"></td><td><input type="number" step="0.0001" min="0" name="estimated_cost[]" value="0"></td><td><select name="cost_code_id[]"><option value="0">—</option><?php foreach($codes as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['code'].' — '.$c['name_ar']) ?></option><?php endforeach;?></select></td><td><button type="button" onclick="this.closest('tr').remove()">×</button></td></tr></template><script>addRequestLine.onclick=()=>document.querySelector('#requestLines tbody').append(requestTemplate.content.cloneNode(true));</script>
<?php render_footer();
