<?php
declare(strict_types=1);
require_once __DIR__.'/common.php';

apiMethod('POST');
$cfg=apiCfg($mysqli);$device=apiAuth($mysqli);$payload=apiJson();$id=(int)$device['id'];
$text=static fn(string $key,int $max=500):string=>apiText($payload[$key]??'',$max);
$type=strtoupper($text('device_type',20));if(!in_array($type,['TABLET','SMARTPHONE','OUTRO'],true))$type=(string)$device['tipo_dispositivo'];
$fields=[
 'fabricante'=>$text('manufacturer',120),'marca'=>$text('brand',120),'modelo'=>$text('model',180),'device_name'=>$text('device_name',180),
 'android_version'=>$text('android_version',40),'security_patch'=>$text('security_patch',30),'build_id'=>$text('build_id',120),
 'build_fingerprint'=>$text('build_fingerprint',500),'arquitetura'=>$text('architecture',120),'bateria_status'=>$text('battery_status',60),
 'bateria_fonte'=>$text('battery_source',60),'rede_tipo'=>$text('network_type',60),'ip_local'=>$text('local_ip',80),
 'resolucao_tela'=>$text('screen_resolution',80),'densidade_tela'=>$text('screen_density',80),'app_version'=>$text('app_version',40)
];
$ints=[
 'sdk_int'=>apiInt($payload['sdk_int']??0,0,100,'sdk_int'),'cpu_cores'=>apiInt($payload['cpu_cores']??0,0,1024,'cpu_cores'),
 'ram_total_mb'=>apiInt($payload['ram_total_mb']??0,0,1048576,'ram_total_mb'),'ram_disponivel_mb'=>apiInt($payload['ram_available_mb']??0,0,1048576,'ram_available_mb'),
 'armazenamento_total_mb'=>apiInt($payload['storage_total_mb']??0,0,16777216,'storage_total_mb'),'armazenamento_livre_mb'=>apiInt($payload['storage_free_mb']??0,0,16777216,'storage_free_mb'),
 'bateria_percentual'=>apiInt($payload['battery_percent']??0,0,100,'battery_percent'),'app_version_code'=>apiInt($payload['app_version_code']??0,0,1000000000,'app_version_code')
];
$storageUsed=max(0,$ints['armazenamento_total_mb']-$ints['armazenamento_livre_mb']);
$charging=!empty($payload['battery_charging'])?1:0;
$temperature=is_numeric($payload['battery_temperature']??null)?max(-50.0,min(120.0,(float)$payload['battery_temperature'])):null;
$remoteIp=apiIp();$collected=$text('collected_at',30);$collected=($collected&&strtotime($collected))?date('Y-m-d H:i:s',strtotime($collected)):date('Y-m-d H:i:s');

$watched=['fabricante'=>'Fabricante','modelo'=>'Modelo','android_version'=>'Android','security_patch'=>'Security patch','arquitetura'=>'Arquitetura','ram_total_mb'=>'RAM','armazenamento_total_mb'=>'Armazenamento','ip_local'=>'IP'];
foreach($watched as $key=>$label){$new=array_key_exists($key,$fields)?$fields[$key]:$ints[$key];$old=$device[$key]??null;if((string)$new!==''&&(string)$old!==''&&(string)$new!==(string)$old)apiEvent($mysqli,$id,'MUDANCA_'.strtoupper($key),'ATENCAO',$label.' alterado',(string)$old,(string)$new,'Alteração detectada automaticamente.','AGENTE');}

$apps=is_array($payload['apps']??null)?array_slice($payload['apps'],0,100):[];
$appsJson=json_encode($apps,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)?:'[]';$appsHash=hash('sha256',$appsJson);
$summary=$fields+$ints+['type'=>$type,'storage_used'=>$storageUsed,'charging'=>$charging,'temperature'=>$temperature,'apps_hash'=>$appsHash];
$summaryHash=hash('sha256',json_encode($summary,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)?:'');

