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

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $opacity = max(0, min(100, (int)($_POST['opacity'] ?? 45)));
    $width = max(20, min(800, (int)($_POST['width'] ?? 120)));
    $height = max(20, min(800, (int)($_POST['height'] ?? 60)));
    $target_type = trim((string)($_POST['target_type'] ?? 'global'));
    $target_value = trim((string)($_POST['target_value'] ?? ''));
    $allowedTargets = ['global','username','password','android_id','code','client_key'];
    if (!in_array($target_type, $allowedTargets, true)) $target_type = 'global';

    $current = $db->querySingle('SELECT image_path FROM screen_logo WHERE id=1', true);
    $image_path = $current['image_path'] ?? '';

    if (!empty($_FILES['logo']['name']) && is_uploaded_file($_FILES['logo']['tmp_name'])) {
        $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['png','jpg','jpeg','webp','gif'], true)) {
            $erro = 'Formato inválido. Use PNG, JPG, WEBP ou GIF.';
        } else {
            $name = 'logo_tela_'.time().'.'.$ext;
            $dest = $uploadDir.$name;
            if (move_uploaded_file($_FILES['logo']['tmp_name'], $dest)) {
                $image_path = $uploadUrl.$name;
            } else {
                $erro = 'Erro ao enviar a imagem.';
            }
        }
    }

    if ($erro === '') {
        $stmt = $db->prepare("UPDATE screen_logo SET is_active=:a,image_path=:img,position='bottom_left',opacity=:op,width=:w,height=:h,target_type=:tt,target_value=:tv,updated_at=CURRENT_TIMESTAMP WHERE id=1");
        $stmt->bindValue(':a', $is_active, SQLITE3_INTEGER);
        $stmt->bindValue(':img', $image_path, SQLITE3_TEXT);
        $stmt->bindValue(':op', $opacity, SQLITE3_INTEGER);
        $stmt->bindValue(':w', $width, SQLITE3_INTEGER);
        $stmt->bindValue(':h', $height, SQLITE3_INTEGER);
        $stmt->bindValue(':tt', $target_type, SQLITE3_TEXT);
        $stmt->bindValue(':tv', $target_value, SQLITE3_TEXT);
        $stmt->execute();
        $msg = 'Configuração da logo salva com sucesso.';
    }
}

$row = $db->querySingle('SELECT * FROM screen_logo WHERE id=1', true);
if (!$row) {
    $db->exec("INSERT INTO screen_logo(id,is_active,image_path,position,opacity,width,height,target_type,target_value) VALUES(1,0,'','bottom_left',45,120,60,'global','')");
    $row = $db->querySingle('SELECT * FROM screen_logo WHERE id=1', true);
}

require_once __DIR__.'/includes/header.php';
?>
<div class="card">
    <h1>Logo na Tela do Canal</h1>
    <p>Configure a logo que aparece no canto inferior esquerdo do player.</p>

    <?php if($msg): ?><div class="ok"><?=htmlspecialchars($msg)?></div><?php endif; ?>
    <?php if($erro): ?><div class="err"><?=htmlspecialchars($erro)?></div><?php endif; ?>

    <form method="post" enctype="multipart/form-data">
        <label><input type="checkbox" name="is_active" value="1" <?=((int)($row['is_active'] ?? 0)===1?'checked':'')?>> Ativar logo no canal</label>

        <label>Enviar logo</label>
        <input type="file" name="logo" accept="image/png,image/jpeg,image/webp,image/gif">

        <?php if(!empty($row['image_path'])): ?>
            <p>Logo atual:</p>
            <div style="background:#000;border:1px solid #333;border-radius:12px;padding:18px;display:inline-block">
                <img src="<?=htmlspecialchars($row['image_path'])?>" style="max-width:240px;max-height:120px;opacity:<?=((int)$row['opacity'])/100?>">
            </div>
        <?php endif; ?>

        <label>Transparência / Mesclar com a imagem</label>
        <input type="range" name="opacity" min="0" max="100" value="<?=htmlspecialchars((string)($row['opacity'] ?? 45))?>" oninput="document.getElementById('opv').innerText=this.value+'%'">
        <b id="opv"><?=htmlspecialchars((string)($row['opacity'] ?? 45))?>%</b>

        <label>Largura da logo (px)</label>
        <input type="number" name="width" min="20" max="800" value="<?=htmlspecialchars((string)($row['width'] ?? 120))?>">

        <label>Altura da logo (px)</label>
        <input type="number" name="height" min="20" max="800" value="<?=htmlspecialchars((string)($row['height'] ?? 60))?>">

        <label>Destino</label>
        <select name="target_type">
            <?php
            $targets = ['global'=>'Todos','username'=>'Usuário','password'=>'Senha','android_id'=>'Android ID','code'=>'Código','client_key'=>'Chave do cliente'];
            foreach($targets as $k=>$v){
                $sel = (($row['target_type'] ?? 'global') === $k) ? 'selected' : '';
                echo '<option value="'.htmlspecialchars($k).'" '.$sel.'>'.htmlspecialchars($v).'</option>';
            }
            ?>
        </select>

        <label>Valor do destino individual</label>
        <input type="text" name="target_value" value="<?=htmlspecialchars((string)($row['target_value'] ?? ''))?>" placeholder="Deixe vazio quando for Todos">

        <button type="submit">Salvar Logo</button>
    </form>
</div>
<?php require_once __DIR__.'/includes/footer.php'; ?>
