<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_permission('contracts.manage');require __DIR__.'/app/layout.php';
$pdo=db();$companyId=company_id();$userId=(int)user()['id'];$currencyId=(int)scalar('SELECT base_currency_id FROM companies WHERE id=?',[$companyId]);
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();try{$action=(string)($_POST['action']??'');
 if($action==='tender_create'){$no=trim((string)($_POST['tender_no']??''));$title=trim((string)($_POST['title']??''));if(!$no||!$title)throw new RuntimeException('رقم المناقصة وعنوانها مطلوبان.');$s=$pdo->prepare("INSERT INTO tenders(company_id,branch_id,tender_no,title,customer_id,tender_type,submission_deadline,bid_valid_until,estimated_value,currency_id,bid_bond_required,bid_bond_amount,status,owner_user_id,created_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'draft',?,?,NOW(),NOW())");$s->execute([$companyId,(int)user()['branch_id'],$no,$title,(int)($_POST['customer_id']??0)?:null,(string)($_POST['tender_type']??'private'),($_POST['submission_deadline']??'')?:null,($_POST['bid_valid_until']??'')?:null,(float)($_POST['estimated_value']??0)?:null,$currencyId,isset($_POST['bid_bond_required'])?1:0,(float)($_POST['bid_bond_amount']??0),$userId,$userId]);audit('tender.create','tender',(string)$pdo->lastInsertId());flash('success','تم تسجيل المناقصة.');
 }elseif($action==='tender_status'){$id=(int)($_POST['id']??0);$status=(string)($_POST['status']??'');if(!in_array($status,['studying','priced','submitted','awarded','lost','cancelled'],true))throw new RuntimeException('الحالة غير صالحة.');$s=$pdo->prepare("UPDATE tenders SET status=? WHERE id=? AND company_id=? AND status NOT IN ('awarded','lost','cancelled')");$s->execute([$status,$id,$companyId]);if(!$s->rowCount())throw new RuntimeException('تعذر تحديث المناقصة.');audit('tender.status','tender',(string)$id,['status'=>$status]);flash('success','تم تحديث حالة المناقصة.');
 }elseif($action==='claim_create'){$projectId=(int)($_POST['project_id']??0);$no=trim((string)($_POST['claim_no']??''));$title=trim((string)($_POST['title']??''));if(!$projectId||!$no||!$title)throw new RuntimeException('المشروع ورقم المطالبة والعنوان مطلوبة.');if(!(int)scalar('SELECT COUNT(*) FROM projects WHERE id=? AND company_id=?',[$projectId,$companyId]))throw new RuntimeException('المشروع غير صالح.');$s=$pdo->prepare("INSERT INTO project_claims(project_id,contract_id,claim_no,title,claim_type,claimed_amount,claimed_days,submitted_on,status,created_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?, 'draft',?,NOW(),NOW())");$s->execute([$projectId,(int)($_POST['contract_id']??0)?:null,$no,$title,(string)($_POST['claim_type']??'cost'),round((float)($_POST['claimed_amount']??0),2),(int)($_POST['claimed_days']??0),($_POST['submitted_on']??'')?:null,$userId]);audit('project_claim.create','project_claim',(string)$pdo->lastInsertId());flash('success','تم تسجيل المطالبة.');
 }elseif($action==='claim_status'){$id=(int)($_POST['id']??0);$status=(string)($_POST['status']??'');if(!in_array($status,['submitted','under_review','negotiation','approved','partially_approved','rejected','withdrawn'],true))throw new RuntimeException('الحالة غير صالحة.');$s=$pdo->prepare("UPDATE project_claims pc JOIN projects p ON p.id=pc.project_id SET pc.status=?,pc.approved_amount=IF(? IN ('approved','partially_approved'),?,pc.approved_amount),pc.approved_days=IF(? IN ('approved','partially_approved'),?,pc.approved_days),pc.submitted_on=IF(?='submitted',COALESCE(pc.submitted_on,CURDATE()),pc.submitted_on) WHERE pc.id=? AND p.company_id=? AND pc.status NOT IN ('approved','rejected','withdrawn')");$s->execute([$status,$status,round((float)($_POST['approved_amount']??0),2),$status,(int)($_POST['approved_days']??0),$status,$id,$companyId]);if(!$s->rowCount())throw new RuntimeException('تعذر تحديث المطالبة.');audit('project_claim.status','project_claim',(string)$id,['status'=>$status]);flash('success','تم تحديث المطالبة.');
 }elseif($action==='variation_create'){$projectId=(int)($_POST['project_id']??0);$contractId=(int)($_POST['contract_id']??0);$descs=$_POST['description']??[];$qtys=$_POST['quantity']??[];$rates=$_POST['unit_rate']??[];$lines=[];$submitted=0;foreach($descs as $i=>$desc){$desc=trim((string)$desc);$qty=round((float)($qtys[$i]??0),4);$rate=round((float)($rates[$i]??0),4);if(!$desc||$qty==0)continue;$lines[]=[$desc,$qty,$rate];$submitted+=round($qty*$rate,2);}if(!$projectId||!$contractId||!$lines)throw new RuntimeException('المشروع والعقد وبند تغيير واحد على الأقل مطلوبة.');if(!(int)scalar('SELECT COUNT(*) FROM project_contracts pc JOIN projects p ON p.id=pc.project_id WHERE pc.id=? AND pc.project_id=? AND p.company_id=?',[$contractId,$projectId,$companyId]))throw new RuntimeException('العقد غير مرتبط بالمشروع.');$pdo->beginTransaction();$s=$pdo->prepare("INSERT INTO variation_orders(project_id,contract_id,variation_no,title,variation_type,requested_by,submitted_value,cost_impact,days_impact,submitted_on,status,created_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,'draft',?,NOW(),NOW())");$s->execute([$projectId,$contractId,trim((string)$_POST['variation_no']),trim((string)$_POST['title']),(string)($_POST['variation_type']??'addition'),(string)($_POST['requested_by']??'client'),$submitted,round((float)($_POST['cost_impact']??0),2),(int)($_POST['days_impact']??0),($_POST['submitted_on']??'')?:null,$userId]);$id=(int)$pdo->lastInsertId();$s=$pdo->prepare("INSERT INTO variation_order_items(variation_order_id,description,unit_code,quantity,unit_rate) VALUES (?,?,'وحدة',?,?)");foreach($lines as $l)$s->execute([$id,...$l]);$pdo->commit();audit('variation.create','variation_order',(string)$id);flash('success','تم إنشاء أمر التغيير بقيمة '.number_format($submitted,2));
 }elseif($action==='variation_status'){$id=(int)($_POST['id']??0);$status=(string)($_POST['status']??'');if(!in_array($status,['under_review','submitted','approved','partially_approved','rejected','cancelled'],true))throw new RuntimeException('الحالة غير صالحة.');$approved=round((float)($_POST['approved_value']??0),2);$s=$pdo->prepare("UPDATE variation_orders vo JOIN projects p ON p.id=vo.project_id SET vo.status=?,vo.approved_value=IF(? IN ('approved','partially_approved'),?,vo.approved_value),vo.approved_on=IF(? IN ('approved','partially_approved'),CURDATE(),vo.approved_on),vo.submitted_on=IF(?='submitted',COALESCE(vo.submitted_on,CURDATE()),vo.submitted_on) WHERE vo.id=? AND p.company_id=? AND vo.status NOT IN ('approved','rejected','cancelled')");$s->execute([$status,$status,$approved,$status,$status,$id,$companyId]);if(!$s->rowCount())throw new RuntimeException('تعذر تحديث أمر التغيير.');if(in_array($status,['approved','partially_approved'],true)){$factor=$approved>0&&((float)scalar('SELECT submitted_value FROM variation_orders WHERE id=?',[$id]))!=0?$approved/(float)scalar('SELECT submitted_value FROM variation_orders WHERE id=?',[$id]):1;$pdo->prepare('UPDATE variation_order_items SET approved_quantity=quantity,approved_unit_rate=unit_rate*? WHERE variation_order_id=?')->execute([$factor,$id]);}audit('variation.status','variation_order',(string)$id,['status'=>$status]);flash('success','تم تحديث أمر التغيير.');
 }}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash('error',$e instanceof PDOException?'الرقم مكرر أو البيانات غير متوافقة.':$e->getMessage());}redirect('project_controls.php');}
