<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_auth();require __DIR__.'/app/layout.php';
if(!function_exists('mb_strlen')){function mb_strlen(string $value):int{return strlen($value);}}
$pdo=db();$companyId=company_id();$term=trim((string)($_GET['q']??''));$results=[];if(mb_strlen($term)>=2){$like='%'.$term.'%';$sources=[['مشروع','projects.php',"SELECT id,CONCAT(project_no,' — ',name_ar) title,status subtitle FROM projects WHERE company_id=? AND deleted_at IS NULL AND (project_no LIKE ? OR name_ar LIKE ?) LIMIT 20"],['أمر شراء','purchases.php',"SELECT id,po_no title,status subtitle FROM purchase_orders WHERE company_id=? AND po_no LIKE ? LIMIT 20"],['طلب شراء','procurement.php',"SELECT id,request_no title,status subtitle FROM purchase_requests WHERE company_id=? AND (request_no LIKE ? OR purpose LIKE ?) LIMIT 20"],['فاتورة عميل','invoices.php',"SELECT id,invoice_no title,status subtitle FROM sales_invoices WHERE company_id=? AND invoice_no LIKE ? LIMIT 20"],['فاتورة مورد','payables.php',"SELECT id,CONCAT(internal_no,' / ',invoice_no) title,status subtitle FROM supplier_invoices WHERE company_id=? AND (internal_no LIKE ? OR invoice_no LIKE ?) LIMIT 20"],['مورد','purchases.php',"SELECT bp.id,CONCAT(bp.partner_code,' — ',bp.legal_name_ar) title,'مورد' subtitle FROM business_partners bp JOIN suppliers s ON s.partner_id=bp.id WHERE bp.company_id=? AND (bp.partner_code LIKE ? OR bp.legal_name_ar LIKE ?) LIMIT 20"],['عميل','projects.php',"SELECT bp.id,CONCAT(bp.partner_code,' — ',bp.legal_name_ar) title,'عميل' subtitle FROM business_partners bp JOIN customers c ON c.partner_id=bp.id WHERE bp.company_id=? AND (bp.partner_code LIKE ? OR bp.legal_name_ar LIKE ?) LIMIT 20"]];foreach($sources as [$kind,$url,$sql]){$q=$pdo->prepare($sql);$count=substr_count($sql,'?');$params=$count===2?[$companyId,$like]:[$companyId,$like,$like];$q->execute($params);foreach($q->fetchAll() as $r)$results[]=[$kind,$url,$r];}}
render_header('search','البحث العام',$term?'نتائج البحث عن: '.$term:'ابحث في المشاريع والمستندات والأطراف.');?>
<form class="panel form-card" method="get"><label>عبارة البحث<input name="q" value="<?= e($term) ?>" minlength="2" autofocus></label><button class="primary-btn">بحث</button></form><section class="panel data-card"><div class="responsive-table"><table><thead><tr><th>النوع</th><th>النتيجة</th><th>الحالة</th><th></th></tr></thead><tbody><?php foreach($results as [$kind,$url,$r]):?><tr><td><?= e($kind) ?></td><td><?= e($r['title']) ?></td><td><span class="chip"><?= e($r['subtitle']) ?></span></td><td><a href="<?= e(app_url($url)) ?>">فتح الوحدة</a></td></tr><?php endforeach;?></tbody></table></div><?php if($term&&mb_strlen($term)>=2&&!$results):?><p>لا توجد نتائج مطابقة.</p><?php endif;?></section><?php render_footer();
