<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_permission('inventory.transactions.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==='warehouse_create'){$code=trim((string)$_POST['code']);$name=trim((string)$_POST['name_ar']);if(!$code||!$name)throw new RuntimeException('كود المستودع واسمه مطلوبان.');$s=$pdo->prepare("INSERT INTO warehouses(company_id,branch_id,project_id,code,name_ar,warehouse_type,location_text,is_active,created_at,updated_at) VALUES (?,?,?,?,?,?,?,1,NOW(),NOW())");$s->execute([$companyId,(int)user()['branch_id'],(int)($_POST['project_id']??0)?:null,$code,$name,(string)($_POST['warehouse_type']??'central'),trim((string)($_POST['location_text']??''))?:null]);audit('warehouse.create','warehouse',(string)$pdo->lastInsertId());flash('success','تم إنشاء المستودع.');
  }elseif($action==='item_create'){$code=trim((string)$_POST['item_code']);$name=trim((string)$_POST['item_name']);if(!$code||!$name)throw new RuntimeException('كود الصنف واسمه مطلوبان.');$s=$pdo->prepare("INSERT INTO items(company_id,item_code,name_ar,item_type,base_unit_code,purchase_unit_code,valuation_method,is_active,created_at,updated_at) VALUES (?,?,?,?,?,?,'weighted_average',1,NOW(),NOW())");$s->execute([$companyId,$code,$name,(string)($_POST['item_type']??'inventory'),trim((string)($_POST['unit_code']??'وحدة')),trim((string)($_POST['unit_code']??'وحدة'))]);audit('item.create','item',(string)$pdo->lastInsertId());flash('success','تم إنشاء الصنف.');
  }elseif($action==='receive'){
   $poId=(int)($_POST['po_id']??0);$warehouseId=(int)($_POST['warehouse_id']??0);$date=(string)($_POST['receipt_date']??'');if(!$poId||!$warehouseId||!$date)throw new RuntimeException('أمر الشراء والمستودع والتاريخ مطلوبة.');
   $poS=$pdo->prepare("SELECT * FROM purchase_orders WHERE id=? AND company_id=? AND status IN ('approved','sent','partially_received') FOR UPDATE");$pdo->beginTransaction();$poS->execute([$poId,$companyId]);$po=$poS->fetch();if(!$po)throw new RuntimeException('أمر الشراء غير متاح للاستلام.');
   $poItemIds=$_POST['po_item_id']??[];$itemIds=$_POST['item_id']??[];$qtys=$_POST['received_qty']??[];$lines=[];
   foreach($poItemIds as $i=>$poItemId){$itemId=(int)($itemIds[$i]??0);$qty=round((float)($qtys[$i]??0),4);if(!$itemId||$qty<=0)continue;$s=$pdo->prepare('SELECT * FROM purchase_order_items WHERE id=? AND purchase_order_id=?');$s->execute([(int)$poItemId,$poId]);$row=$s->fetch();if(!$row)throw new RuntimeException('بند شراء غير صالح.');$remaining=(float)$row['ordered_qty']-(float)$row['received_qty'];if($qty>$remaining+0.00001)throw new RuntimeException('كمية الاستلام تتجاوز الكمية المتبقية.');$lines[]=[$row,$itemId,$qty];}
   if(!$lines)throw new RuntimeException('أدخل كمية مستلمة لصنف واحد على الأقل.');$receiptNo='GR-'.date('Ym',strtotime($date)).'-'.str_pad((string)((int)scalar('SELECT COUNT(*)+1 FROM goods_receipts WHERE company_id=?',[$companyId])),5,'0',STR_PAD_LEFT);
   $s=$pdo->prepare("INSERT INTO goods_receipts(company_id,branch_id,project_id,warehouse_id,supplier_id,purchase_order_id,receipt_no,receipt_date,supplier_delivery_note,inspection_status,status,received_by,approved_by,created_at) VALUES (?,?,?,?,?,?,?,?,?,'accepted','posted',?,?,NOW())");$s->execute([$companyId,(int)$po['branch_id'],$po['project_id'],$warehouseId,$po['supplier_id'],$poId,$receiptNo,$date,trim((string)($_POST['delivery_note']??''))?:null,$userId,$userId]);$receiptId=(int)$pdo->lastInsertId();
   $txNo='ST-'.$receiptNo;$s=$pdo->prepare("INSERT INTO stock_transactions(company_id,branch_id,transaction_no,transaction_type,transaction_date,to_warehouse_id,project_id,source_type,source_id,status,created_by,approved_by,created_at) VALUES (?,?,?,'receipt',?,?,?,?,?,'posted',?,?,NOW())");$s->execute([$companyId,(int)$po['branch_id'],$txNo,$date,$warehouseId,$po['project_id'],'goods_receipt',$receiptId,$userId,$userId]);$txId=(int)$pdo->lastInsertId();
   $gr=$pdo->prepare('INSERT INTO goods_receipt_items(goods_receipt_id,purchase_order_item_id,item_id,description,received_qty,accepted_qty,unit_code,unit_cost) VALUES (?,?,?,?,?,?,?,?)');$st=$pdo->prepare('INSERT INTO stock_transaction_lines(stock_transaction_id,item_id,quantity,unit_cost,total_cost) VALUES (?,?,?,?,?)');
   foreach($lines as [$row,$itemId,$qty]){$cost=(float)$row['unit_price'];$gr->execute([$receiptId,$row['id'],$itemId,$row['description'],$qty,$qty,$row['unit_code'],$cost]);$st->execute([$txId,$itemId,$qty,$cost,round($qty*$cost,2)]);$pdo->prepare('UPDATE purchase_order_items SET received_qty=received_qty+?,item_id=COALESCE(item_id,?) WHERE id=?')->execute([$qty,$itemId,$row['id']]);$old=$pdo->prepare("SELECT quantity_on_hand,average_unit_cost FROM stock_balances WHERE warehouse_id=? AND item_id=? AND lot_no='' FOR UPDATE");$old->execute([$warehouseId,$itemId]);$bal=$old->fetch();if($bal){$oldQty=(float)$bal['quantity_on_hand'];$newQty=$oldQty+$qty;$avg=$newQty>0?(($oldQty*(float)$bal['average_unit_cost'])+($qty*$cost))/$newQty:$cost;$pdo->prepare("UPDATE stock_balances SET quantity_on_hand=?,average_unit_cost=? WHERE warehouse_id=? AND item_id=? AND lot_no=''")->execute([$newQty,$avg,$warehouseId,$itemId]);}else{$pdo->prepare("INSERT INTO stock_balances(warehouse_id,item_id,lot_no,quantity_on_hand,average_unit_cost) VALUES (?,?,'',?,?)")->execute([$warehouseId,$itemId,$qty,$cost]);}}
   $remaining=(int)scalar('SELECT COUNT(*) FROM purchase_order_items WHERE purchase_order_id=? AND received_qty<ordered_qty',[$poId]);$pdo->prepare("UPDATE purchase_orders SET status=? WHERE id=?")->execute([$remaining?'partially_received':'received',$poId]);$pdo->commit();audit('goods_receipt.post','goods_receipt',(string)$receiptId,['receipt_no'=>$receiptNo]);flash('success','تم ترحيل الاستلام وتحديث المخزون: '.$receiptNo);
  }
 }catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash('error',$e instanceof PDOException?'البيانات مكررة أو مرتبطة بسجل آخر.':$e->getMessage());}redirect('inventory.php');
}
$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();
$warehouses=$pdo->prepare('SELECT * FROM warehouses WHERE company_id=? AND is_active=1 ORDER BY code');$warehouses->execute([$companyId]);$warehouses=$warehouses->fetchAll();
$items=$pdo->prepare("SELECT * FROM items WHERE company_id=? AND is_active=1 AND deleted_at IS NULL ORDER BY item_code");$items->execute([$companyId]);$items=$items->fetchAll();
$pos=$pdo->prepare("SELECT po.id,po.po_no,bp.legal_name_ar supplier_name FROM purchase_orders po JOIN suppliers s ON s.id=po.supplier_id JOIN business_partners bp ON bp.id=s.partner_id WHERE po.company_id=? AND po.status IN ('approved','sent','partially_received') ORDER BY po.id DESC");$pos->execute([$companyId]);$pos=$pos->fetchAll();
$selectedPo=(int)($_GET['po_id']??0);$poLines=[];if($selectedPo){$s=$pdo->prepare('SELECT * FROM purchase_order_items WHERE purchase_order_id=? AND received_qty<ordered_qty ORDER BY id');$s->execute([$selectedPo]);$poLines=$s->fetchAll();}
$balances=$pdo->prepare("SELECT w.name_ar warehouse_name,i.item_code,i.name_ar,sb.quantity_on_hand,sb.quantity_reserved,sb.average_unit_cost FROM stock_balances sb JOIN warehouses w ON w.id=sb.warehouse_id JOIN items i ON i.id=sb.item_id WHERE w.company_id=? ORDER BY w.code,i.item_code");$balances->execute([$companyId]);$balances=$balances->fetchAll();
render_header('inventory','المخزون واستلام المواد','المستودعات والأصناف واستلام أوامر الشراء وتحديث الأرصدة.');?>
<div class="settings-grid"><details class="panel quick-add"><summary>＋ مستودع جديد</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="warehouse_create"><label>الكود<input name="code" required></label><label>الاسم<input name="name_ar" required></label><label>النوع<select name="warehouse_type"><option value="central">مركزي</option><option value="project">مشروع</option><option value="transit">تحت النقل</option></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 name="location_text"></label><button class="primary-btn">حفظ</button></form></details><details class="panel quick-add"><summary>＋ صنف جديد</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="item_create"><label>الكود<input name="item_code" required></label><label>الاسم<input name="item_name" required></label><label>النوع<select name="item_type"><option value="inventory">مخزني</option><option value="non_inventory">غير مخزني</option><option value="service">خدمة</option></select></label><label>الوحدة<input name="unit_code" value="وحدة"></label><button class="primary-btn">حفظ</button></form></details></div>
<section class="panel form-card"><form method="get"><label>اختر أمر الشراء للاستلام<select name="po_id" onchange="this.form.submit()"><option value="0">اختر...</option><?php foreach($pos as $po):?><option value="<?= (int)$po['id'] ?>" <?= $selectedPo===(int)$po['id']?'selected':'' ?>><?= e($po['po_no'].' — '.$po['supplier_name']) ?></option><?php endforeach;?></select></label></form><?php if($selectedPo&&$poLines):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="receive"><input type="hidden" name="po_id" value="<?= $selectedPo ?>"><div class="form-grid"><label>المستودع<select name="warehouse_id" required><?php foreach($warehouses as $w):?><option value="<?= (int)$w['id'] ?>"><?= e($w['code'].' — '.$w['name_ar']) ?></option><?php endforeach;?></select></label><label>تاريخ الاستلام<input type="date" name="receipt_date" value="<?= date('Y-m-d') ?>" required></label><label>إذن تسليم المورد<input name="delivery_note"></label></div><div class="responsive-table"><table><thead><tr><th>بند الأمر</th><th>المتبقي</th><th>الصنف</th><th>المستلم الآن</th></tr></thead><tbody><?php foreach($poLines as $l):$remain=(float)$l['ordered_qty']-(float)$l['received_qty'];?><tr><td><?= e($l['description']) ?><input type="hidden" name="po_item_id[]" value="<?= (int)$l['id'] ?>"></td><td><?= number_format($remain,4) ?></td><td><select name="item_id[]"><option value="0">اختر الصنف</option><?php foreach($items as $i):?><option value="<?= (int)$i['id'] ?>"><?= e($i['item_code'].' — '.$i['name_ar']) ?></option><?php endforeach;?></select></td><td><input type="number" step="0.0001" min="0" max="<?= $remain ?>" name="received_qty[]" value="0"></td></tr><?php endforeach;?></tbody></table></div><button class="primary-btn">ترحيل الاستلام للمخزون</button></form><?php endif;?></section>
<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></tr></thead><tbody><?php foreach($balances as $b):?><tr><td><?= e($b['warehouse_name']) ?></td><td><?= e($b['item_code'].' — '.$b['name_ar']) ?></td><td><?= number_format((float)$b['quantity_on_hand'],4) ?></td><td><?= number_format((float)$b['quantity_reserved'],4) ?></td><td><?= number_format((float)$b['average_unit_cost'],4) ?></td><td><?= number_format((float)$b['quantity_on_hand']*(float)$b['average_unit_cost'],2) ?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php render_footer();
