<?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'];$branchId=(int)user()['branch_id'];
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();try{$action=(string)($_POST['action']??'');
 if($action==='rfq_create'){$requestId=(int)($_POST['request_id']??0);$supplierIds=array_values(array_unique(array_filter(array_map('intval',$_POST['supplier_ids']??[]))));if(!$requestId||!$supplierIds)throw new RuntimeException('اختر طلب شراء معتمدًا وموردًا واحدًا على الأقل.');$request=$pdo->prepare("SELECT * FROM purchase_requests WHERE id=? AND company_id=? AND status='approved'");$request->execute([$requestId,$companyId]);$request=$request->fetch();if(!$request)throw new RuntimeException('طلب الشراء غير متاح أو غير معتمد.');$items=$pdo->prepare('SELECT * FROM purchase_request_items WHERE purchase_request_id=?');$items->execute([$requestId]);$items=$items->fetchAll();if(!$items)throw new RuntimeException('طلب الشراء لا يحتوي على بنود.');$currencyId=(int)scalar('SELECT base_currency_id FROM companies WHERE id=?',[$companyId]);$no='RFQ-'.date('Ym').'-'.str_pad((string)((int)scalar('SELECT COUNT(*)+1 FROM requests_for_quotation WHERE company_id=?',[$companyId])),5,'0',STR_PAD_LEFT);$pdo->beginTransaction();$s=$pdo->prepare("INSERT INTO requests_for_quotation(company_id,project_id,rfq_no,issue_date,closing_date,currency_id,status,created_by,created_at) VALUES (?,?,?,?,?,?,'issued',?,NOW())");$s->execute([$companyId,$request['project_id'],$no,$_POST['issue_date'],($_POST['closing_date']??'')?:null,$currencyId,$userId]);$rfqId=(int)$pdo->lastInsertId();$s=$pdo->prepare('INSERT INTO rfq_items(rfq_id,purchase_request_item_id,item_id,description,unit_code,quantity,required_by_date) VALUES (?,?,?,?,?,?,?)');foreach($items as $i)$s->execute([$rfqId,$i['id'],$i['item_id'],$i['description'],$i['unit_code'],(float)$i['approved_qty']>0?$i['approved_qty']:$i['requested_qty'],$request['required_by_date']]);$s=$pdo->prepare("INSERT INTO rfq_suppliers(rfq_id,supplier_id,invited_at,response_status) VALUES (?,?,NOW(),'invited')");foreach($supplierIds as $sid)$s->execute([$rfqId,$sid]);$pdo->commit();audit('rfq.create','request_for_quotation',(string)$rfqId,['rfq_no'=>$no]);flash('success','تم إصدار طلب عرض الأسعار: '.$no);
 }elseif($action==='quotation_create'){$rfqId=(int)($_POST['rfq_id']??0);$supplierId=(int)($_POST['supplier_id']??0);$invited=(int)scalar('SELECT COUNT(*) FROM rfq_suppliers rs JOIN requests_for_quotation r ON r.id=rs.rfq_id WHERE rs.rfq_id=? AND rs.supplier_id=? AND r.company_id=?',[$rfqId,$supplierId,$companyId]);if(!$invited)throw new RuntimeException('المورد غير مدعو إلى طلب العرض المحدد.');if((int)scalar('SELECT COUNT(*) FROM supplier_quotations WHERE rfq_id=? AND supplier_id=?',[$rfqId,$supplierId]))throw new RuntimeException('تم تسجيل عرض لهذا المورد مسبقًا.');$rfqItems=$pdo->prepare('SELECT * FROM rfq_items WHERE rfq_id=? ORDER BY id');$rfqItems->execute([$rfqId]);$rfqItems=$rfqItems->fetchAll();$prices=$_POST['unit_price']??[];$taxPcts=$_POST['tax_pct']??[];$lines=[];$subtotal=0;$taxTotal=0;foreach($rfqItems as $i=>$line){$price=round((float)($prices[$i]??0),4);$taxPct=max(0,(float)($taxPcts[$i]??15));if($price<0)throw new RuntimeException('سعر الوحدة غير صحيح.');$base=round((float)$line['quantity']*$price,2);$tax=round($base*$taxPct/100,2);$lines[]=[$line,$price,$tax,$base+$tax];$subtotal+=$base;$taxTotal+=$tax;}$currencyId=(int)scalar('SELECT currency_id FROM requests_for_quotation WHERE id=? AND company_id=?',[$rfqId,$companyId]);$pdo->beginTransaction();$s=$pdo->prepare("INSERT INTO supplier_quotations(rfq_id,supplier_id,quotation_no,quotation_date,valid_until,currency_id,subtotal,tax_amount,total_amount,delivery_days,payment_terms,status,created_by,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,'received',?,NOW())");$s->execute([$rfqId,$supplierId,trim((string)($_POST['quotation_no']??''))?:null,$_POST['quotation_date'],($_POST['valid_until']??'')?:null,$currencyId,$subtotal,$taxTotal,$subtotal+$taxTotal,(int)($_POST['delivery_days']??0)?:null,trim((string)($_POST['payment_terms']??''))?:null,$userId]);$quoteId=(int)$pdo->lastInsertId();$s=$pdo->prepare('INSERT INTO supplier_quotation_items(supplier_quotation_id,rfq_item_id,item_id,description,quantity,unit_code,unit_price,tax_amount,total_amount) VALUES (?,?,?,?,?,?,?,?,?)');foreach($lines as [$line,$price,$tax,$total])$s->execute([$quoteId,$line['id'],$line['item_id'],$line['description'],$line['quantity'],$line['unit_code'],$price,$tax,$total]);$pdo->prepare("UPDATE rfq_suppliers SET response_status='responded',responded_at=NOW() WHERE rfq_id=? AND supplier_id=?")->execute([$rfqId,$supplierId]);$pdo->commit();audit('supplier_quotation.create','supplier_quotation',(string)$quoteId);flash('success','تم تسجيل عرض المورد وإضافته للمقارنة.');
 }elseif($action==='award'){$quoteId=(int)($_POST['quote_id']??0);$q=$pdo->prepare("SELECT q.*,r.company_id,r.project_id,r.rfq_no FROM supplier_quotations q JOIN requests_for_quotation r ON r.id=q.rfq_id WHERE q.id=? AND r.company_id=? AND r.status IN ('issued','closed','evaluated')");$q->execute([$quoteId,$companyId]);$q=$q->fetch();if(!$q)throw new RuntimeException('العرض غير متاح للترسية.');if((int)scalar('SELECT COUNT(*) FROM purchase_orders WHERE supplier_quotation_id=?',[$quoteId]))throw new RuntimeException('سبق إنشاء أمر شراء من هذا العرض.');$lines=$pdo->prepare('SELECT qi.*,ri.purchase_request_item_id,pri.cost_code_id,pri.budget_line_id FROM supplier_quotation_items qi LEFT JOIN rfq_items ri ON ri.id=qi.rfq_item_id LEFT JOIN purchase_request_items pri ON pri.id=ri.purchase_request_item_id WHERE qi.supplier_quotation_id=?');$lines->execute([$quoteId]);$lines=$lines->fetchAll();if(!$lines)throw new RuntimeException('العرض لا يحتوي على بنود.');$date=date('Y-m-d');$poNo='PO-'.date('Ym').'-'.str_pad((string)((int)scalar('SELECT COUNT(*)+1 FROM purchase_orders WHERE company_id=?',[$companyId])),5,'0',STR_PAD_LEFT);$pdo->beginTransaction();$s=$pdo->prepare("INSERT INTO purchase_orders(company_id,branch_id,project_id,supplier_id,supplier_quotation_id,po_no,order_date,expected_delivery_date,currency_id,exchange_rate,subtotal,discount_amount,tax_amount,total_amount,payment_terms,status,created_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'draft',?,NOW(),NOW())");$expected=$q['delivery_days']?date('Y-m-d',strtotime('+'.(int)$q['delivery_days'].' days')):null;$s->execute([$companyId,$branchId,$q['project_id'],$q['supplier_id'],$quoteId,$poNo,$date,$expected,$q['currency_id'],$q['exchange_rate'],$q['subtotal'],$q['discount_amount'],$q['tax_amount'],$q['total_amount'],$q['payment_terms'],$userId]);$poId=(int)$pdo->lastInsertId();$s=$pdo->prepare('INSERT INTO purchase_order_items(purchase_order_id,purchase_request_item_id,item_id,description,unit_code,ordered_qty,unit_price,discount_amount,tax_code_id,tax_amount,total_amount,cost_code_id,budget_line_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');foreach($lines as $l)$s->execute([$poId,$l['purchase_request_item_id'],$l['item_id'],$l['description'],$l['unit_code'],$l['quantity'],$l['unit_price'],$l['discount_amount'],$l['tax_code_id'],$l['tax_amount'],$l['total_amount'],$l['cost_code_id'],$l['budget_line_id']]);$pdo->prepare("UPDATE supplier_quotations SET status=CASE WHEN id=? THEN 'selected' ELSE 'rejected' END WHERE rfq_id=?")->execute([$quoteId,$q['rfq_id']]);$pdo->prepare("UPDATE requests_for_quotation SET status='awarded' WHERE id=?")->execute([$q['rfq_id']]);$pdo->prepare("UPDATE purchase_requests pr SET pr.status='ordered' WHERE pr.id IN (SELECT DISTINCT pri.purchase_request_id FROM rfq_items ri JOIN purchase_request_items pri ON pri.id=ri.purchase_request_item_id WHERE ri.rfq_id=?)")->execute([$q['rfq_id']]);$pdo->commit();audit('rfq.award','supplier_quotation',(string)$quoteId,['purchase_order'=>$poNo]);flash('success','تمت الترسية وإنشاء أمر الشراء: '.$poNo);
 }}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash('error',$e instanceof PDOException?'تعذر الحفظ؛ تحقق من عدم تكرار العرض وصحة البيانات.':$e->getMessage());}redirect('quotations.php');}
