<?php
require_once __DIR__ . '/../../includes/config.php';

$db = db();

function logo_dyn_input($key, $default=''){
    if (isset($_GET[$key])) return trim((string)$_GET[$key]);
    if (isset($_POST[$key])) return trim((string)$_POST[$key]);
    return $default;
}
function logo_dyn_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 logo_dyn_local_path($url){
    if ($url === '') return '';
    if (preg_match('~^https?://[^/]+/(.+)$~i', $url, $m)) {
        return __DIR__.'/../../'.$m[1];
    }
    return __DIR__.'/../../'.ltrim($url, '/');
}
function logo_dyn_find($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;
}

$mac = normalize_mac_value(logo_dyn_input('mac'));
$android_id = normalize_mac_value(logo_dyn_input('android_id', logo_dyn_input('androidId')));
$device_key = $android_id !== '' ? $android_id : $mac;

$owner_type = 'global';
$owner_id = 0;

if ($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'] ?? 'global');
        $owner_id=(int)($r['owner_id'] ?? 0);
    }
}

$row = null;
if (in_array($owner_type, ['admin','revenda','subrevenda'], true)) {
    $row = logo_dyn_find($db, $owner_type, $owner_id);
}
if (!$row) $row = logo_dyn_find($db, 'global', 0);
if (!$row || empty($row['logo_path'])) {
    http_response_code(404);
    exit;
}

$url = logo_dyn_abs_url($row['logo_path']);
$local = logo_dyn_local_path($url);

if (is_file($local)) {
    $ext = strtolower(pathinfo($local, PATHINFO_EXTENSION));
    if ($ext === 'png') header('Content-Type: image/png');
    elseif ($ext === 'gif') header('Content-Type: image/gif');
    else header('Content-Type: image/jpeg');
    header('Cache-Control: no-cache, no-store, must-revalidate');
    readfile($local);
    exit;
}

header('Location: '.$url, true, 302);
exit;
