<?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==='supplier_create'){
   $code=trim((string)($_POST['partner_code']??''));$name=trim((string)($_POST['supplier_name']??''));if(!$code||!$name)throw new RuntimeException('كود المورد واسمه مطلوبان.');
   $pdo->beginTransaction();$s=$pdo->prepare("INSERT INTO business_partners(company_id,partner_code,legal_name_ar,partner_kind,commercial_registration_no,vat_registration_no,country_code,city,phone,email,status,created_at,updated_at) VALUES (?,?,?,'organization',?,?, 'SA',?,?,?,'active',NOW(),NOW())");
   $s->execute([$companyId,$code,$name,trim((string)($_POST['cr_no']??''))?:null,trim((string)($_POST['vat_no']??''))?:null,trim((string)($_POST['city']??''))?:null,trim((string)($_POST['phone']??''))?:null,trim((string)($_POST['email']??''))?:null]);
   $partnerId=(int)$pdo->lastInsertId();$pdo->prepare("INSERT INTO suppliers(partner_id,qualification_status,is_active) VALUES (?,'qualified',1)")->execute([$partnerId]);$supplierId=(int)$pdo->lastInsertId();$pdo->commit();audit('supplier.create','supplier',(string)$supplierId);flash('success','تمت إضافة المورد.');
  }elseif($action==='po_create'){
   $supplierId=(int)($_POST['supplier_id']??0);$projectId=(int)($_POST['project_id']??0);$costCodeId=(int)($_POST['cost_code_id']??0);$date=(string)($_POST['order_date']??'');$descriptions=$_POST['item_description']??[];$qtys=$_POST['qty']??[];$prices=$_POST['unit_price']??[];$taxPcts=$_POST['tax_pct']??[];
   if(!$supplierId||!$date)throw new RuntimeException('المورد وتاريخ الأمر مطلوبان.');$lines=[];$subtotal=0;$taxTotal=0;
   foreach($descriptions as $i=>$description){$description=trim((string)$description);$qty=round((float)($qtys[$i]??0),4);$price=round((float)($prices[$i]??0),4);$taxPct=max(0,(float)($taxPcts[$i]??15));if(!$description||$qty<=0||$price<0)continue;$base=round($qty*$price,2);$tax=round($base*$taxPct/100,2);$lines[]=[$description,$qty,$price,$tax,$base+$tax];$subtotal+=$base;$taxTotal+=$tax;}
   if(!$lines)throw new RuntimeException('أضف بندًا واحدًا صحيحًا على الأقل.');$pdo->beginTransaction();$currencyId=(int)scalar('SELECT base_currency_id FROM companies WHERE id=?',[$companyId]);$poNo='PO-'.date('Ym',strtotime($date)).'-'.str_pad((string)((int)scalar('SELECT COUNT(*)+1 FROM purchase_orders WHERE company_id=?',[$companyId])),5,'0',STR_PAD_LEFT);
   $s=$pdo->prepare("INSERT INTO purchase_orders(company_id,branch_id,project_id,supplier_id,po_no,order_date,expected_delivery_date,currency_id,subtotal,tax_amount,total_amount,payment_terms,status,created_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?, 'draft',?,NOW(),NOW())");
   $s->execute([$companyId,(int)user()['branch_id'],$projectId?:null,$supplierId,$poNo,$date,($_POST['expected_delivery_date']??'')?:null,$currencyId,$subtotal,$taxTotal,$subtotal+$taxTotal,trim((string)($_POST['payment_terms']??''))?:null,$userId]);$poId=(int)$pdo->lastInsertId();
   $s=$pdo->prepare('INSERT INTO purchase_order_items(purchase_order_id,description,unit_code,ordered_qty,unit_price,tax_amount,total_amount,cost_code_id) VALUES (?,?,?,?,?,?,?,?)');foreach($lines as $line)$s->execute([$poId,$line[0],'وحدة',$line[1],$line[2],$line[3],$line[4],$costCodeId?:null]);
   $pdo->commit();audit('purchase_order.create','purchase_order',(string)$poId,['po_no'=>$poNo]);flash('success','تم حفظ أمر الشراء كمسودة: '.$poNo);
  }elseif(in_array($action,['approve','send'],true)){
   $id=(int)($_POST['id']??0);if($action==='approve'){$s=$pdo->prepare("UPDATE purchase_orders SET status='approved',approved_by=?,approved_at=NOW() WHERE id=? AND company_id=? AND status='draft'");$s->execute([$userId,$id,$companyId]);}else{$s=$pdo->prepare("UPDATE purchase_orders SET status='sent' WHERE id=? AND company_id=? AND status='approved'");$s->execute([$id,$companyId]);}if(!$s->rowCount())throw new RuntimeException('تعذر تغيير حالة الأمر.');audit('purchase_order.'.$action,'purchase_order',(string)$id);flash('success',$action==='approve'?'تم اعتماد أمر الشراء.':'تم تحويل الأمر إلى حالة مرسل.');
  }
 }catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash('error',$e instanceof PDOException?'البيانات مكررة أو غير متوافقة مع السجلات الحالية.':$e->getMessage());}
 redirect('purchases.php');
}
$suppliers=$pdo->prepare("SELECT s.id,bp.partner_code,bp.legal_name_ar FROM suppliers s JOIN business_partners bp ON bp.id=s.partner_id WHERE bp.company_id=? AND bp.status='active' AND bp.deleted_at IS NULL AND s.is_active=1 ORDER BY bp.legal_name_ar");$suppliers->execute([$companyId]);$suppliers=$suppliers->fetchAll();
$projects=$pdo->prepare("SELECT id,project_no,name_ar FROM projects WHERE company_id=? AND status='active' AND deleted_at IS NULL ORDER BY project_no");$projects->execute([$companyId]);$projects=$projects->fetchAll();$costCodes=$pdo->prepare("SELECT id,code,name_ar FROM cost_codes WHERE company_id=? AND is_active=1 AND is_postable=1 ORDER BY code");$costCodes->execute([$companyId]);$costCodes=$costCodes->fetchAll();
$orders=$pdo->prepare("SELECT po.*,bp.legal_name_ar supplier_name,p.name_ar project_name FROM purchase_orders po JOIN suppliers s ON s.id=po.supplier_id JOIN business_partners bp ON bp.id=s.partner_id LEFT JOIN projects p ON p.id=po.project_id WHERE po.company_id=? ORDER BY po.id DESC LIMIT 100");$orders->execute([$companyId]);$orders=$orders->fetchAll();
render_header('purchases','المشتريات وأوامر الشراء','إدارة الموردين وأوامر الشراء المرتبطة بالمشاريع.');?><section class="panel form-card"><label>كود التكلفة لأمر الشراء<select name="cost_code_id" form="poForm"><option value="0">بدون كود</option><?php foreach($costCodes as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['code'].' — '.$c['name_ar']) ?></option><?php endforeach;?></select></label></section>
<details class="panel quick-add"><summary>＋ إضافة مورد</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="supplier_create"><div class="form-grid"><label>كود المورد<input name="partner_code" required></label><label>اسم المورد<input name="supplier_name" required></label><label>السجل التجاري<input name="cr_no"></label><label>الرقم الضريبي<input name="vat_no"></label><label>المدينة<input name="city"></label><label>الهاتف<input name="phone"></label><label>البريد<input type="email" name="email"></label></div><button class="primary-btn">حفظ المورد</button></form></details>
<details class="panel quick-add" open><summary>＋ إنشاء أمر شراء</summary><form method="post" id="poForm"><?= csrf_field() ?><input type="hidden" name="action" value="po_create"><div class="form-grid"><label>المورد<select name="supplier_id" required><option value="">اختر المورد</option><?php foreach($suppliers as $s):?><option value="<?= (int)$s['id'] ?>"><?= e($s['partner_code'].' — '.$s['legal_name_ar']) ?></option><?php endforeach;?></select></label><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="order_date" value="<?= date('Y-m-d') ?>" required></label><label>التسليم المتوقع<input type="date" name="expected_delivery_date"></label><label class="wide">شروط الدفع<input name="payment_terms"></label></div><div class="responsive-table"><table id="poLines"><thead><tr><th>وصف البند</th><th>الكمية</th><th>سعر الوحدة</th><th>الضريبة %</th><th></th></tr></thead><tbody><tr><td><input name="item_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="unit_price[]" value="0"></td><td><input type="number" step="0.01" min="0" name="tax_pct[]" value="15"></td><td><button type="button" onclick="this.closest('tr').remove()">×</button></td></tr></tbody></table></div><button type="button" class="secondary-btn" id="addPoLine">إضافة بند</button> <button class="primary-btn">حفظ كمسودة</button></form></details>
<section class="panel data-card"><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($orders as $o):?><tr><td><?= e($o['po_no']) ?></td><td><?= e($o['supplier_name']) ?></td><td><?= e($o['project_name']?:'عام') ?></td><td><?= e($o['order_date']) ?></td><td><?= number_format((float)$o['total_amount'],2) ?></td><td><span class="chip"><?= e($o['status']) ?></span></td><td><?php if($o['status']==='draft'):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="approve"><input type="hidden" name="id" value="<?= (int)$o['id'] ?>"><button>اعتماد</button></form><?php elseif($o['status']==='approved'):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="send"><input type="hidden" name="id" value="<?= (int)$o['id'] ?>"><button>إرسال</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<template id="poTemplate"><tr><td><input name="item_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="unit_price[]" value="0"></td><td><input type="number" step="0.01" min="0" name="tax_pct[]" value="15"></td><td><button type="button" onclick="this.closest('tr').remove()">×</button></td></tr></template><script>addPoLine.onclick=()=>document.querySelector('#poLines tbody').append(poTemplate.content.cloneNode(true));</script>
<?php render_footer();
