<?php
/**
 * AURA FARMING — Etapa 20
 * Painel do responsável, controles parentais, atividade e alertas.
 */

function afGuardianDashboardConfig(PDO $pdo, string $key, mixed $default = null): mixed
{
    if (function_exists('afMinorPolicyConfig')) return afMinorPolicyConfig($pdo,$key,$default);
    try {
        $st=$pdo->prepare('SELECT valor,tipo FROM af_configuracoes WHERE chave=? LIMIT 1');
        $st->execute([$key]);$row=$st->fetch();
        if(!$row)return $default;
        return match((string)$row['tipo']){'bool'=>filter_var($row['valor'],FILTER_VALIDATE_BOOLEAN),'int'=>(int)$row['valor'],'float'=>(float)$row['valor'],default=>$row['valor']};
    } catch(Throwable $e){return $default;}
}

function afGuardianDashboardLink(PDO $pdo, int $guardianUsuarioId, int $linkId): array
{
    $st=$pdo->prepare("SELECT l.*,u.nome,u.username,u.aura_id,u.foto_perfil,u.foto_externa,u.total_partidas,u.aura_total,u.melhor_pontuacao,
        ag.idade_declarada,ag.status_idade,p.perfil_privado,ga.status_verificacao guardian_status
        FROM af_guardian_minor_links l
        JOIN af_usuarios u ON u.id=l.minor_usuario_id
        LEFT JOIN af_user_age_profiles ag ON ag.usuario_id=u.id
        LEFT JOIN af_perfis p ON p.usuario_id=u.id
        LEFT JOIN af_guardian_accounts ga ON ga.usuario_id=l.guardian_usuario_id
        WHERE l.id=? AND l.guardian_usuario_id=? AND l.status IN ('pending_verification','verified_pending_consent','active') LIMIT 1");
    $st->execute([$linkId,$guardianUsuarioId]);$row=$st->fetch();
    if(!$row)throw new RuntimeException('Dependente não encontrado ou vínculo encerrado.');
    return $row;
}

function afGuardianDashboardDefaultControls(PDO $pdo): array
{
    return [
        'access_status'=>'active',
        'daily_limit_minutes'=>max(0,min(240,(int)afGuardianDashboardConfig($pdo,'guardian_default_daily_limit_minutes',30))),
        'allowed_start_time'=>substr((string)afGuardianDashboardConfig($pdo,'guardian_default_allowed_start_time','08:00'),0,5),
        'allowed_end_time'=>substr((string)afGuardianDashboardConfig($pdo,'guardian_default_allowed_end_time','21:00'),0,5),
        'timezone'=>APP_TIMEZONE,
        'camera_enabled'=>1,
        'farm_enabled'=>1,
        'battle_enabled'=>0,
        'ranking_enabled'=>1,
        'transmission_enabled'=>0,
        'profile_private'=>1,
        'comments_moderated'=>0,
        'notify_session_start'=>1,
        'notify_session_end'=>1,
        'notify_security_incident'=>1,
        'notify_weekly_summary'=>1,
        'notify_friend_request'=>1,
        'notify_live_start'=>1,
        'notify_battle_start'=>1,
        'notify_report'=>1,
        'notify_privacy_change'=>1,
        'notify_blocked_access'=>1,
    ];
}

function afGuardianDashboardEnsureControls(PDO $pdo, int $guardianUsuarioId, int $linkId): array
{
    $link=afGuardianDashboardLink($pdo,$guardianUsuarioId,$linkId);
    $d=afGuardianDashboardDefaultControls($pdo);
    $pdo->prepare("INSERT INTO af_guardian_controls
        (link_id,guardian_usuario_id,minor_usuario_id,access_status,daily_limit_minutes,allowed_start_time,allowed_end_time,timezone,
         camera_enabled,farm_enabled,battle_enabled,ranking_enabled,transmission_enabled,profile_private,comments_moderated,
         notify_session_start,notify_session_end,notify_security_incident,notify_weekly_summary,notify_friend_request,notify_live_start,
         notify_battle_start,notify_report,notify_privacy_change,notify_blocked_access,alterado_por_usuario_id,criado_em,atualizado_em)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())
        ON DUPLICATE KEY UPDATE guardian_usuario_id=VALUES(guardian_usuario_id),minor_usuario_id=VALUES(minor_usuario_id)")
        ->execute([$linkId,$guardianUsuarioId,(int)$link['minor_usuario_id'],$d['access_status'],$d['daily_limit_minutes'],$d['allowed_start_time'],$d['allowed_end_time'],$d['timezone'],
            $d['camera_enabled'],$d['farm_enabled'],$d['battle_enabled'],$d['ranking_enabled'],$d['transmission_enabled'],$d['profile_private'],$d['comments_moderated'],
            $d['notify_session_start'],$d['notify_session_end'],$d['notify_security_incident'],$d['notify_weekly_summary'],$d['notify_friend_request'],$d['notify_live_start'],
            $d['notify_battle_start'],$d['notify_report'],$d['notify_privacy_change'],$d['notify_blocked_access'],$guardianUsuarioId]);
    if(function_exists('afMinorSafetySettingsEnsure'))afMinorSafetySettingsEnsure($pdo,(int)$link['minor_usuario_id']);
    $st=$pdo->prepare('SELECT * FROM af_guardian_controls WHERE link_id=? LIMIT 1');$st->execute([$linkId]);
    return $st->fetch()?:$d;
}

function afGuardianDashboardControlsForMinor(PDO $pdo, int $minorUsuarioId): ?array
{
    $st=$pdo->prepare("SELECT c.*,l.status link_status FROM af_guardian_controls c
        JOIN af_guardian_minor_links l ON l.id=c.link_id AND l.family_confirmed_at IS NOT NULL
        JOIN af_guardian_accounts ga ON ga.usuario_id=l.guardian_usuario_id AND ga.status_verificacao='verified'
        JOIN af_guardian_manual_reviews gr ON gr.guardian_account_id=ga.id AND gr.status='approved' AND (gr.valid_until IS NULL OR gr.valid_until>NOW())
        WHERE c.minor_usuario_id=? AND l.status='active' ORDER BY c.id DESC LIMIT 1");
    $st->execute([$minorUsuarioId]);return $st->fetch()?:null;
}

function afGuardianDashboardNormalizeTime(string $value, string $fallback): string
{
    $value=trim($value);
    if(!preg_match('/^(?:[01]\d|2[0-3]):[0-5]\d$/',$value))return $fallback;
    return $value;
}

function afGuardianDashboardSaveControls(PDO $pdo, int $guardianUsuarioId, int $linkId, array $input): array
{
    $link=afGuardianDashboardLink($pdo,$guardianUsuarioId,$linkId);
    if(!afGuardianAdultVerified($pdo,$guardianUsuarioId))throw new RuntimeException('Conclua a verificação interna antes de alterar os controles.');
    if(!function_exists('afGuardianFamilyLinkConfirmed') || !afGuardianFamilyLinkConfirmed($pdo,$linkId))throw new RuntimeException('Confirme o código familiar deste dependente antes de alterar os controles.');
    $old=afGuardianDashboardEnsureControls($pdo,$guardianUsuarioId,$linkId);
    $status=(string)($input['access_status']??'active');
    if(!in_array($status,['active','paused'],true))$status='active';
    $limit=max(0,min(240,(int)($input['daily_limit_minutes']??30)));
    $start=afGuardianDashboardNormalizeTime((string)($input['allowed_start_time']??''),'08:00');
    $end=afGuardianDashboardNormalizeTime((string)($input['allowed_end_time']??''),'21:00');
    $bool=static fn(string $key):int=>!empty($input[$key])?1:0;
    $new=[
        'access_status'=>$status,'daily_limit_minutes'=>$limit,'allowed_start_time'=>$start,'allowed_end_time'=>$end,'timezone'=>APP_TIMEZONE,
        'camera_enabled'=>$bool('camera_enabled'),'farm_enabled'=>$bool('farm_enabled'),'battle_enabled'=>$bool('battle_enabled'),
        'ranking_enabled'=>$bool('ranking_enabled'),'transmission_enabled'=>0,'profile_private'=>1,'comments_moderated'=>$bool('comments_moderated'),
        'notify_session_start'=>$bool('notify_session_start'),'notify_session_end'=>$bool('notify_session_end'),
        'notify_security_incident'=>$bool('notify_security_incident'),'notify_weekly_summary'=>$bool('notify_weekly_summary'),
        'notify_friend_request'=>$bool('notify_friend_request'),'notify_live_start'=>$bool('notify_live_start'),
        'notify_battle_start'=>$bool('notify_battle_start'),'notify_report'=>$bool('notify_report'),
        'notify_privacy_change'=>$bool('notify_privacy_change'),'notify_blocked_access'=>$bool('notify_blocked_access'),
    ];
    if($new['battle_enabled'] && function_exists('afApprovedContacts') && count(afApprovedContacts($pdo,$guardianUsuarioId,$linkId,true))===0){
        throw new RuntimeException('Aprove pelo menos um contato antes de ativar o Battle.');
    }
    $pdo->beginTransaction();
    try{
        $pdo->prepare("UPDATE af_guardian_controls SET access_status=?,daily_limit_minutes=?,allowed_start_time=?,allowed_end_time=?,timezone=?,
            camera_enabled=?,farm_enabled=?,battle_enabled=?,ranking_enabled=?,transmission_enabled=?,profile_private=?,comments_moderated=?,
            notify_session_start=?,notify_session_end=?,notify_security_incident=?,notify_weekly_summary=?,notify_friend_request=?,notify_live_start=?,
            notify_battle_start=?,notify_report=?,notify_privacy_change=?,notify_blocked_access=?,alterado_por_usuario_id=?,atualizado_em=NOW()
            WHERE link_id=? AND guardian_usuario_id=?")
            ->execute([$new['access_status'],$new['daily_limit_minutes'],$new['allowed_start_time'],$new['allowed_end_time'],$new['timezone'],
                $new['camera_enabled'],$new['farm_enabled'],$new['battle_enabled'],$new['ranking_enabled'],$new['transmission_enabled'],$new['profile_private'],$new['comments_moderated'],
                $new['notify_session_start'],$new['notify_session_end'],$new['notify_security_incident'],$new['notify_weekly_summary'],$new['notify_friend_request'],$new['notify_live_start'],
                $new['notify_battle_start'],$new['notify_report'],$new['notify_privacy_change'],$new['notify_blocked_access'],$guardianUsuarioId,$linkId,$guardianUsuarioId]);
        $minorId=(int)$link['minor_usuario_id'];
        $pdo->prepare('UPDATE af_perfis SET perfil_privado=1,cidade=NULL,estado=NULL,atualizado_em=NOW() WHERE usuario_id=?')->execute([$minorId]);
        if(afSafetyTableExists($pdo,'af_minor_safety_settings')){
            $pdo->prepare("UPDATE af_minor_safety_settings SET profile_private=1,hide_city=1,hide_location=1,comments_mode=?,updated_at=NOW() WHERE minor_usuario_id=?")
                ->execute([$new['comments_moderated']?'moderated':'disabled',$minorId]);
        }
        if(function_exists('afMinorFeaturePermissionSet')){
            afMinorFeaturePermissionSet($pdo,$minorId,'camera',(bool)$new['camera_enabled'],$guardianUsuarioId,$linkId);
            afMinorFeaturePermissionSet($pdo,$minorId,'body_processing',(bool)$new['camera_enabled'],$guardianUsuarioId,$linkId);
            afMinorFeaturePermissionSet($pdo,$minorId,'farm',(bool)$new['farm_enabled'],$guardianUsuarioId,$linkId);
            afMinorFeaturePermissionSet($pdo,$minorId,'battle',(bool)$new['battle_enabled'],$guardianUsuarioId,$linkId);
            afMinorFeaturePermissionSet($pdo,$minorId,'ranking_alias',(bool)$new['ranking_enabled'],$guardianUsuarioId,$linkId);
            afMinorFeaturePermissionSet($pdo,$minorId,'live',false,$guardianUsuarioId,$linkId);
        }
        $pdo->prepare("INSERT INTO af_guardian_control_audit
            (link_id,guardian_usuario_id,minor_usuario_id,action_key,old_values_json,new_values_json,ip_address,user_agent,device_uuid,criado_em)
            VALUES (?,?,?,?,?,?,?,?,?,NOW())")
            ->execute([$linkId,$guardianUsuarioId,$minorId,'controls_updated',json_encode($old,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),json_encode($new,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),clientIp(),substr((string)($_SERVER['HTTP_USER_AGENT']??''),0,1000),deviceUuid()]);
        $pdo->commit();
    }catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();throw $e;}
    if(function_exists('afMinorPolicyClearCache'))afMinorPolicyClearCache((int)$link['minor_usuario_id']);
    criarNotificacao($pdo,(int)$link['minor_usuario_id'],'guardian_controls_updated','Controles atualizados','Seu responsável atualizou as permissões, horários ou limites da conta.',['link_id'=>$linkId]);
    afGuardianDashboardCreateAlert($pdo,(int)$link['minor_usuario_id'],'privacy_change','info','Controles de privacidade atualizados','As permissões do dependente foram atualizadas pelo responsável.',['link_id'=>$linkId],'guardian_controls',$linkId);
    return afGuardianDashboardEnsureControls($pdo,$guardianUsuarioId,$linkId);
}

function afGuardianDashboardUsageSeconds(PDO $pdo, int $minorUsuarioId, ?string $date = null): int
{
    $date=$date&&preg_match('/^\d{4}-\d{2}-\d{2}$/',$date)?$date:date('Y-m-d');
    $st=$pdo->prepare("SELECT COALESCE(SUM(CASE
        WHEN iniciada_em IS NULL THEN 0
        WHEN finalizada_em IS NOT NULL THEN GREATEST(0,LEAST(?,TIMESTAMPDIFF(SECOND,iniciada_em,finalizada_em)))
        WHEN status='em_andamento' THEN GREATEST(0,LEAST(?,TIMESTAMPDIFF(SECOND,iniciada_em,COALESCE(LEAST(NOW(),expira_em),NOW()))))
        ELSE 0 END),0)
        FROM af_partidas WHERE usuario_id=? AND DATE(iniciada_em)=? AND status IN ('em_andamento','finalizada')");
    $st->execute([SESSAO_DURACAO,SESSAO_DURACAO,$minorUsuarioId,$date]);return (int)$st->fetchColumn();
}

function afGuardianDashboardAccessDecision(PDO $pdo, int $minorUsuarioId): array
{
    $controls=afGuardianDashboardControlsForMinor($pdo,$minorUsuarioId);
    if(!$controls)return ['allowed'=>false,'code'=>'PARENTAL_CONTROLS_REQUIRED','message'=>'O responsável precisa configurar os controles da conta.','controls'=>null,'used_seconds'=>0,'remaining_seconds'=>0];
    if((string)$controls['access_status']==='paused')return ['allowed'=>false,'code'=>'PARENTAL_ACCESS_PAUSED','message'=>'O responsável pausou temporariamente o acesso aos recursos de jogo.','controls'=>$controls,'used_seconds'=>0,'remaining_seconds'=>0];
    $now=date('H:i');$start=substr((string)$controls['allowed_start_time'],0,5);$end=substr((string)$controls['allowed_end_time'],0,5);
    $inside=$start===$end || ($start<$end ? ($now>=$start&&$now<$end) : ($now>=$start||$now<$end));
    if(!$inside)return ['allowed'=>false,'code'=>'OUTSIDE_GUARDIAN_HOURS','message'=>'Este recurso está disponível apenas entre '.$start.' e '.$end.'.','controls'=>$controls,'used_seconds'=>afGuardianDashboardUsageSeconds($pdo,$minorUsuarioId),'remaining_seconds'=>0];
    $used=afGuardianDashboardUsageSeconds($pdo,$minorUsuarioId);$limitMin=(int)$controls['daily_limit_minutes'];$limitSec=$limitMin*60;
    if($limitMin>0 && $used>=$limitSec)return ['allowed'=>false,'code'=>'DAILY_LIMIT_REACHED','message'=>'O limite diário definido pelo responsável foi atingido.','controls'=>$controls,'used_seconds'=>$used,'remaining_seconds'=>0];
    return ['allowed'=>true,'code'=>'PARENTAL_CONTROLS_ALLOWED','message'=>'Controles parentais liberados.','controls'=>$controls,'used_seconds'=>$used,'remaining_seconds'=>$limitMin>0?max(0,$limitSec-$used):0];
}

function afGuardianDashboardRecentSessions(PDO $pdo, int $minorUsuarioId, int $limit = 10): array
{
    $limit=max(1,min(50,$limit));
    $st=$pdo->prepare("SELECT p.id,p.status,p.modo,p.aura_gerada,p.pontuacao_total,p.pontuacao_validada,p.antifraude_status,
        p.iniciada_em,p.finalizada_em,p.duracao_real_segundos,
        sc.pause_total_seconds,sc.multiple_people_incidents,sc.no_person_incidents,sc.visibility_incidents,sc.camera_incidents,sc.lighting_incidents,sc.lighting_score,sc.lighting_ok,sc.privacy_mode
        FROM af_partidas p LEFT JOIN af_safe_camera_sessions sc ON sc.partida_id=p.id
        WHERE p.usuario_id=? ORDER BY p.id DESC LIMIT {$limit}");
    $st->execute([$minorUsuarioId]);return $st->fetchAll()?:[];
}

function afGuardianDashboardRecentIncidents(PDO $pdo, int $minorUsuarioId, int $limit = 12): array
{
    $limit=max(1,min(50,$limit));
    $st=$pdo->prepare("SELECT e.id,e.event_type,e.person_count,e.criado_em,e.partida_id,e.details_json
        FROM af_safe_camera_events e WHERE e.usuario_id=? AND e.event_type IN ('multiple_people','poor_lighting','camera_lost','detector_unavailable','privacy_unavailable','tab_hidden')
        ORDER BY e.id DESC LIMIT {$limit}");
    $st->execute([$minorUsuarioId]);return $st->fetchAll()?:[];
}

function afGuardianDashboardStats(PDO $pdo, int $minorUsuarioId): array
{
    $st=$pdo->prepare("SELECT COUNT(*) sessions_30,SUM(status='finalizada') completed_30,COALESCE(SUM(COALESCE(duracao_real_segundos,0)),0) seconds_30,
        MAX(COALESCE(finalizada_em,iniciada_em,criada_em)) last_activity
        FROM af_partidas WHERE usuario_id=? AND criada_em>=DATE_SUB(NOW(),INTERVAL 30 DAY)");$st->execute([$minorUsuarioId]);$m=$st->fetch()?:[];
    $st=$pdo->prepare("SELECT COUNT(*) incidents_30,COALESCE(SUM(event_type='multiple_people'),0) multiple_30,COALESCE(SUM(event_type='poor_lighting'),0) lighting_30
        FROM af_safe_camera_events WHERE usuario_id=? AND criado_em>=DATE_SUB(NOW(),INTERVAL 30 DAY) AND event_type IN ('multiple_people','poor_lighting','camera_lost','detector_unavailable','privacy_unavailable','tab_hidden')");$st->execute([$minorUsuarioId]);$s=$st->fetch()?:[];
    return array_merge($m,$s,['used_today_seconds'=>afGuardianDashboardUsageSeconds($pdo,$minorUsuarioId)]);
}

function afGuardianDashboardCreateAlert(PDO $pdo, int $minorUsuarioId, string $type, string $severity, string $title, string $message, array $details = [], ?string $referenceType = null, ?int $referenceId = null): void
{
    try{
        $st=$pdo->prepare("SELECT l.id link_id,l.guardian_usuario_id,c.*
            FROM af_guardian_minor_links l LEFT JOIN af_guardian_controls c ON c.link_id=l.id
            WHERE l.minor_usuario_id=? AND l.status='active' ORDER BY l.id DESC LIMIT 1");$st->execute([$minorUsuarioId]);$row=$st->fetch();if(!$row)return;
        $pref=match($type){
            'session_start'=>'notify_session_start','session_end'=>'notify_session_end','friend_request'=>'notify_friend_request',
            'live_start'=>'notify_live_start','battle_start','battle_invite'=>'notify_battle_start','report','serious_incident'=>'notify_report',
            'privacy_change'=>'notify_privacy_change','blocked_access'=>'notify_blocked_access',default=>str_starts_with($type,'security_')?'notify_security_incident':null,
        };
        if($pref!==null && array_key_exists($pref,$row) && empty($row[$pref]))return;
        $cooldown=max(1,min(1440,(int)afGuardianDashboardConfig($pdo,'guardian_alert_cooldown_minutes',30)));
        $st=$pdo->prepare("SELECT id FROM af_guardian_alerts WHERE guardian_usuario_id=? AND minor_usuario_id=? AND type_key=? AND criado_em>=DATE_SUB(NOW(),INTERVAL {$cooldown} MINUTE) AND (? IS NULL OR reference_id=?) LIMIT 1");
        $st->execute([(int)$row['guardian_usuario_id'],$minorUsuarioId,$type,$referenceId,$referenceId]);if($st->fetchColumn())return;
        $pdo->prepare("INSERT INTO af_guardian_alerts
            (link_id,guardian_usuario_id,minor_usuario_id,type_key,severity,title,message,reference_type,reference_id,details_json,criado_em,atualizado_em)
            VALUES (?,?,?,?,?,?,?,?,?,?,NOW(),NOW())")
            ->execute([(int)$row['link_id'],(int)$row['guardian_usuario_id'],$minorUsuarioId,substr($type,0,60),in_array($severity,['info','warning','critical'],true)?$severity:'info',substr($title,0,180),substr($message,0,500),$referenceType?substr($referenceType,0,60):null,$referenceId,$details?json_encode($details,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES):null]);
        criarNotificacao($pdo,(int)$row['guardian_usuario_id'],'guardian_'.$type,$title,$message,['minor_user_id'=>$minorUsuarioId,'reference_type'=>$referenceType,'reference_id'=>$referenceId]);
    }catch(Throwable $e){if(defined('APP_DEBUG')&&APP_DEBUG)error_log('[AURA-GUARDIAN-ALERT] '.$e->getMessage());}
}

function afGuardianDashboardAlerts(PDO $pdo, int $guardianUsuarioId, int $limit = 30, bool $onlyUnread = false): array
{
    $limit=max(1,min(100,$limit));$extra=$onlyUnread?' AND a.read_at IS NULL':'';
    $st=$pdo->prepare("SELECT a.*,u.nome minor_nome,u.aura_id FROM af_guardian_alerts a JOIN af_usuarios u ON u.id=a.minor_usuario_id
        WHERE a.guardian_usuario_id=? {$extra} ORDER BY a.id DESC LIMIT {$limit}");$st->execute([$guardianUsuarioId]);return $st->fetchAll()?:[];
}

function afGuardianDashboardMarkAlert(PDO $pdo, int $guardianUsuarioId, int $alertId, bool $resolved = false): void
{
    $sql=$resolved?'UPDATE af_guardian_alerts SET read_at=COALESCE(read_at,NOW()),resolved_at=NOW(),atualizado_em=NOW() WHERE id=? AND guardian_usuario_id=?':'UPDATE af_guardian_alerts SET read_at=NOW(),atualizado_em=NOW() WHERE id=? AND guardian_usuario_id=?';
    $pdo->prepare($sql)->execute([$alertId,$guardianUsuarioId]);
}

function afGuardianDashboardApiControls(array $c, array $access = []): array
{
    return [
        'access_status'=>(string)($c['access_status']??'active'),
        'daily_limit_minutes'=>(int)($c['daily_limit_minutes']??0),
        'allowed_start_time'=>substr((string)($c['allowed_start_time']??''),0,5),
        'allowed_end_time'=>substr((string)($c['allowed_end_time']??''),0,5),
        'features'=>[
            'camera'=>!empty($c['camera_enabled']),'farm'=>!empty($c['farm_enabled']),'battle'=>!empty($c['battle_enabled']),
            'ranking'=>!empty($c['ranking_enabled']),'transmission'=>!empty($c['transmission_enabled']),'profile_private'=>!empty($c['profile_private']),
            'comments_moderated'=>!empty($c['comments_moderated']),
        ],
        'notifications'=>[
            'session_start'=>!empty($c['notify_session_start']),'session_end'=>!empty($c['notify_session_end']),
            'security_incident'=>!empty($c['notify_security_incident']),'weekly_summary'=>!empty($c['notify_weekly_summary']),
            'friend_request'=>!empty($c['notify_friend_request']),'live_start'=>!empty($c['notify_live_start']),
            'battle_start'=>!empty($c['notify_battle_start']),'report'=>!empty($c['notify_report']),
            'privacy_change'=>!empty($c['notify_privacy_change']),'blocked_access'=>!empty($c['notify_blocked_access']),
        ],
        'access'=>['allowed'=>(bool)($access['allowed']??false),'code'=>(string)($access['code']??''),'message'=>(string)($access['message']??''),'used_seconds'=>(int)($access['used_seconds']??0),'remaining_seconds'=>(int)($access['remaining_seconds']??0)]
    ];
}
