<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_permission('assets.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==='usage_create'){$assetId=(int)$_POST['asset_id'];$projectId=(int)$_POST['project_id'];$hours=round((float)($_POST['usage_hours']??0),2);$idle=round((float)($_POST['idle_hours']??0),2);$rate=round((float)($_POST['internal_rate']??0),4);if(!$assetId||!$projectId||$hours<0||$idle<0)throw new RuntimeException('المعدة والمشروع والساعات مطلوبة.');if(!(int)scalar('SELECT COUNT(*) FROM assets WHERE id=? AND company_id=? AND is_equipment=1 AND deleted_at IS NULL',[$assetId,$companyId]))throw new RuntimeException('المعدة غير صالحة.');$s=$pdo->prepare('INSERT INTO equipment_usage_logs(asset_id,project_id,usage_date,start_meter,end_meter,usage_hours,idle_hours,internal_rate,cost_amount,operator_employee_id,cost_code_id,approved_by,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,NOW())');$s->execute([$assetId,$projectId,$_POST['usage_date'],($_POST['start_meter']??'')!==''?(float)$_POST['start_meter']:null,($_POST['end_meter']??'')!==''?(float)$_POST['end_meter']:null,$hours,$idle,$rate,round($hours*$rate,2),(int)($_POST['operator_employee_id']??0)?:null,(int)($_POST['cost_code_id']??0)?:null,$userId]);$pdo->prepare('UPDATE assets SET current_project_id=? WHERE id=? AND company_id=?')->execute([$projectId,$assetId,$companyId]);audit('equipment.usage','equipment_usage',(string)$pdo->lastInsertId());flash('success','تم تسجيل تشغيل المعدة وتكلفتها.');
 }elseif($action==='fuel_create'){$assetId=(int)$_POST['asset_id'];$qty=round((float)($_POST['quantity']??0),4);$cost=round((float)($_POST['unit_cost']??0),4);if(!$assetId||$qty<=0||$cost<0)throw new RuntimeException('المعدة والكمية والتكلفة غير صحيحة.');if(!(int)scalar('SELECT COUNT(*) FROM assets WHERE id=? AND company_id=? AND is_equipment=1 AND deleted_at IS NULL',[$assetId,$companyId]))throw new RuntimeException('المعدة غير صالحة.');$s=$pdo->prepare('INSERT INTO equipment_fuel_logs(asset_id,project_id,fuel_date,fuel_type,quantity,unit_cost,total_cost,meter_reading,supplier_id,created_by,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,NOW())');$s->execute([$assetId,(int)($_POST['project_id']??0)?:null,$_POST['fuel_date'],trim((string)$_POST['fuel_type']),$qty,$cost,round($qty*$cost,2),($_POST['meter_reading']??'')!==''?(float)$_POST['meter_reading']:null,(int)($_POST['supplier_id']??0)?:null,$userId]);audit('equipment.fuel','equipment_fuel',(string)$pdo->lastInsertId());flash('success','تم تسجيل الوقود.');
 }elseif($action==='maintenance_create'){$assetId=(int)$_POST['asset_id'];if(!$assetId||!trim((string)$_POST['description']))throw new RuntimeException('المعدة ووصف الصيانة مطلوبان.');if(!(int)scalar('SELECT COUNT(*) FROM assets WHERE id=? AND company_id=? AND is_equipment=1 AND deleted_at IS NULL',[$assetId,$companyId]))throw new RuntimeException('المعدة غير صالحة.');$no='MNT-'.date('Ym').'-'.str_pad((string)((int)scalar('SELECT COUNT(*)+1 FROM equipment_maintenance em JOIN assets a ON a.id=em.asset_id WHERE a.company_id=?',[$companyId])),5,'0',STR_PAD_LEFT);$pdo->beginTransaction();$s=$pdo->prepare("INSERT INTO equipment_maintenance(asset_id,project_id,maintenance_no,maintenance_type,opened_on,vendor_id,description,parts_cost,labor_cost,other_cost,downtime_hours,status,created_by,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,'open',?,NOW())");$s->execute([$assetId,(int)($_POST['project_id']??0)?:null,$no,(string)($_POST['maintenance_type']??'preventive'),$_POST['opened_on'],(int)($_POST['vendor_id']??0)?:null,trim((string)$_POST['description']),round((float)($_POST['parts_cost']??0),2),round((float)($_POST['labor_cost']??0),2),round((float)($_POST['other_cost']??0),2),round((float)($_POST['downtime_hours']??0),2),$userId]);$id=(int)$pdo->lastInsertId();$pdo->prepare("UPDATE assets SET asset_status='under_maintenance' WHERE id=? AND company_id=?")->execute([$assetId,$companyId]);$pdo->commit();audit('equipment.maintenance.create','equipment_maintenance',(string)$id);flash('success','تم فتح أمر الصيانة: '.$no);
 }elseif($action==='maintenance_status'){$id=(int)($_POST['id']??0);$status=(string)($_POST['status']??'');if(!in_array($status,['in_progress','completed','cancelled'],true))throw new RuntimeException('الحالة غير صالحة.');$q=$pdo->prepare('SELECT em.asset_id FROM equipment_maintenance em JOIN assets a ON a.id=em.asset_id WHERE em.id=? AND a.company_id=?');$q->execute([$id,$companyId]);$assetId=(int)$q->fetchColumn();if(!$assetId)throw new RuntimeException('أمر الصيانة غير صالح.');$pdo->beginTransaction();$s=$pdo->prepare("UPDATE equipment_maintenance SET status=?,completed_on=IF(?='completed',CURDATE(),completed_on) WHERE id=? AND status NOT IN ('completed','cancelled')");$s->execute([$status,$status,$id]);if(!$s->rowCount())throw new RuntimeException('تعذر تحديث أمر الصيانة.');if(in_array($status,['completed','cancelled'],true))$pdo->prepare("UPDATE assets SET asset_status='active' WHERE id=? AND company_id=?")->execute([$assetId,$companyId]);$pdo->commit();audit('equipment.maintenance.status','equipment_maintenance',(string)$id,['status'=>$status]);flash('success','تم تحديث أمر الصيانة.');
 }}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash('error',$e instanceof PDOException?'تعذر الحفظ؛ تحقق من السجل والبيانات.':$e->getMessage());}redirect('equipment.php');}
