<?php
require_once __DIR__.'/includes/config.php';
require_login();

$db = db();
$msg = '';
$erro = '';

$uploadDir = __DIR__.'/images/app_assets/';
$uploadUrl = 'images/app_assets/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

function app_asset_owner_label($type, $id, $db){
    $type = (string)$type; $id = (int)$id;
    if ($type === 'global') return 'Todos / Global';
    if ($type === 'revenda') {
        $st=$db->prepare('SELECT nome,usuario FROM revendas WHERE id=:id');
        $st->bindValue(':id',$id,SQLITE3_INTEGER);
        $r=$st->execute()->fetchArray(SQLITE3_ASSOC);
        return $r ? 'Revenda: '.($r['nome'] ?: $r['usuario']) : 'Revenda #'.$id;
    }
    if ($type === 'subrevenda') {
        $st=$db->prepare('SELECT nome,usuario FROM sub_revendas WHERE id=:id');
        $st->bindValue(':id',$id,SQLITE3_INTEGER);
        $r=$st->execute()->fetchArray(SQLITE3_ASSOC);
        return $r ? 'Sub Revenda: '.($r['nome'] ?: $r['usuario']) : 'Sub Revenda #'.$id;
    }
    return 'Admin';
}

function app_asset_upload($field, $prefix, $uploadDir, $uploadUrl, &$erro){
    if (empty($_FILES[$field]['name']) || !is_uploaded_file($_FILES[$field]['tmp_name'])) return null;
    if ((int)($_FILES[$field]['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) { $erro = 'Erro no upload da imagem.'; return null; }
    $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['png','jpg','jpeg','gif'], true)) { $erro = 'Formato inválido. Use somente PNG, JPG, JPEG ou GIF.'; return null; }
    $info = @getimagesize($_FILES[$field]['tmp_name']);
    if (!$info || !in_array((int)$info[2], [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF], true)) { $erro = 'Arquivo inválido. Envie uma imagem PNG, JPG, JPEG ou GIF.'; return null; }
    $name = $prefix.'_'.date('Ymd_His').'_'.bin2hex(random_bytes(4)).'.'.$ext;
    $dest = $uploadDir.$name;
    if (!move_uploaded_file($_FILES[$field]['tmp_name'], $dest)) { $erro = 'Não foi possível salvar a imagem.'; return null; }
    @chmod($dest, 0644);
    return $uploadUrl.$name;
}

$owner_type = $_GET['owner_type'] ?? 'global';
$owner_id = (int)($_GET['owner_id'] ?? 0);
if (!in_array($owner_type, ['global','admin','revenda','subrevenda'], true)) $owner_type = 'global';
if ($owner_type === 'global' || $owner_type === 'admin') $owner_id = 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $owner_type = $_POST['owner_type'] ?? 'global';
    $owner_id = (int)($_POST['owner_id'] ?? 0);
    if (!in_array($owner_type, ['global','admin','revenda','subrevenda'], true)) $owner_type = 'global';
    if ($owner_type === 'global' || $owner_type === 'admin') $owner_id = 0;
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    $st=$db->prepare('SELECT * FROM app_appearance WHERE owner_type=:t AND owner_id=:id');
    $st->bindValue(':t',$owner_type,SQLITE3_TEXT);
    $st->bindValue(':id',$owner_id,SQLITE3_INTEGER);
    $current=$st->execute()->fetchArray(SQLITE3_ASSOC) ?: [];
    $logo_path = (string)($current['logo_path'] ?? '');
    $wallpaper_path = (string)($current['wallpaper_path'] ?? '');

    if (isset($_POST['remove_logo'])) $logo_path = '';
    if (isset($_POST['remove_wallpaper'])) $wallpaper_path = '';

    $newLogo = app_asset_upload('logo', 'logo', $uploadDir, $uploadUrl, $erro);
    if ($erro === '' && $newLogo !== null) $logo_path = $newLogo;

    $newWall = app_asset_upload('wallpaper', 'fundo', $uploadDir, $uploadUrl, $erro);
    if ($erro === '' && $newWall !== null) $wallpaper_path = $newWall;

    if ($erro === '') {
        $st=$db->prepare('INSERT OR REPLACE INTO app_appearance(owner_type,owner_id,logo_path,wallpaper_path,is_active,updated_at) VALUES(:t,:id,:l,:w,:a,CURRENT_TIMESTAMP)');
        $st->bindValue(':t',$owner_type,SQLITE3_TEXT);
        $st->bindValue(':id',$owner_id,SQLITE3_INTEGER);
        $st->bindValue(':l',$logo_path,SQLITE3_TEXT);
        $st->bindValue(':w',$wallpaper_path,SQLITE3_TEXT);
        $st->bindValue(':a',$is_active,SQLITE3_INTEGER);
        $st->execute();
        $msg = 'Aparência salva com sucesso.';
    }
}

