<?php
require_once __DIR__ . '/../includes/config.php';
header('Content-Type: application/json; charset=utf-8');

function apk_input($key, $default=''){
    static $json = null;
    if ($json === null) {
        $raw = file_get_contents('php://input');
        $tmp = json_decode($raw, true);
        $json = is_array($tmp) ? $tmp : [];
    }
    if (isset($_POST[$key])) return trim((string)$_POST[$key]);
    if (isset($_GET[$key])) return trim((string)$_GET[$key]);
    if (isset($json[$key])) return trim((string)$json[$key]);
    return $default;
}

function abs_asset_url_apk($path){
    $path = (string)$path;
    if ($path === '') return '';
    if (preg_match('~^https?://~i', $path)) return $path;
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $base = $scheme.'://'.($_SERVER['HTTP_HOST'] ?? '').rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/\\');
    return $base.'/'.ltrim($path, '/');
}

function find_app_appearance_apk($db, $type, $id){
    $st=$db->prepare('SELECT * FROM app_appearance WHERE owner_type=:t AND owner_id=:id AND is_active=1 LIMIT 1');
    $st->bindValue(':t',$type,SQLITE3_TEXT);
    $st->bindValue(':id',(int)$id,SQLITE3_INTEGER);
    $r=$st->execute()->fetchArray(SQLITE3_ASSOC);
    return $r ?: null;
}

$db = db();

$mac = normalize_mac_value(apk_input('mac'));
$android_id = normalize_mac_value(apk_input('android_id', apk_input('androidId')));
$device_key = $android_id !== '' ? $android_id : $mac;
$modelo = apk_input('modelo', apk_input('model'));
$app_version = apk_input('app_version', apk_input('version'));
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
if (strpos($ip, ',') !== false) $ip = trim(explode(',', $ip)[0]);

if ($device_key === '') {
    echo json_encode(['success'=>false,'authorized'=>false,'error'=>'MAC/ID ausente'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    exit;
}

$now = date('Y-m-d H:i:s');

$st = $db->prepare('SELECT * FROM client_macs WHERE mac=:mac LIMIT 1');
$st->bindValue(':mac',$device_key,SQLITE3_TEXT);
$row = $st->execute()->fetchArray(SQLITE3_ASSOC);

if (!$row) {
    // Registro pendente apenas para o ADMIN visualizar. Não vincula automaticamente a nenhuma revenda.
    $st=$db->prepare("INSERT INTO client_macs(mac,cliente_nome,usuario,senha,owner_type,owner_id,notes,is_active,status,modelo,app_version,ip,first_seen,last_seen)
                      VALUES(:mac,'','','','admin',0,'Pendente: cliente precisa enviar este MAC para a revenda.',0,'pendente',:modelo,:app_version,:ip,:now,:now)");
    $st->bindValue(':mac',$device_key,SQLITE3_TEXT);
    $st->bindValue(':modelo',$modelo,SQLITE3_TEXT);
    $st->bindValue(':app_version',$app_version,SQLITE3_TEXT);
    $st->bindValue(':ip',$ip,SQLITE3_TEXT);
    $st->bindValue(':now',$now,SQLITE3_TEXT);
    $st->execute();
    echo json_encode([
        'success'=>true,
        'authorized'=>false,
        'status'=>'pendente',
        'device_id'=>$device_key,
        'message'=>'Dispositivo não liberado. Envie este MAC/ID para sua revenda.'
    ], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    exit;
}

// Bloqueio automático por vencimento do cliente/MAC.
if (function_exists('expiry_days_left')) {
    $expiresAtCheck = (string)($row['expires_at'] ?? '');
    $daysLeftCheck = expiry_days_left($expiresAtCheck);
    if ($daysLeftCheck !== null && $daysLeftCheck < 0 && (int)get_setting('expiry_auto_block_enabled','1') === 1) {
        $auto=$db->prepare("UPDATE client_macs SET is_active=0,status='bloqueado',auto_blocked=1,updated_at=:now WHERE id=:id");
        $auto->bindValue(':now',$now,SQLITE3_TEXT);
        $auto->bindValue(':id',(int)$row['id'],SQLITE3_INTEGER);
        $auto->execute();
        $row['is_active']=0;
        $row['status']='bloqueado';
    }
}

// Atualiza última atividade sem alterar dono.
$up=$db->prepare('UPDATE client_macs SET modelo=:modelo, app_version=:app_version, ip=:ip, last_seen=:now WHERE id=:id');
$up->bindValue(':modelo',$modelo,SQLITE3_TEXT);
$up->bindValue(':app_version',$app_version,SQLITE3_TEXT);
$up->bindValue(':ip',$ip,SQLITE3_TEXT);
$up->bindValue(':now',$now,SQLITE3_TEXT);
$up->bindValue(':id',(int)$row['id'],SQLITE3_INTEGER);
$up->execute();

$is_active = (int)($row['is_active'] ?? 0) === 1;
$status = (string)($row['status'] ?? ($is_active ? 'ativo' : 'bloqueado'));
if (!$is_active || $status === 'bloqueado' || $status === 'pendente') {
    echo json_encode([
        'success'=>true,
        'authorized'=>false,
        'status'=>$status ?: 'bloqueado',
        'device_id'=>$device_key,
        'owner_type'=>(string)($row['owner_type'] ?? 'admin'),
        'owner_id'=>(int)($row['owner_id'] ?? 0),
        'expires_at'=>(string)($row['expires_at'] ?? ''),
        'auto_blocked'=>((int)($row['auto_blocked'] ?? 0) === 1),
        'message'=>'Dispositivo não liberado ou bloqueado.'
    ], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    exit;
}

$owner_type = (string)($row['owner_type'] ?? 'admin');
$owner_id = (int)($row['owner_id'] ?? 0);

$app = null;
if (in_array($owner_type, ['revenda','subrevenda','admin'], true)) {
    $app = find_app_appearance_apk($db, $owner_type, $owner_id);
}
if (!$app) $app = find_app_appearance_apk($db, 'global', 0);

echo json_encode([
    'success'=>true,
    'authorized'=>true,
        'dns_active'=>(int)($row['dns_active']??0)===1,
        'dns_service'=>($row['dns_service']??'off'),
        'dns_primary'=>($row['dns_primary']??''),
        'dns_secondary'=>($row['dns_secondary']??''),
    'status'=>'ativo',
    'device_id'=>$device_key,
    'owner_type'=>$owner_type,
    'owner_id'=>$owner_id,
    'cliente_nome'=>(string)($row['cliente_nome'] ?? ''),
    'logo_url'=>$app ? abs_asset_url_apk($app['logo_path'] ?? '') : '',
    'wallpaper_url'=>$app ? abs_asset_url_apk($app['wallpaper_path'] ?? '') : '',
    'logo_adjust'=>'fitCenter',
    'wallpaper_adjust'=>'centerCrop',
    'message'=>'Dispositivo liberado.'
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
