<?php
$page_title='تنبيهات أجهزة الشبكة';$UA_FORCE_DESIGN_V2=true;$UA_PAGE_CSS=['assets/css/device_admin_alerts.css'];
require_once __DIR__.'/auth.php';require_once __DIR__.'/helpers.php';require_once __DIR__.'/security.php';require_once __DIR__.'/db_bootstrap.php';require_once __DIR__.'/device_admin_alerts_lib.php';require_once __DIR__.'/airmax_monitor_lib.php';
require_login('login.php');if(function_exists('require_perm'))require_perm('can_manage_messages');$conn=ensure_db(true);device_admin_alerts_ensure_schema($conn);$msg='';$err='';
try{
  if($_SERVER['REQUEST_METHOD']==='POST'){
    if(function_exists('ua_csrf_verify')&&!ua_csrf_verify())throw new RuntimeException('انتهت جلسة الحماية.');
    $action=(string)($_POST['action']??'settings');
    if($action==='settings'){device_admin_alerts_save_settings($conn,isset($_POST['enabled']),isset($_POST['notify_down']),isset($_POST['notify_up']));$msg='تم حفظ إعدادات تنبيهات الإدارة.';}
    elseif($action==='unmute'){device_admin_alert_unmute($conn,(string)($_POST['device_group']??''),(int)($_POST['device_id']??0));$msg='تم إلغاء كتم الجهاز.';}
    elseif($action==='mute'){
      $mode=(string)($_POST['mute_for']??'1h');$until=null;if($mode!=='permanent'){$seconds=['1h'=>3600,'6h'=>21600,'24h'=>86400,'7d'=>604800][$mode]??0;if($mode==='custom')$until=(string)($_POST['muted_until']??'');elseif($seconds>0)$until=date('Y-m-d H:i:s',time()+$seconds);}
      device_admin_alert_mute($conn,(string)($_POST['device_group']??''),(int)($_POST['device_id']??0),$until,trim((string)($_POST['reason']??'')),(int)($_SESSION['user_id']??0));$msg='تم كتم تنبيهات الجهاز.';
    }
  }
}catch(Throwable $e){$err=$e->getMessage();}
$settings=device_admin_alerts_settings($conn);$recipients=device_admin_alerts_recipients($conn);$devices=[];
$routerWhere=(function_exists('col_exists')&&col_exists($conn,'routers','is_enabled'))?' WHERE is_enabled=1':'';$rr=@$conn->query("SELECT id,name,host FROM routers{$routerWhere} ORDER BY name,id");while($rr&&($r=$rr->fetch_assoc()))$devices[]=['group'=>'routers','type'=>'راوتر']+$r;
foreach(airmax_get_all($conn,true) as $d){$station=function_exists('airmax_device_is_station')?airmax_device_is_station($d):false;$devices[]=['group'=>$station?'receivers':'sectors','type'=>$station?'مستقبل':'قطاع/مرسل','id'=>$d['id'],'name'=>$d['name'],'host'=>$d['host']];}
$mutes=[];$mr=@$conn->query("SELECT * FROM device_alert_mutes WHERE muted_until IS NULL OR muted_until>NOW()");while($mr&&($r=$mr->fetch_assoc()))$mutes[$r['device_group'].':'.$r['device_id']]=$r;
require_once __DIR__.'/header.php';require_once __DIR__.'/sidebar.php';$active_tab='device_alerts';include __DIR__.'/messages_tabs.php';
?>
<div class="content-wrapper ua-extracted-page daa-page"><section class="content"><div class="container-fluid">
<header class="daa-hero"><div><small>NETWORK ADMIN ALERTS</small><h1>تنبيهات أجهزة الشبكة</h1></div><i class="fa fa-bell"></i></header>
<?php if($msg):?><div class="alert alert-success"><?=h($msg)?></div><?php endif;?><?php if($err):?><div class="alert alert-danger"><?=h($err)?></div><?php endif;?>
<div class="daa-grid"><form method="post" class="daa-card"><?php ua_csrf_field();?><input type="hidden" name="action" value="settings"><h2><i class="fa fa-sliders"></i> خيارات الإرسال</h2>
<label class="daa-switch"><input type="checkbox" name="enabled" <?=$settings['enabled']?'checked':''?>><span><b>تفعيل رسائل تنبيهات الإدارة</b><small>المفتاح الرئيسي لجميع رسائل حالة الأجهزة.</small></span></label>
<label class="daa-switch"><input type="checkbox" name="notify_down" <?=$settings['notify_down']?'checked':''?>><span><b>رسالة عند الانقطاع</b><small>بعد اكتمال التحقق وعدم وجود مشترك متصل عبر الجهاز.</small></span></label>
<label class="daa-switch"><input type="checkbox" name="notify_up" <?=$settings['notify_up']?'checked':''?>><span><b>رسالة عند العودة</b><small>تُرسل مرة واحدة عند الانتقال من الانقطاع إلى العمل.</small></span></label><button class="btn btn-success" type="submit"><i class="fa fa-save"></i> حفظ</button></form>
<section class="daa-card"><h2><i class="fa fa-address-book"></i> مستلمو التنبيهات</h2><?php if($recipients):?><div class="daa-phones"><?php foreach($recipients as $p):?><span dir="ltr"><?=h($p)?></span><?php endforeach;?></div><?php else:?><p class="daa-empty">لم تُحدد أرقام بعد.</p><?php endif;?><a class="btn btn-outline-info" href="company_admin.php"><i class="fa fa-building"></i> تعديل الأرقام في بيانات الشركة</a><a class="btn btn-outline-secondary" href="messages_templates.php"><i class="fa fa-file-text-o"></i> تعديل قوالب الانقطاع والعودة</a></section></div>
<section class="daa-card daa-devices"><div class="daa-title"><div><h2><i class="fa fa-volume-off"></i> كتم جهاز محدد</h2><p>الكتم يمنع الرسائل والتنبيه المرئي فقط ولا يوقف المراقبة أو تحديث الحالة.</p></div><input id="daaSearch" type="search" placeholder="بحث بالاسم أو العنوان"></div>
<div class="table-responsive"><table class="table"><thead><tr><th>النوع</th><th>الجهاز</th><th>العنوان</th><th>الحالة</th><th>الإجراء</th></tr></thead><tbody><?php foreach($devices as $d):$key=$d['group'].':'.$d['id'];$mute=$mutes[$key]??null;?><tr data-device-row data-search="<?=h(mb_strtolower(($d['name']??'').' '.($d['host']??''),'UTF-8'))?>"><td><?=h($d['type'])?></td><td><b><?=h($d['name']??('#'.$d['id']))?></b></td><td dir="ltr"><?=h($d['host']??'')?></td><td><?php if($mute):?><span class="badge badge-warning">مكتوم <?=empty($mute['muted_until'])?'دائمًا':'حتى '.h($mute['muted_until'])?></span><?php else:?><span class="badge badge-success">فعّال</span><?php endif;?></td><td><?php if($mute):?><form method="post"><?php ua_csrf_field();?><input type="hidden" name="action" value="unmute"><input type="hidden" name="device_group" value="<?=h($d['group'])?>"><input type="hidden" name="device_id" value="<?=(int)$d['id']?>"><button class="btn btn-sm btn-success">إلغاء الكتم</button></form><?php else:?><form method="post" class="daa-mute-form"><?php ua_csrf_field();?><input type="hidden" name="action" value="mute"><input type="hidden" name="device_group" value="<?=h($d['group'])?>"><input type="hidden" name="device_id" value="<?=(int)$d['id']?>"><select name="mute_for"><option value="1h">ساعة</option><option value="6h">6 ساعات</option><option value="24h">24 ساعة</option><option value="7d">7 أيام</option><option value="permanent">دائم</option><option value="custom">حتى وقت محدد</option></select><input type="datetime-local" name="muted_until"><input name="reason" placeholder="سبب اختياري"><button class="btn btn-sm btn-warning">كتم</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
</div></section></div><script>document.getElementById('daaSearch').addEventListener('input',function(){const q=this.value.trim().toLowerCase();document.querySelectorAll('[data-device-row]').forEach(r=>r.hidden=q&&!r.dataset.search.includes(q));});</script><?php require_once __DIR__.'/footer.php';?>