$st=$db->prepare('SELECT * FROM app_appearance WHERE owner_type=:t AND owner_id=:id');
$st->bindValue(':t',$owner_type,SQLITE3_TEXT);
$st->bindValue(':id',$owner_id,SQLITE3_INTEGER);
$row=$st->execute()->fetchArray(SQLITE3_ASSOC) ?: ['owner_type'=>$owner_type,'owner_id'=>$owner_id,'logo_path'=>'','wallpaper_path'=>'','is_active'=>1];

$revendas=[]; $res=$db->query('SELECT id,nome,usuario FROM revendas ORDER BY nome,usuario'); while($r=$res->fetchArray(SQLITE3_ASSOC)) $revendas[]=$r;
$subrevendas=[]; $res=$db->query('SELECT id,nome,usuario FROM sub_revendas ORDER BY nome,usuario'); while($r=$res->fetchArray(SQLITE3_ASSOC)) $subrevendas[]=$r;
$all=[]; $res=$db->query('SELECT * FROM app_appearance ORDER BY CASE owner_type WHEN "global" THEN 0 WHEN "admin" THEN 1 WHEN "revenda" THEN 2 ELSE 3 END, owner_id'); while($r=$res->fetchArray(SQLITE3_ASSOC)) $all[]=$r;

include __DIR__.'/includes/header.php';
?>
<div class="card">
    <h3>🎨 Aparência do APK</h3>
    <p class="muted">Troque a logo e o papel de parede do APK pelo painel. Aceita somente PNG, JPG, JPEG e GIF. A imagem ajusta automático no aplicativo.</p>
    <?php if($msg): ?><p class="ok"><?=h($msg)?></p><?php endif; ?>
    <?php if($erro): ?><p class="bad"><?=h($erro)?></p><?php endif; ?>

    <form method="post" enctype="multipart/form-data">
        <div class="grid" style="grid-template-columns:repeat(2,minmax(0,1fr));gap:12px">
            <div>
                <label>Destino</label>
                <select name="owner_type" id="owner_type" onchange="trocarDestino()">
                    <option value="global" <?=$owner_type==='global'?'selected':''?>>Todos / Global</option>
                    <option value="admin" <?=$owner_type==='admin'?'selected':''?>>Admin</option>
                    <option value="revenda" <?=$owner_type==='revenda'?'selected':''?>>Revenda específica</option>
                    <option value="subrevenda" <?=$owner_type==='subrevenda'?'selected':''?>>Sub Revenda específica</option>
                </select>
            </div>
            <div id="box_revenda" style="display:none">
                <label>Escolher Revenda</label>
                <select name="revenda_id_select" onchange="document.getElementById('owner_id').value=this.value">
                    <option value="0">Selecione</option>
                    <?php foreach($revendas as $rv): ?><option value="<?=h($rv['id'])?>" <?=($owner_type==='revenda' && (int)$owner_id===(int)$rv['id'])?'selected':''?>><?=h($rv['nome'] ?: $rv['usuario'])?></option><?php endforeach; ?>
                </select>
            </div>
            <div id="box_subrevenda" style="display:none">
                <label>Escolher Sub Revenda</label>
                <select name="subrevenda_id_select" onchange="document.getElementById('owner_id').value=this.value">
                    <option value="0">Selecione</option>
                    <?php foreach($subrevendas as $sr): ?><option value="<?=h($sr['id'])?>" <?=($owner_type==='subrevenda' && (int)$owner_id===(int)$sr['id'])?'selected':''?>><?=h($sr['nome'] ?: $sr['usuario'])?></option><?php endforeach; ?>
                </select>
            </div>
        </div>
        <input type="hidden" name="owner_id" id="owner_id" value="<?=h($owner_id)?>">
        <label style="display:flex;gap:8px;align-items:center;margin-top:12px"><input type="checkbox" name="is_active" value="1" <?=((int)($row['is_active'] ?? 1)===1?'checked':'')?>> Ativar esta aparência</label>

        <div class="grid" style="grid-template-columns:repeat(2,minmax(0,1fr));gap:18px;margin-top:14px">
            <div class="card" style="margin:0;background:#0b1018">
                <h3>Logo do APK</h3>
                <input type="file" name="logo" accept="image/png,image/jpeg,image/gif">
                <p class="muted">Ajuste automático: centralizada, mantém proporção e não estica.</p>
                <?php if(!empty($row['logo_path'])): ?>
                    <div style="background:#000;border:1px solid #333;border-radius:14px;padding:18px;text-align:center;min-height:140px;display:flex;align-items:center;justify-content:center">
                        <img src="<?=h($row['logo_path'])?>" style="max-width:260px;max-height:130px;width:auto;height:auto;object-fit:contain">
                    </div>
                    <label style="display:flex;gap:8px;align-items:center"><input type="checkbox" name="remove_logo" value="1"> Remover logo atual</label>
                <?php endif; ?>
            </div>
            <div class="card" style="margin:0;background:#0b1018">
                <h3>Papel de parede</h3>
                <input type="file" name="wallpaper" accept="image/png,image/jpeg,image/gif">
                <p class="muted">Ajuste automático: ocupa a tela toda em celular, TV Box e Android TV.</p>
                <?php if(!empty($row['wallpaper_path'])): ?>
                    <div style="background:#000;border:1px solid #333;border-radius:14px;padding:8px;text-align:center;height:170px;overflow:hidden">
                        <img src="<?=h($row['wallpaper_path'])?>" style="width:100%;height:100%;object-fit:cover;border-radius:10px">
                    </div>
                    <label style="display:flex;gap:8px;align-items:center"><input type="checkbox" name="remove_wallpaper" value="1"> Remover papel de parede atual</label>
                <?php endif; ?>
            </div>
        </div>
        <p><button class="btn" type="submit">Salvar Aparência</button></p>
    </form>
