<?php
declare(strict_types=1);

require_once __DIR__ . '/company_profile_lib.php';

if (!function_exists('device_admin_alerts_ensure_schema')) {
  function device_admin_alerts_ensure_schema(mysqli $conn): void {
    company_profile_ensure_schema($conn);
    $table = company_profile_table($conn);
    if ($table !== '' && (!function_exists('col_exists') || !col_exists($conn, $table, 'admin_alert_phones'))) {
      try { $conn->query("ALTER TABLE `{$table}` ADD COLUMN admin_alert_phones TEXT NULL"); } catch (Throwable $ignored) {}
    }
    $conn->query("CREATE TABLE IF NOT EXISTS device_admin_alert_settings (
      id TINYINT UNSIGNED NOT NULL PRIMARY KEY,
      enabled TINYINT(1) NOT NULL DEFAULT 1,
      notify_down TINYINT(1) NOT NULL DEFAULT 1,
      notify_up TINYINT(1) NOT NULL DEFAULT 1,
      updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    $conn->query("INSERT IGNORE INTO device_admin_alert_settings (id) VALUES (1)");
    $conn->query("CREATE TABLE IF NOT EXISTS device_alert_mutes (
      device_group VARCHAR(20) NOT NULL,
      device_id INT NOT NULL,
      muted_until DATETIME NULL,
      reason VARCHAR(255) NULL,
      muted_by INT NULL,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (device_group,device_id), INDEX idx_device_alert_mutes_until (muted_until)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    $conn->query("CREATE TABLE IF NOT EXISTS device_admin_alert_state (
      device_group VARCHAR(20) NOT NULL,
      device_id INT NOT NULL,
      last_state VARCHAR(12) NOT NULL DEFAULT 'UNKNOWN',
      device_name VARCHAR(190) NULL,
      device_host VARCHAR(190) NULL,
      down_since DATETIME NULL,
      last_event_at DATETIME NULL,
      last_notified_at DATETIME NULL,
      updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (device_group,device_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
  }
}

function device_admin_alerts_settings(mysqli $conn): array {
  device_admin_alerts_ensure_schema($conn);
  $rs = $conn->query('SELECT enabled,notify_down,notify_up FROM device_admin_alert_settings WHERE id=1 LIMIT 1');
  $row = $rs ? $rs->fetch_assoc() : [];
  return ['enabled'=>(int)($row['enabled'] ?? 1)===1,'notify_down'=>(int)($row['notify_down'] ?? 1)===1,'notify_up'=>(int)($row['notify_up'] ?? 1)===1];
}

function device_admin_alerts_save_settings(mysqli $conn, bool $enabled, bool $down, bool $up): void {
  device_admin_alerts_ensure_schema($conn);
  $stmt=$conn->prepare('UPDATE device_admin_alert_settings SET enabled=?,notify_down=?,notify_up=? WHERE id=1');
  $a=$enabled?1:0;$b=$down?1:0;$c=$up?1:0;$stmt->bind_param('iii',$a,$b,$c);$stmt->execute();$stmt->close();
}

function device_admin_alerts_recipients(mysqli $conn): array {
  device_admin_alerts_ensure_schema($conn);
  $table=company_profile_table($conn); if($table==='') return [];
  $rs=$conn->query("SELECT admin_alert_phones FROM `{$table}` WHERE id=1 LIMIT 1");
  $row=$rs?$rs->fetch_assoc():[];$raw=(string)($row['admin_alert_phones']??'');
  $parts=preg_split('/[\s,;،]+/u',$raw,-1,PREG_SPLIT_NO_EMPTY)?:[];$out=[];
  foreach($parts as $phone){$phone=trim((string)$phone);$key=preg_replace('/\D+/','',$phone);if($key!==''&&!isset($out[$key]))$out[$key]=$phone;}
  return array_values($out);
}

function device_admin_alert_is_muted(mysqli $conn,string $group,int $id): bool {
  device_admin_alerts_ensure_schema($conn);if($id<=0)return false;
  $stmt=$conn->prepare("SELECT 1 FROM device_alert_mutes WHERE device_group=? AND device_id=? AND (muted_until IS NULL OR muted_until>NOW()) LIMIT 1");
  $stmt->bind_param('si',$group,$id);$stmt->execute();$rs=$stmt->get_result();$muted=(bool)($rs&&$rs->num_rows);$stmt->close();return $muted;
}

function device_admin_alert_mute(mysqli $conn,string $group,int $id,?string $until,string $reason,int $userId=0): void {
  device_admin_alerts_ensure_schema($conn);
  if(!in_array($group,['routers','sectors','receivers'],true)||$id<=0)throw new InvalidArgumentException('Invalid device.');
  $until=($until!==null&&trim($until)!=='')?date('Y-m-d H:i:s',strtotime($until)?:time()):null;
  $stmt=$conn->prepare("INSERT INTO device_alert_mutes(device_group,device_id,muted_until,reason,muted_by) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE muted_until=VALUES(muted_until),reason=VALUES(reason),muted_by=VALUES(muted_by),updated_at=NOW()");
  $stmt->bind_param('sissi',$group,$id,$until,$reason,$userId);$stmt->execute();$stmt->close();
}

function device_admin_alert_unmute(mysqli $conn,string $group,int $id): void {
  device_admin_alerts_ensure_schema($conn);$stmt=$conn->prepare('DELETE FROM device_alert_mutes WHERE device_group=? AND device_id=?');$stmt->bind_param('si',$group,$id);$stmt->execute();$stmt->close();
}

function device_admin_alert_statuses(mysqli $conn,array $items): array {
  $out=[];foreach($items as $item){$g=(string)($item['group']??'');$id=(int)($item['id']??0);if($id>0&&in_array($g,['routers','sectors','receivers'],true))$out[$g.':id:'.$id]=device_admin_alert_is_muted($conn,$g,$id);}return $out;
}

function device_admin_alert_duration(int $seconds): string {
  $seconds=max(0,$seconds);if($seconds<60)return $seconds.' ثانية';if($seconds<3600)return (int)round($seconds/60).' دقيقة';if($seconds<86400)return (int)round($seconds/3600).' ساعة';return (int)round($seconds/86400).' يوم';
}

function device_admin_alert_process(mysqli $conn,array $event): array {
  device_admin_alerts_ensure_schema($conn);
  $group=strtolower(trim((string)($event['group']??'')));$id=(int)($event['id']??0);$state=strtoupper(trim((string)($event['state']??'')));
  if(!in_array($group,['routers','sectors','receivers'],true)||$id<=0||!in_array($state,['DOWN','UP'],true))return ['ok'=>false,'error'=>'invalid_event'];
  $name=mb_substr(trim((string)($event['name']??'')),0,190,'UTF-8');$host=mb_substr(trim((string)($event['host']??'')),0,190,'UTF-8');$now=date('Y-m-d H:i:s');
  $conn->begin_transaction();
  try{
    $stmt=$conn->prepare('SELECT last_state,down_since FROM device_admin_alert_state WHERE device_group=? AND device_id=? FOR UPDATE');$stmt->bind_param('si',$group,$id);$stmt->execute();$rs=$stmt->get_result();$old=$rs?$rs->fetch_assoc():null;$stmt->close();
    $oldState=strtoupper((string)($old['last_state']??'UNKNOWN'));$downSince=(string)($old['down_since']??'');
    if($oldState===$state){$conn->commit();return ['ok'=>true,'duplicate'=>true,'queued'=>0];}
    if($state==='DOWN')$downSince=$now;
    $downSql=$state==='DOWN'?$downSince:null;
    $stmt=$conn->prepare("INSERT INTO device_admin_alert_state(device_group,device_id,last_state,device_name,device_host,down_since,last_event_at) VALUES(?,?,?,?,?,?,NOW()) ON DUPLICATE KEY UPDATE last_state=VALUES(last_state),device_name=VALUES(device_name),device_host=VALUES(device_host),down_since=VALUES(down_since),last_event_at=NOW()");
    $stmt->bind_param('sissss',$group,$id,$state,$name,$host,$downSql);$stmt->execute();$stmt->close();
    $settings=device_admin_alerts_settings($conn);$muted=device_admin_alert_is_muted($conn,$group,$id);$allowed=$settings['enabled']&&($state==='DOWN'?$settings['notify_down']:$settings['notify_up']);
    $queued=0;$errors=[];
    if($allowed&&!$muted){
      require_once __DIR__.'/messages_lib.php';$recipients=device_admin_alerts_recipients($conn);$labels=['routers'=>'راوتر','sectors'=>'قطاع/مرسل','receivers'=>'مستقبل'];
      $duration=$state==='UP'&&$downSince!==''?device_admin_alert_duration(time()-(strtotime($downSince)?:time())):'—';
      $company=company_profile_fetch($conn);$vars=['company_name'=>$company['company_name'],'device_type'=>$labels[$group],'device_name'=>$name?:('#'.$id),'device_host'=>$host?:'—','event_time'=>$now,'offline_duration'=>$duration];
      foreach($recipients as $phone){$result=messages_enqueue_template($conn,$state==='DOWN'?'ADMIN_DEVICE_DOWN':'ADMIN_DEVICE_UP',$phone,$vars);if(!empty($result['ok']))$queued+=count((array)($result['ids']??[]));else$errors[]=(string)($result['error']??'queue_failed');}
      if($queued>0)$conn->query("UPDATE device_admin_alert_state SET last_notified_at=NOW() WHERE device_group='".$conn->real_escape_string($group)."' AND device_id={$id}");
    }
    $conn->commit();return ['ok'=>true,'queued'=>$queued,'muted'=>$muted,'recipient_count'=>count(device_admin_alerts_recipients($conn)),'errors'=>$errors];
  }catch(Throwable $e){try{$conn->rollback();}catch(Throwable $ignored){}return ['ok'=>false,'error'=>$e->getMessage()];}
}
