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

$db = db();

$owner_type = trim((string)($_GET['owner_type'] ?? $_POST['owner_type'] ?? 'global'));
$owner_id = (int)($_GET['owner_id'] ?? $_POST['owner_id'] ?? 0);
$username = trim((string)($_GET['username'] ?? $_POST['username'] ?? ''));
$mac = normalize_mac_value($_GET['mac'] ?? $_POST['mac'] ?? '');
$android_id = normalize_mac_value($_GET['android_id'] ?? $_POST['android_id'] ?? ($_GET['androidId'] ?? $_POST['androidId'] ?? ''));
$device_key = $android_id !== '' ? $android_id : $mac;

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

if (($owner_type === '' || $owner_type === 'auto') && $device_key !== '') {
    $st=$db->prepare('SELECT owner_type, owner_id, is_active, status FROM client_macs WHERE mac=:mac LIMIT 1');
    $st->bindValue(':mac',$device_key,SQLITE3_TEXT);
    $r=$st->execute()->fetchArray(SQLITE3_ASSOC);
    if($r && (int)($r['is_active'] ?? 0)===1 && (($r['status'] ?? 'ativo')==='ativo')){
        $owner_type=(string)$r['owner_type'];
        $owner_id=(int)$r['owner_id'];
    }
}

if (($owner_type === '' || $owner_type === 'auto') && $username !== '') {
    $st=$db->prepare('SELECT id FROM revendas WHERE usuario=:u LIMIT 1');
    $st->bindValue(':u',$username,SQLITE3_TEXT);
    $r=$st->execute()->fetchArray(SQLITE3_ASSOC);
    if($r){ $owner_type='revenda'; $owner_id=(int)$r['id']; }
    else{
        $st=$db->prepare('SELECT id FROM sub_revendas WHERE usuario=:u LIMIT 1');
        $st->bindValue(':u',$username,SQLITE3_TEXT);
        $r=$st->execute()->fetchArray(SQLITE3_ASSOC);
        if($r){ $owner_type='subrevenda'; $owner_id=(int)$r['id']; }
    }
}

$row = null;
if (in_array($owner_type, ['revenda','subrevenda','admin'], true)) $row = find_appearance($db, $owner_type, $owner_id);
if (!$row) $row = find_appearance($db, 'global', 0);

if (!$row) {
    echo json_encode(['success'=>true,'active'=>false], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    exit;
}

$logo = asset_abs_url($row['logo_path'] ?? '');
$wallpaper = asset_abs_url($row['wallpaper_path'] ?? '');

echo json_encode([
    'success'=>true,
    'active'=>true,
    'owner_type'=>(string)($row['owner_type'] ?? 'global'),
    'owner_id'=>(int)($row['owner_id'] ?? 0),
    'logo_url'=>$logo,
    'wallpaper_url'=>$wallpaper,
    'logo_adjust'=>'fitCenter',
    'wallpaper_adjust'=>'centerCrop',
    'allowed_formats'=>['png','jpg','jpeg','gif'],
    'updated_at'=>(string)($row['updated_at'] ?? '')
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
