<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_auth();require __DIR__.'/app/layout.php';
$pdo=db();$companyId=company_id();$userId=(int)user()['id'];
function notify_once(int $companyId,int $userId,string $type,string $title,string $message,string $objectType,int $objectId,string $priority='normal'):bool{$pdo=db();$q=$pdo->prepare('SELECT COUNT(*) FROM notifications WHERE company_id=? AND user_id=? AND notification_type=? AND object_type=? AND object_id=? AND read_at IS NULL');$q->execute([$companyId,$userId,$type,$objectType,$objectId]);if((int)$q->fetchColumn())return false;$pdo->prepare('INSERT INTO notifications(company_id,user_id,notification_type,title,message,object_type,object_id,priority,created_at) VALUES (?,?,?,?,?,?,?,?,NOW())')->execute([$companyId,$userId,$type,$title,$message,$objectType,$objectId,$priority]);return true;}
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();try{$action=(string)($_POST['action']??'');
 if($action==='scan'){$count=0;$q=$pdo->prepare("SELECT id,invoice_no,due_date,net_due_amount-collected_amount amount FROM sales_invoices WHERE company_id=? AND status IN ('issued','partially_collected','overdue') AND collected_amount<net_due_amount AND due_date<=DATE_ADD(CURDATE(),INTERVAL 7 DAY)");$q->execute([$companyId]);foreach($q->fetchAll() as $r){$overdue=$r['due_date']<date('Y-m-d');$count+=notify_once($companyId,$userId,'customer_due',$overdue?'فاتورة عميل متأخرة':'استحقاق عميل قريب','الفاتورة '.$r['invoice_no'].' بمبلغ '.number_format((float)$r['amount'],2).' مستحقة في '.$r['due_date'],'sales_invoice',(int)$r['id'],$overdue?'critical':'high')?1:0;}$q=$pdo->prepare("SELECT id,internal_no,due_date,total_amount-paid_amount amount FROM supplier_invoices WHERE company_id=? AND status IN ('posted','partially_paid') AND paid_amount<total_amount AND due_date<=DATE_ADD(CURDATE(),INTERVAL 7 DAY)");$q->execute([$companyId]);foreach($q->fetchAll() as $r){$overdue=$r['due_date']<date('Y-m-d');$count+=notify_once($companyId,$userId,'supplier_due',$overdue?'فاتورة مورد متأخرة':'استحقاق مورد قريب','الفاتورة '.$r['internal_no'].' بمبلغ '.number_format((float)$r['amount'],2).' مستحقة في '.$r['due_date'],'supplier_invoice',(int)$r['id'],$overdue?'critical':'high')?1:0;}$q=$pdo->prepare("SELECT id,cheque_no,due_date,amount,cheque_type FROM cheques WHERE company_id=? AND status NOT IN ('cleared','cancelled','returned','stale') AND due_date<=DATE_ADD(CURDATE(),INTERVAL 7 DAY)");$q->execute([$companyId]);foreach($q->fetchAll() as $r)$count+=notify_once($companyId,$userId,'cheque_due','شيك مستحق قريب','الشيك '.$r['cheque_no'].' بمبلغ '.number_format((float)$r['amount'],2).' يستحق في '.$r['due_date'],'cheque',(int)$r['id'],'high')?1:0;$approvalQueries=[['purchase_request',"SELECT id,request_no label FROM purchase_requests WHERE company_id=? AND status='submitted'",'طلب شراء ينتظر الاعتماد'],['payment_voucher',"SELECT id,payment_no label FROM payment_vouchers WHERE company_id=? AND status='submitted'",'سند صرف ينتظر الاعتماد'],['receipt_voucher',"SELECT id,receipt_no label FROM receipt_vouchers WHERE company_id=? AND status='submitted'",'سند قبض ينتظر الاعتماد'],['supplier_invoice',"SELECT id,internal_no label FROM supplier_invoices WHERE company_id=? AND status='submitted'",'فاتورة مورد تنتظر الاعتماد']];foreach($approvalQueries as [$type,$sql,$title]){$q=$pdo->prepare($sql);$q->execute([$companyId]);foreach($q->fetchAll() as $r)$count+=notify_once($companyId,$userId,'approval',$title,$r['label'].' بحاجة إلى إجراء اعتماد.',$type,(int)$r['id'],'normal')?1:0;}audit('notifications.scan','notification',null,['created'=>$count]);flash('success','اكتمل الفحص وتم إنشاء '.$count.' تنبيه جديد.');
 }elseif($action==='read'){$pdo->prepare('UPDATE notifications SET read_at=NOW() WHERE id=? AND company_id=? AND user_id=?')->execute([(int)$_POST['id'],$companyId,$userId]);
 }elseif($action==='read_all'){$pdo->prepare('UPDATE notifications SET read_at=NOW() WHERE company_id=? AND user_id=? AND read_at IS NULL')->execute([$companyId,$userId]);flash('success','تم تعليم جميع التنبيهات كمقروءة.');
 }}catch(Throwable $e){flash('error',$e->getMessage());}redirect('notifications.php');}
$filter=(string)($_GET['filter']??'unread');$sql='SELECT * FROM notifications WHERE company_id=? AND user_id=?';if($filter==='unread')$sql.=' AND read_at IS NULL';elseif($filter==='critical')$sql.=" AND priority IN ('high','critical')";$sql.=' ORDER BY (read_at IS NULL) DESC,FIELD(priority,\'critical\',\'high\',\'normal\',\'low\'),id DESC LIMIT 300';$q=$pdo->prepare($sql);$q->execute([$companyId,$userId]);$notifications=$q->fetchAll();$unread=(int)scalar('SELECT COUNT(*) FROM notifications WHERE company_id=? AND user_id=? AND read_at IS NULL',[$companyId,$userId]);
render_header('notifications','مركز التنبيهات','الاستحقاقات والموافقات والشيكات التي تحتاج إلى إجراء.');?>
<div class="panel form-card"><form method="post" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="scan"><button class="primary-btn">فحص الاستحقاقات والموافقات الآن</button></form><?php if($unread):?><form method="post" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="read_all"><button>تعليم الكل كمقروء</button></form><?php endif;?><nav><a href="?filter=unread">غير المقروء (<?= $unread ?>)</a> · <a href="?filter=critical">العاجل</a> · <a href="?filter=all">الكل</a></nav></div>
<section class="panel data-card"><div class="responsive-table"><table><thead><tr><th>الأولوية</th><th>التنبيه</th><th>الرسالة</th><th>المرجع</th><th>التاريخ</th><th></th></tr></thead><tbody><?php foreach($notifications as $n):?><tr style="<?= $n['read_at']?'opacity:.65':'' ?>"><td><span class="chip"><?= e($n['priority']) ?></span></td><td><?= e($n['title']) ?></td><td><?= e($n['message']) ?></td><td><?= e(($n['object_type']?:'—').($n['object_id']?' #'.$n['object_id']:'')) ?></td><td><?= e($n['created_at']) ?></td><td><?php if(!$n['read_at']):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="read"><input type="hidden" name="id" value="<?= (int)$n['id'] ?>"><button>تمت القراءة</button></form><?php else:?>✓<?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php render_footer();