</div>

<div class="card">
    <h3>Aparências cadastradas</h3>
    <table>
        <tr><th>Destino</th><th>Logo</th><th>Fundo</th><th>Status</th><th>Atualizado</th><th>Ações</th></tr>
        <?php foreach($all as $a): ?>
        <tr>
            <td><?=h(app_asset_owner_label($a['owner_type'],$a['owner_id'],$db))?></td>
            <td><?=!empty($a['logo_path'])?'✅':'—'?></td>
            <td><?=!empty($a['wallpaper_path'])?'✅':'—'?></td>
            <td><?=((int)$a['is_active']===1?'Ativo':'Inativo')?></td>
            <td><?=h($a['updated_at'] ?? '')?></td>
            <td><a class="btn dark" href="app_aparencia.php?owner_type=<?=h($a['owner_type'])?>&owner_id=<?=h($a['owner_id'])?>">Editar</a></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>
<script>
function trocarDestino(){
    var t=document.getElementById('owner_type').value;
    document.getElementById('box_revenda').style.display = t==='revenda' ? 'block':'none';
    document.getElementById('box_subrevenda').style.display = t==='subrevenda' ? 'block':'none';
    if(t==='global' || t==='admin') document.getElementById('owner_id').value='0';
}
trocarDestino();
</script>
<?php include __DIR__.'/includes/footer.php'; ?>