$equipment=$pdo->prepare("SELECT a.id,a.asset_no,a.name_ar,a.asset_status,a.current_project_id FROM assets a WHERE a.company_id=? AND a.is_equipment=1 AND a.deleted_at IS NULL ORDER BY a.asset_no");$equipment->execute([$companyId]);$equipment=$equipment->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();$employees=$pdo->prepare("SELECT e.id,e.employee_no,e.full_name legal_name_ar FROM employees e WHERE e.company_id=? AND e.employment_status='active' ORDER BY e.full_name");$employees->execute([$companyId]);$employees=$employees->fetchAll();$suppliers=$pdo->prepare("SELECT s.id,bp.legal_name_ar FROM suppliers s JOIN business_partners bp ON bp.id=s.partner_id WHERE bp.company_id=? AND s.is_active=1 ORDER BY bp.legal_name_ar");$suppliers->execute([$companyId]);$suppliers=$suppliers->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();$usage=$pdo->prepare("SELECT u.*,a.asset_no,a.name_ar asset_name,p.name_ar project_name,e.full_name operator_name FROM equipment_usage_logs u JOIN assets a ON a.id=u.asset_id JOIN projects p ON p.id=u.project_id LEFT JOIN employees e ON e.id=u.operator_employee_id WHERE a.company_id=? ORDER BY u.usage_date DESC,u.id DESC LIMIT 100");$usage->execute([$companyId]);$usage=$usage->fetchAll();$fuel=$pdo->prepare("SELECT f.*,a.asset_no,a.name_ar asset_name,p.name_ar project_name FROM equipment_fuel_logs f JOIN assets a ON a.id=f.asset_id LEFT JOIN projects p ON p.id=f.project_id WHERE a.company_id=? ORDER BY f.fuel_date DESC,f.id DESC LIMIT 100");$fuel->execute([$companyId]);$fuel=$fuel->fetchAll();$maintenance=$pdo->prepare("SELECT m.*,a.asset_no,a.name_ar asset_name,p.name_ar project_name,bp.legal_name_ar vendor_name,m.parts_cost+m.labor_cost+m.other_cost total_cost FROM equipment_maintenance m JOIN assets a ON a.id=m.asset_id LEFT JOIN projects p ON p.id=m.project_id LEFT JOIN suppliers s ON s.id=m.vendor_id LEFT JOIN business_partners bp ON bp.id=s.partner_id WHERE a.company_id=? ORDER BY m.id DESC");$maintenance->execute([$companyId]);$maintenance=$maintenance->fetchAll();
render_header('equipment','تشغيل وصيانة المعدات','ساعات التشغيل والوقود والصيانة وتكلفة المعدات على المشاريع.');?>
<div class="settings-grid"><details class="panel quick-add"><summary>＋ تشغيل معدة</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="usage_create"><label>المعدة<select name="asset_id"><?php foreach($equipment as $e):?><option value="<?= (int)$e['id'] ?>"><?= e($e['asset_no'].' — '.$e['name_ar']) ?></option><?php endforeach;?></select></label><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>التاريخ<input type="date" name="usage_date" value="<?= date('Y-m-d') ?>"></label><label>عداد البداية<input type="number" step="0.01" name="start_meter"></label><label>عداد النهاية<input type="number" step="0.01" name="end_meter"></label><label>ساعات التشغيل<input type="number" step="0.01" min="0" name="usage_hours" value="0"></label><label>ساعات التوقف<input type="number" step="0.01" min="0" name="idle_hours" value="0"></label><label>المعدل الداخلي<input type="number" step="0.0001" min="0" name="internal_rate" value="0"></label><label>المشغل<select name="operator_employee_id"><option value="0">—</option><?php foreach($employees as $e):?><option value="<?= (int)$e['id'] ?>"><?= e($e['employee_no'].' — '.$e['legal_name_ar']) ?></option><?php endforeach;?></select></label><label>كود التكلفة<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></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="fuel_create"><label>المعدة<select name="asset_id"><?php foreach($equipment as $e):?><option value="<?= (int)$e['id'] ?>"><?= e($e['asset_no'].' — '.$e['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="fuel_date" value="<?= date('Y-m-d') ?>"></label><label>نوع الوقود<input name="fuel_type" value="ديزل"></label><label>الكمية<input type="number" step="0.0001" min="0.0001" name="quantity"></label><label>تكلفة الوحدة<input type="number" step="0.0001" min="0" name="unit_cost"></label><label>قراءة العداد<input type="number" step="0.01" name="meter_reading"></label><label>المورد<select name="supplier_id"><option value="0">—</option><?php foreach($suppliers as $s):?><option value="<?= (int)$s['id'] ?>"><?= e($s['legal_name_ar']) ?></option><?php endforeach;?></select></label><button class="primary-btn">حفظ الوقود</button></form></details></div>
<details class="panel quick-add"><summary>＋ أمر صيانة</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="maintenance_create"><div class="form-grid"><label>المعدة<select name="asset_id"><?php foreach($equipment as $e):?><option value="<?= (int)$e['id'] ?>"><?= e($e['asset_no'].' — '.$e['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>نوع الصيانة<select name="maintenance_type"><option value="preventive">وقائية</option><option value="corrective">تصحيحية</option><option value="inspection">فحص</option><option value="accident">حادث</option><option value="other">أخرى</option></select></label><label>تاريخ الفتح<input type="date" name="opened_on" value="<?= date('Y-m-d') ?>"></label><label>المنفذ<select name="vendor_id"><option value="0">داخلي</option><?php foreach($suppliers as $s):?><option value="<?= (int)$s['id'] ?>"><?= e($s['legal_name_ar']) ?></option><?php endforeach;?></select></label><label class="wide">الوصف<input name="description" required></label><label>قطع الغيار<input type="number" step="0.01" name="parts_cost" value="0"></label><label>العمالة<input type="number" step="0.01" name="labor_cost" value="0"></label><label>تكاليف أخرى<input type="number" step="0.01" name="other_cost" value="0"></label><label>ساعات التوقف<input type="number" step="0.01" name="downtime_hours" value="0"></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><th></th></tr></thead><tbody><?php foreach($maintenance as $m):?><tr><td><?= e($m['maintenance_no']) ?></td><td><?= e($m['asset_no'].' — '.$m['asset_name']) ?></td><td><?= e($m['project_name']?:'—') ?></td><td><?= e($m['maintenance_type']) ?></td><td><?= number_format((float)$m['total_cost'],2) ?></td><td><?= number_format((float)$m['downtime_hours'],2) ?></td><td><span class="chip"><?= e($m['status']) ?></span></td><td><?php if(!in_array($m['status'],['completed','cancelled'],true)):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="maintenance_status"><input type="hidden" name="id" value="<?= (int)$m['id'] ?>"><select name="status"><option value="in_progress">قيد التنفيذ</option><option value="completed">مكتملة</option><option value="cancelled">ملغاة</option></select><button>تحديث</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<div class="settings-grid"><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></tr></thead><tbody><?php foreach($usage as $u):?><tr><td><?= e($u['usage_date']) ?></td><td><?= e($u['asset_no'].' — '.$u['asset_name']) ?></td><td><?= e($u['project_name']) ?></td><td><?= number_format((float)$u['usage_hours'],2).' / '.number_format((float)$u['idle_hours'],2) ?></td><td><?= number_format((float)$u['cost_amount'],2) ?></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></tr></thead><tbody><?php foreach($fuel as $f):?><tr><td><?= e($f['fuel_date']) ?></td><td><?= e($f['asset_no'].' — '.$f['asset_name']) ?></td><td><?= e($f['project_name']?:'—') ?></td><td><?= number_format((float)$f['quantity'],4) ?></td><td><?= number_format((float)$f['total_cost'],2) ?></td></tr><?php endforeach;?></tbody></table></div></section></div>
<?php render_footer();