$stmt=$mysqli->prepare("UPDATE ti_mobile_dispositivos SET tipo_dispositivo=?,fabricante=?,marca=?,modelo=?,device_name=?,android_version=?,sdk_int=NULLIF(?,0),security_patch=?,build_id=?,build_fingerprint=?,arquitetura=?,cpu_cores=NULLIF(?,0),ram_total_mb=NULLIF(?,0),ram_disponivel_mb=NULLIF(?,0),armazenamento_total_mb=NULLIF(?,0),armazenamento_usado_mb=?,armazenamento_livre_mb=NULLIF(?,0),bateria_percentual=?,bateria_carregando=?,bateria_temperatura=?,bateria_status=?,bateria_fonte=?,rede_tipo=?,ip_local=?,resolucao_tela=?,densidade_tela=?,app_version=?,app_version_code=?,apps_hash=?,ultima_comunicacao=NOW(),ultimo_ip_remoto=? WHERE id=?");
$stmt->bind_param('ssssssissssiiiiiiiidsssssssissi',$type,$fields['fabricante'],$fields['marca'],$fields['modelo'],$fields['device_name'],$fields['android_version'],$ints['sdk_int'],$fields['security_patch'],$fields['build_id'],$fields['build_fingerprint'],$fields['arquitetura'],$ints['cpu_cores'],$ints['ram_total_mb'],$ints['ram_disponivel_mb'],$ints['armazenamento_total_mb'],$storageUsed,$ints['armazenamento_livre_mb'],$ints['bateria_percentual'],$charging,$temperature,$fields['bateria_status'],$fields['bateria_fonte'],$fields['rede_tipo'],$fields['ip_local'],$fields['resolucao_tela'],$fields['densidade_tela'],$fields['app_version'],$ints['app_version_code'],$appsHash,$remoteIp,$id);
if(!$stmt->execute()){$stmt->close();apiOut(500,['ok'=>false,'message'=>'Falha ao atualizar o dispositivo.']);}$stmt->close();

$storagePct=$ints['armazenamento_total_mb']>0?($ints['armazenamento_livre_mb']/$ints['armazenamento_total_mb']*100):100.0;$critical=(int)($cfg['storage_critical_percent']??10);
if($storagePct<=$critical){$stmt=$mysqli->prepare("SELECT id FROM ti_mobile_eventos WHERE dispositivo_id=? AND tipo='ARMAZENAMENTO_CRITICO' AND resolvido=0 LIMIT 1");$stmt->bind_param('i',$id);$stmt->execute();$exists=$stmt->get_result()->fetch_assoc();$stmt->close();if(!$exists)apiEvent($mysqli,$id,'ARMAZENAMENTO_CRITICO','CRITICO','Armazenamento crítico',null,round($storagePct,1).'%',round($ints['armazenamento_livre_mb']/1024,1).' GB livres.','AGENTE');}
else{$stmt=$mysqli->prepare("UPDATE ti_mobile_eventos SET resolvido=1,status_revisao='RESOLVIDO',resolvido_por='SISTEMA',resolvido_em=NOW() WHERE dispositivo_id=? AND tipo='ARMAZENAMENTO_CRITICO' AND resolvido=0");$stmt->bind_param('i',$id);$stmt->execute();$stmt->close();}

$policyAlerts=[];
if($ints['sdk_int']>0&&$ints['sdk_int']<(int)($cfg['min_android_sdk']??29))$policyAlerts['ANDROID_ANTIGO']=['Android abaixo da política mínima',(string)$ints['sdk_int']];
$patchTime=strtotime($fields['security_patch']);if($patchTime&&time()-$patchTime>(int)($cfg['security_patch_max_age_days']??365)*86400)$policyAlerts['PATCH_ANTIGO']=['Security patch antigo',$fields['security_patch']];
foreach(['ANDROID_ANTIGO','PATCH_ANTIGO'] as $alertType){if(isset($policyAlerts[$alertType])){[$title,$value]=$policyAlerts[$alertType];$stmt=$mysqli->prepare('SELECT id FROM ti_mobile_eventos WHERE dispositivo_id=? AND tipo=? AND resolvido=0 LIMIT 1');$stmt->bind_param('is',$id,$alertType);$stmt->execute();$open=$stmt->get_result()->fetch_assoc();$stmt->close();if(!$open)apiEvent($mysqli,$id,$alertType,'ATENCAO',$title,null,$value,'Política configurada no inventário Android.','AGENTE');}else{$stmt=$mysqli->prepare("UPDATE ti_mobile_eventos SET resolvido=1,status_revisao='RESOLVIDO',resolvido_por='SISTEMA',resolvido_em=NOW() WHERE dispositivo_id=? AND tipo=? AND resolvido=0");$stmt->bind_param('is',$id,$alertType);$stmt->execute();$stmt->close();}}