$customers=$pdo->prepare("SELECT c.id,bp.legal_name_ar FROM customers c JOIN business_partners bp ON bp.id=c.partner_id WHERE bp.company_id=? AND c.is_active=1 ORDER BY bp.legal_name_ar");$customers->execute([$companyId]);$customers=$customers->fetchAll();$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();$contracts=$pdo->prepare("SELECT pc.id,pc.project_id,pc.contract_no,pc.contract_title,p.project_no FROM project_contracts pc JOIN projects p ON p.id=pc.project_id WHERE p.company_id=? AND pc.is_active=1 ORDER BY p.project_no,pc.contract_no");$contracts->execute([$companyId]);$contracts=$contracts->fetchAll();$tenders=$pdo->prepare("SELECT t.*,bp.legal_name_ar customer_name FROM tenders t LEFT JOIN customers c ON c.id=t.customer_id LEFT JOIN business_partners bp ON bp.id=c.partner_id WHERE t.company_id=? ORDER BY t.id DESC");$tenders->execute([$companyId]);$tenders=$tenders->fetchAll();$claims=$pdo->prepare("SELECT pc.*,p.project_no,p.name_ar project_name,c.contract_no FROM project_claims pc JOIN projects p ON p.id=pc.project_id LEFT JOIN project_contracts c ON c.id=pc.contract_id WHERE p.company_id=? ORDER BY pc.id DESC");$claims->execute([$companyId]);$claims=$claims->fetchAll();$variations=$pdo->prepare("SELECT vo.*,p.project_no,p.name_ar project_name,pc.contract_no FROM variation_orders vo JOIN projects p ON p.id=vo.project_id JOIN project_contracts pc ON pc.id=vo.contract_id WHERE p.company_id=? ORDER BY vo.id DESC");$variations->execute([$companyId]);$variations=$variations->fetchAll();
render_header('project_controls','ضوابط العقود والمشاريع','المناقصات والمطالبات وأوامر التغيير وآثارها المالية والزمنية.');?>
<details class="panel quick-add"><summary>＋ مناقصة جديدة</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="tender_create"><div class="form-grid"><label>رقم المناقصة<input name="tender_no" required></label><label>العنوان<input name="title" required></label><label>العميل<select name="customer_id"><option value="0">غير محدد</option><?php foreach($customers as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['legal_name_ar']) ?></option><?php endforeach;?></select></label><label>النوع<select name="tender_type"><option value="private">خاصة</option><option value="public">عامة</option><option value="invitation">دعوة</option><option value="direct">مباشرة</option></select></label><label>آخر موعد<input type="datetime-local" name="submission_deadline"></label><label>صلاحية العرض<input type="date" name="bid_valid_until"></label><label>القيمة التقديرية<input type="number" step="0.01" name="estimated_value"></label><label>قيمة الضمان الابتدائي<input type="number" step="0.01" name="bid_bond_amount" value="0"></label><label class="checks"><span><input type="checkbox" name="bid_bond_required"> ضمان مطلوب</span></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></tr></thead><tbody><?php foreach($tenders as $t):?><tr><td><?= e($t['tender_no'].' — '.$t['title']) ?></td><td><?= e($t['customer_name']?:'—') ?></td><td><?= number_format((float)$t['estimated_value'],2) ?></td><td><?= e($t['submission_deadline']?:'—') ?></td><td><span class="chip"><?= e($t['status']) ?></span></td><td><?php if(!in_array($t['status'],['awarded','lost','cancelled'],true)):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="tender_status"><input type="hidden" name="id" value="<?= (int)$t['id'] ?>"><select name="status"><option value="studying">دراسة</option><option value="priced">مسعرة</option><option value="submitted">مقدمة</option><option value="awarded">فائزة</option><option value="lost">غير فائزة</option><option value="cancelled">ملغاة</option></select><button>حفظ</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<div class="settings-grid"><details class="panel quick-add"><summary>＋ مطالبة مشروع</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="claim_create"><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>العقد<select name="contract_id"><option value="0">بدون</option><?php foreach($contracts as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['project_no'].' — '.$c['contract_no']) ?></option><?php endforeach;?></select></label><label>رقم المطالبة<input name="claim_no" required></label><label>العنوان<input name="title" required></label><label>النوع<select name="claim_type"><option value="cost">تكلفة</option><option value="time">وقت</option><option value="cost_and_time">تكلفة ووقت</option><option value="other">أخرى</option></select></label><label>المبلغ المطالب<input type="number" step="0.01" name="claimed_amount" value="0"></label><label>الأيام المطالب بها<input type="number" name="claimed_days" value="0"></label><label>تاريخ التقديم<input type="date" name="submitted_on"></label><button class="primary-btn">حفظ المطالبة</button></form></details>
<details class="panel quick-add"><summary>＋ أمر تغيير</summary><form method="post" id="variationForm"><?= csrf_field() ?><input type="hidden" name="action" value="variation_create"><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>العقد<select name="contract_id"><?php foreach($contracts as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['project_no'].' — '.$c['contract_no']) ?></option><?php endforeach;?></select></label><label>الرقم<input name="variation_no" required></label><label>العنوان<input name="title" required></label><label>النوع<select name="variation_type"><option value="addition">إضافة</option><option value="omission">حذف</option><option value="substitution">استبدال</option><option value="time_extension">تمديد</option><option value="claim_conversion">تحويل مطالبة</option></select></label><label>مطلوب من<select name="requested_by"><option value="client">العميل</option><option value="contractor">المقاول</option><option value="consultant">الاستشاري</option><option value="other">أخرى</option></select></label><label>أثر التكلفة<input type="number" step="0.01" name="cost_impact" value="0"></label><label>أثر الأيام<input type="number" name="days_impact" value="0"></label><label>تاريخ التقديم<input type="date" name="submitted_on"></label><div class="responsive-table wide"><table id="variationLines"><thead><tr><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" name="quantity[]" value="1"></td><td><input type="number" step="0.0001" name="unit_rate[]" value="0"></td><td><button type="button" onclick="this.closest('tr').remove()">×</button></td></tr></tbody></table><button type="button" id="addVariationLine">إضافة بند</button></div><button class="primary-btn">حفظ أمر التغيير</button></form></details></div>
<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($claims as $c):?><tr><td><?= e($c['project_no'].' — '.$c['project_name']) ?></td><td><?= e($c['claim_no'].' — '.$c['title']) ?></td><td><?= number_format((float)$c['claimed_amount'],2) ?></td><td><?= number_format((float)$c['approved_amount'],2) ?></td><td><?= (int)$c['claimed_days'].' / '.(int)$c['approved_days'] ?></td><td><span class="chip"><?= e($c['status']) ?></span></td><td><?php if(!in_array($c['status'],['approved','rejected','withdrawn'],true)):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="claim_status"><input type="hidden" name="id" value="<?= (int)$c['id'] ?>"><select name="status"><option value="submitted">مقدمة</option><option value="under_review">مراجعة</option><option value="negotiation">تفاوض</option><option value="approved">معتمدة</option><option value="partially_approved">اعتماد جزئي</option><option value="rejected">مرفوضة</option><option value="withdrawn">مسحوبة</option></select><input type="number" step="0.01" name="approved_amount" placeholder="المبلغ المعتمد"><input type="number" name="approved_days" placeholder="الأيام"><button>حفظ</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></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><th>الحالة</th><th>تحديث</th></tr></thead><tbody><?php foreach($variations as $v):?><tr><td><?= e($v['project_no'].' — '.$v['project_name']) ?></td><td><?= e($v['variation_no'].' — '.$v['title']) ?></td><td><?= number_format((float)$v['submitted_value'],2) ?></td><td><?= number_format((float)$v['approved_value'],2) ?></td><td><?= number_format((float)$v['cost_impact'],2) ?></td><td><?= (int)$v['days_impact'] ?></td><td><span class="chip"><?= e($v['status']) ?></span></td><td><?php if(!in_array($v['status'],['approved','rejected','cancelled'],true)):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="variation_status"><input type="hidden" name="id" value="<?= (int)$v['id'] ?>"><select name="status"><option value="under_review">مراجعة</option><option value="submitted">مقدم</option><option value="approved">معتمد</option><option value="partially_approved">اعتماد جزئي</option><option value="rejected">مرفوض</option><option value="cancelled">ملغي</option></select><input type="number" step="0.01" name="approved_value" placeholder="القيمة المعتمدة"><button>حفظ</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<template id="variationTemplate"><tr><td><input name="description[]" required></td><td><input type="number" step="0.0001" name="quantity[]" value="1"></td><td><input type="number" step="0.0001" name="unit_rate[]" value="0"></td><td><button type="button" onclick="this.closest('tr').remove()">×</button></td></tr></template><script>addVariationLine.onclick=()=>document.querySelector('#variationLines tbody').append(variationTemplate.content.cloneNode(true));</script>
<?php render_footer();