$requests=$pdo->prepare("SELECT pr.id,pr.request_no,p.name_ar project_name FROM purchase_requests pr LEFT JOIN projects p ON p.id=pr.project_id WHERE pr.company_id=? AND pr.status='approved' AND NOT EXISTS(SELECT 1 FROM rfq_items ri JOIN purchase_request_items pri ON pri.id=ri.purchase_request_item_id WHERE pri.purchase_request_id=pr.id) ORDER BY pr.id DESC");$requests->execute([$companyId]);$requests=$requests->fetchAll();$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();$rfqs=$pdo->prepare("SELECT r.*,p.name_ar project_name,(SELECT COUNT(*) FROM rfq_suppliers rs WHERE rs.rfq_id=r.id) suppliers_count FROM requests_for_quotation r LEFT JOIN projects p ON p.id=r.project_id WHERE r.company_id=? ORDER BY r.id DESC");$rfqs->execute([$companyId]);$rfqs=$rfqs->fetchAll();$openRfqs=array_values(array_filter($rfqs,fn($r)=>in_array($r['status'],['issued','closed','evaluated'],true)));$selectedRfq=(int)($_GET['rfq_id']??($openRfqs[0]['id']??0));$invited=[];$rfqItems=[];if($selectedRfq){$s=$pdo->prepare("SELECT s.id,bp.legal_name_ar FROM rfq_suppliers rs JOIN suppliers s ON s.id=rs.supplier_id JOIN business_partners bp ON bp.id=s.partner_id WHERE rs.rfq_id=? AND NOT EXISTS(SELECT 1 FROM supplier_quotations q WHERE q.rfq_id=rs.rfq_id AND q.supplier_id=rs.supplier_id)");$s->execute([$selectedRfq]);$invited=$s->fetchAll();$s=$pdo->prepare('SELECT * FROM rfq_items WHERE rfq_id=? ORDER BY id');$s->execute([$selectedRfq]);$rfqItems=$s->fetchAll();}$quotes=$pdo->prepare("SELECT q.*,r.rfq_no,r.status rfq_status,bp.legal_name_ar supplier_name,po.po_no FROM supplier_quotations q JOIN requests_for_quotation r ON r.id=q.rfq_id JOIN suppliers s ON s.id=q.supplier_id JOIN business_partners bp ON bp.id=s.partner_id LEFT JOIN purchase_orders po ON po.supplier_quotation_id=q.id WHERE r.company_id=? ORDER BY q.rfq_id DESC,q.total_amount ASC");$quotes->execute([$companyId]);$quotes=$quotes->fetchAll();
render_header('quotations','عروض أسعار الموردين','دعوة الموردين، مقارنة عروضهم، وترسية العرض الفائز.');?>
<details class="panel quick-add" open><summary>＋ إصدار طلب عرض أسعار</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="rfq_create"><div class="form-grid"><label>طلب الشراء المعتمد<select name="request_id" required><option value="">اختر الطلب</option><?php foreach($requests as $r):?><option value="<?= (int)$r['id'] ?>"><?= e($r['request_no'].' — '.($r['project_name']?:'عام')) ?></option><?php endforeach;?></select></label><label>تاريخ الإصدار<input type="date" name="issue_date" value="<?= date('Y-m-d') ?>" required></label><label>إغلاق استقبال العروض<input type="date" name="closing_date"></label><label class="wide">الموردون<select name="supplier_ids[]" multiple size="5" required><?php foreach($suppliers as $s):?><option value="<?= (int)$s['id'] ?>"><?= e($s['partner_code'].' — '.$s['legal_name_ar']) ?></option><?php endforeach;?></select><small>يمكن تحديد أكثر من مورد.</small></label></div><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></tr></thead><tbody><?php foreach($rfqs as $r):?><tr><td><?= e($r['rfq_no']) ?></td><td><?= e($r['project_name']?:'عام') ?></td><td><?= e($r['issue_date']) ?></td><td><?= e($r['closing_date']?:'—') ?></td><td><?= (int)$r['suppliers_count'] ?></td><td><span class="chip"><?= e($r['status']) ?></span></td><td><?php if(in_array($r['status'],['issued','closed','evaluated'],true)):?><a href="?rfq_id=<?= (int)$r['id'] ?>">تسجيل عرض</a><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php if($selectedRfq&&$rfqItems):?><details class="panel quick-add" open><summary>＋ تسجيل عرض مورد</summary><?php if($invited):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="quotation_create"><input type="hidden" name="rfq_id" value="<?= $selectedRfq ?>"><div class="form-grid"><label>المورد<select name="supplier_id" required><?php foreach($invited as $s):?><option value="<?= (int)$s['id'] ?>"><?= e($s['legal_name_ar']) ?></option><?php endforeach;?></select></label><label>رقم عرض المورد<input name="quotation_no"></label><label>تاريخ العرض<input type="date" name="quotation_date" value="<?= date('Y-m-d') ?>" required></label><label>صالح حتى<input type="date" name="valid_until"></label><label>مدة التوريد بالأيام<input type="number" min="0" name="delivery_days"></label><label>شروط الدفع<input name="payment_terms"></label></div><div class="responsive-table"><table><thead><tr><th>البند</th><th>الكمية</th><th>سعر الوحدة</th><th>الضريبة %</th></tr></thead><tbody><?php foreach($rfqItems as $i):?><tr><td><?= e($i['description']) ?></td><td><?= number_format((float)$i['quantity'],4) ?> <?= e($i['unit_code']) ?></td><td><input type="number" step="0.0001" min="0" name="unit_price[]" required></td><td><input type="number" step="0.01" min="0" name="tax_pct[]" value="15"></td></tr><?php endforeach;?></tbody></table></div><button class="primary-btn">حفظ العرض</button></form><?php else:?><p>سُجلت عروض جميع الموردين المدعوين لهذا الطلب.</p><?php endif;?></details><?php endif;?>
<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($quotes as $q):?><tr><td><?= e($q['rfq_no']) ?></td><td><?= e($q['supplier_name']) ?></td><td><?= e($q['quotation_no']?:'—') ?></td><td><?= number_format((float)$q['total_amount'],2) ?></td><td><?= $q['delivery_days']!==null?(int)$q['delivery_days'].' يوم':'—' ?></td><td><span class="chip"><?= e($q['status']) ?></span></td><td><?= e($q['po_no']?:'—') ?></td><td><?php if(in_array($q['rfq_status'],['issued','closed','evaluated'],true)):?><form method="post" onsubmit="return confirm('ترسية هذا العرض وإنشاء أمر شراء؟')"><?= csrf_field() ?><input type="hidden" name="action" value="award"><input type="hidden" name="quote_id" value="<?= (int)$q['id'] ?>"><button>ترسية</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php render_footer();