if(!empty($cfg['collect_apps'])&&$apps){
 $catalog=[];foreach(apiTrackedApps($mysqli) as $tracked)$catalog[(string)$tracked['package_name']]=$tracked;
 $mysqli->begin_transaction();try{
  $stmt=$mysqli->prepare("INSERT INTO ti_mobile_apps(dispositivo_id,package_name,app_label,version_name,version_code,instalado,obrigatorio,system_app,primeira_deteccao,ultima_deteccao,ativo) VALUES(?,?,?,?,?,?,?,?,NOW(),NOW(),1) ON DUPLICATE KEY UPDATE app_label=VALUES(app_label),version_name=VALUES(version_name),version_code=VALUES(version_code),instalado=VALUES(instalado),obrigatorio=VALUES(obrigatorio),system_app=VALUES(system_app),ultima_deteccao=NOW(),ativo=1");
  foreach($apps as $app){if(!is_array($app))continue;$package=$textValue=apiText($app['package']??'',220);if($package===''||!isset($catalog[$package]))continue;$label=apiText($app['label']??$catalog[$package]['label'],220);$version=apiText($app['version_name']??'',120)?:null;$versionCode=max(0,(int)($app['version_code']??0));$installed=!empty($app['installed'])?1:0;$required=!empty($catalog[$package]['required'])?1:0;$system=!empty($app['system_app'])?1:0;$stmt->bind_param('isssiiii',$id,$package,$label,$version,$versionCode,$installed,$required,$system);$stmt->execute();
   if($required&&!$installed){$check=$mysqli->prepare("SELECT id FROM ti_mobile_eventos WHERE dispositivo_id=? AND tipo='APP_OBRIGATORIO_AUSENTE' AND valor_novo=? AND resolvido=0 LIMIT 1");$check->bind_param('is',$id,$package);$check->execute();$missing=$check->get_result()->fetch_assoc();$check->close();if(!$missing)apiEvent($mysqli,$id,'APP_OBRIGATORIO_AUSENTE','ATENCAO','Aplicativo obrigatório ausente',null,$package,$label.' não foi detectado.','AGENTE');}
   if($installed){$resolve=$mysqli->prepare("UPDATE ti_mobile_eventos SET resolvido=1,status_revisao='RESOLVIDO',resolvido_por='SISTEMA',resolvido_em=NOW() WHERE dispositivo_id=? AND tipo='APP_OBRIGATORIO_AUSENTE' AND valor_novo=? AND resolvido=0");$resolve->bind_param('is',$id,$package);$resolve->execute();$resolve->close();}
  }$stmt->close();$mysqli->commit();
 }catch(Throwable){$mysqli->rollback();}
}

$lastFull=strtotime((string)($device['ultima_sincronizacao_completa']??''))?:0;$needSnapshot=time()-$lastFull>=6*3600||($device['apps_hash']??'')!==$appsHash;
if($needSnapshot){$json=json_encode($payload,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);$stmt=$mysqli->prepare('INSERT INTO ti_mobile_sincronizacoes(dispositivo_id,coletado_em,resumo_hash,payload_json,ip_remoto,app_version,app_version_code) VALUES(?,?,?,?,?,?,?)');$stmt->bind_param('isssssi',$id,$collected,$summaryHash,$json,$remoteIp,$fields['app_version'],$ints['app_version_code']);$stmt->execute();$stmt->close();$stmt=$mysqli->prepare('UPDATE ti_mobile_dispositivos SET ultima_sincronizacao_completa=NOW() WHERE id=?');$stmt->bind_param('i',$id);$stmt->execute();$stmt->close();}

apiOut(200,['ok'=>true,'server_time'=>date(DATE_ATOM),'sync_interval_min'=>(int)($cfg['sync_interval_min']??30),'collect_apps'=>(bool)($cfg['collect_apps']??1),'current_app_version'=>(string)($cfg['current_app_version']??'1.0.0'),'current_app_version_code'=>(int)($cfg['current_app_version_code']??1),'tracked_apps'=>apiTrackedApps($mysqli)]);
?>
