<?php
// OneLauncher - configuracoes.php
require_once 'includes/auth.php';
require_once 'db.php';

$pageTitle = 'Configurações';
$nav = 'configuracoes';
$configSaved = false;
$passwordChanged = false;
$passwordError = '';
$usernameChanged = false;
$usernameError = '';

// Alterar Senha do Painel
if (isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Busca senha atual do admin logado
    $admin_id = (int) $_SESSION['admin_id'];
    $res_admin = $conn->prepare("SELECT password FROM admins WHERE id = ?");
    $res_admin->bind_param("i", $admin_id);
    $res_admin->execute();
    $row_admin = $res_admin->get_result()->fetch_assoc();

    if (!$row_admin) {
        $passwordError = 'Usuário não encontrado.';
    } elseif (!password_verify($current_password, $row_admin['password'])) {
        $passwordError = 'Senha atual incorreta.';
    } elseif (strlen($new_password) < 6) {
        $passwordError = 'A nova senha deve ter pelo menos 6 caracteres.';
    } elseif ($new_password !== $confirm_password) {
        $passwordError = 'A confirmação da nova senha não confere.';
    } else {
        $hashed = password_hash($new_password, PASSWORD_DEFAULT);
        $stmt_pw = $conn->prepare("UPDATE admins SET password = ? WHERE id = ?");
        $stmt_pw->bind_param("si", $hashed, $admin_id);
        if ($stmt_pw->execute()) {
            $passwordChanged = true;
        } else {
            $passwordError = 'Erro ao atualizar a senha. Tente novamente.';
        }
    }
}

// Alterar Nome de Usuário
if (isset($_POST['change_username'])) {
    $admin_id = (int) $_SESSION['admin_id'];
    $new_username = trim($_POST['new_username'] ?? '');
    $confirm_pw_usr = $_POST['confirm_password_username'] ?? '';

    $res_au = $conn->prepare("SELECT password FROM admins WHERE id = ?");
    $res_au->bind_param("i", $admin_id);
    $res_au->execute();
    $row_au = $res_au->get_result()->fetch_assoc();

    if (!$row_au) {
        $usernameError = 'Usuário não encontrado.';
    } elseif (strlen($new_username) < 3) {
        $usernameError = 'O novo nome de usuário deve ter pelo menos 3 caracteres.';
    } elseif (!preg_match('/^[a-zA-Z0-9_\.\-]+$/', $new_username)) {
        $usernameError = 'Nome de usuário inválido. Use apenas letras, números, pontos, hífens e underscores.';
    } elseif (!password_verify($confirm_pw_usr, $row_au['password'])) {
        $usernameError = 'Senha incorreta. Confirme sua senha para alterar o usuário.';
    } else {
        // Verifica se já existe outro admin com esse username
        $res_check = $conn->prepare("SELECT id FROM admins WHERE username = ? AND id != ?");
        $res_check->bind_param("si", $new_username, $admin_id);
        $res_check->execute();
        $exists = $res_check->get_result()->fetch_assoc();
        if ($exists) {
            $usernameError = 'Este nome de usuário já está em uso.';
        } else {
            $stmt_usr = $conn->prepare("UPDATE admins SET username = ? WHERE id = ?");
            $stmt_usr->bind_param("si", $new_username, $admin_id);
            if ($stmt_usr->execute()) {
                $_SESSION['admin_username'] = $new_username;
                $usernameChanged = true;
            } else {
                $usernameError = 'Erro ao atualizar o nome de usuário.';
            }
        }
    }
}

// Upload da Launcher (APK de atualização)
$launcherUpdateMsg = '';
if (isset($_POST['save_launcher_update'])) {
    $version_code = (int) ($_POST['update_version_code'] ?? 0);
    $version_name = trim($_POST['update_version_name'] ?? '');
    $apk_url = $_POST['update_apk_url_direct'] ?? '';

    // Se as versões automáticas não vieram (ou seja, usou URL Direta), pegamos os inputs manuais
    if ($version_code === 0) {
        $version_code = (int) ($_POST['update_version_code_manual'] ?? 1);
    }
    if (empty($version_name)) {
        $version_name = trim($_POST['update_version_name_manual'] ?? '1.0.0');
    }

    // Upload de APK
    if (isset($_FILES['launcher_apk_file']) && $_FILES['launcher_apk_file']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = __DIR__ . '/uploads';
        if (!file_exists($upload_dir))
            mkdir($upload_dir, 0777, true);

        $ext = strtolower(pathinfo($_FILES['launcher_apk_file']['name'], PATHINFO_EXTENSION));
        if ($ext === 'apk') {
            $new_name = "launcher_update_" . time() . "_" . bin2hex(random_bytes(4)) . ".apk";
            if (move_uploaded_file($_FILES['launcher_apk_file']['tmp_name'], "$upload_dir/$new_name")) {
                $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://";
                $apk_url = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/uploads/$new_name";
            } else {
                $launcherUpdateMsg = 'error:Erro ao mover o arquivo APK de atualização.';
            }
        } else {
            $launcherUpdateMsg = 'error:Apenas arquivos com extensão .apk são permitidos.';
        }
    }

    if (empty($launcherUpdateMsg)) {
        // Garante as colunas no banco antes de salvar
        $conn->query("ALTER TABLE config ADD COLUMN update_version_code INTEGER DEFAULT 1");
        $conn->query("ALTER TABLE config ADD COLUMN update_version_name TEXT DEFAULT '1.0.0'");
        $conn->query("ALTER TABLE config ADD COLUMN update_apk_url TEXT DEFAULT ''");

        // Atualiza todas as configurações de todos os temas para que todas as TVs recebam a atualização
        $stmt = $conn->prepare("UPDATE config SET update_version_code = ?, update_version_name = ?, update_apk_url = ?");
        $stmt->bind_param("iss", $version_code, $version_name, $apk_url);
        if ($stmt->execute()) {
            $launcherUpdateMsg = 'success:Atualização da Launcher lançada com sucesso!';
            // Recarrega config ativa
            $res = $conn->query("SELECT * FROM config WHERE theme_id = 1");
            $config = $res->fetch_assoc();
        } else {
            $launcherUpdateMsg = 'error:Erro ao salvar atualização no banco de dados.';
        }
    }
}

// Upload da Logo (sempre substitui assets/upload/logo.png)
$logoUploadMsg = '';
if (isset($_FILES['logo_upload']) && $_FILES['logo_upload']['error'] === UPLOAD_ERR_OK) {
    $allowed = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $_FILES['logo_upload']['tmp_name']);
    finfo_close($finfo);
    if (!in_array($mime, $allowed)) {
        $logoUploadMsg = 'error:Formato inválido. Use PNG, JPG, GIF, WEBP ou SVG.';
    } elseif ($_FILES['logo_upload']['size'] > 2 * 1024 * 1024) {
        $logoUploadMsg = 'error:Arquivo muito grande. Máximo 2MB.';
    } else {
        $dest = __DIR__ . '/assets/upload/logo.png';
        // Converter para PNG independentemente do formato enviado
        if (in_array($mime, ['image/jpeg', 'image/gif', 'image/webp'])) {
            $img = imagecreatefromstring(file_get_contents($_FILES['logo_upload']['tmp_name']));
            if ($img) {
                imagepng($img, $dest);
                imagedestroy($img);
                $logoUploadMsg = 'success:Logo atualizada com sucesso!';
            } else {
                $logoUploadMsg = 'error:Não foi possível processar a imagem.';
            }
        } elseif ($mime === 'image/svg+xml') {
            // SVG: salva direto (renomeia extensão internamente, mas mantém nome logo.png)
            if (move_uploaded_file($_FILES['logo_upload']['tmp_name'], $dest)) {
                $logoUploadMsg = 'success:Logo atualizada com sucesso!';
            } else {
                $logoUploadMsg = 'error:Erro ao mover o arquivo. Verifique permissões.';
            }
        } else {
            // PNG direto
            if (move_uploaded_file($_FILES['logo_upload']['tmp_name'], $dest)) {
                $logoUploadMsg = 'success:Logo atualizada com sucesso!';
            } else {
                $logoUploadMsg = 'error:Erro ao mover o arquivo. Verifique permissões.';
            }
        }
    }
}

if (isset($_POST['save_configuracoes'])) {
    $tech_password = $_POST['tech_password'] ?? '';
    $mp_token = $_POST['mercado_pago_token'] ?? '';
    $support_whatsapp = preg_replace('/\D/', '', $_POST['support_whatsapp'] ?? '');

    $panel_title = trim($_POST['panel_title'] ?? 'Painel Admin');
    if (empty($panel_title)) $panel_title = 'Painel Admin';
    $panel_logo_size = (int)($_POST['panel_logo_size'] ?? 42);
    if ($panel_logo_size < 15) $panel_logo_size = 15;
    if ($panel_logo_size > 120) $panel_logo_size = 120;

    // Garante que as colunas existem antes de salvar
    $conn->query("ALTER TABLE config ADD COLUMN tech_password TEXT DEFAULT '8899'");
    $conn->query("ALTER TABLE config ADD COLUMN mercado_pago_token TEXT DEFAULT ''");
    $conn->query("ALTER TABLE config ADD COLUMN update_version_code INTEGER DEFAULT 1");
    $conn->query("ALTER TABLE config ADD COLUMN update_version_name TEXT DEFAULT '1.0.0'");
    $conn->query("ALTER TABLE config ADD COLUMN update_apk_url TEXT DEFAULT ''");
    $conn->query("ALTER TABLE config ADD COLUMN support_whatsapp TEXT DEFAULT ''");
    $conn->query("ALTER TABLE config ADD COLUMN panel_title VARCHAR(100) DEFAULT 'Painel Admin'");
    $conn->query("ALTER TABLE config ADD COLUMN panel_logo_size INTEGER DEFAULT 42");

    $stmt = $conn->prepare("UPDATE config SET tech_password = ?, mercado_pago_token = ?, support_whatsapp = ?, panel_title = ?, panel_logo_size = ? WHERE theme_id = 1");
    $stmt->bind_param("ssssi", $tech_password, $mp_token, $support_whatsapp, $panel_title, $panel_logo_size);

    if ($stmt->execute()) {
        $configSaved = true;
        // Recarregar config
        $res = $conn->query("SELECT * FROM config WHERE theme_id = 1");
        $config = $res->fetch_assoc();
    }
}

// Garante que as colunas existem para evitar erros no SELECT
$conn->query("ALTER TABLE config ADD COLUMN tech_password TEXT DEFAULT '8899'");
$conn->query("ALTER TABLE config ADD COLUMN mercado_pago_token TEXT DEFAULT ''");
$conn->query("ALTER TABLE config ADD COLUMN update_version_code INTEGER DEFAULT 1");
$conn->query("ALTER TABLE config ADD COLUMN update_version_name TEXT DEFAULT '1.0.0'");
$conn->query("ALTER TABLE config ADD COLUMN update_apk_url TEXT DEFAULT ''");
$conn->query("ALTER TABLE config ADD COLUMN support_whatsapp TEXT DEFAULT ''");
$conn->query("ALTER TABLE config ADD COLUMN panel_title VARCHAR(100) DEFAULT 'Painel Admin'");
$conn->query("ALTER TABLE config ADD COLUMN panel_logo_size INTEGER DEFAULT 42");

$res = $conn->query("SELECT * FROM config WHERE theme_id = 1");
$config = $res->fetch_assoc();
if (!$config) {
    $conn->query("INSERT IGNORE INTO config (theme_id) VALUES (1)");
    $res = $conn->query("SELECT * FROM config WHERE theme_id = 1");
    $config = $res->fetch_assoc() ?? ['theme_id' => 1];
}

// --- Lógica de Limpeza de Arquivos Órfãos ---
$upload_dir = __DIR__ . '/uploads';
$orphan_files = [];
$total_orphan_size = 0;
$orphan_count = 0;

function formatBytes($bytes, $precision = 2)
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= @pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}

if (file_exists($upload_dir) && is_dir($upload_dir)) {
    $dir_files = array_diff(scandir($upload_dir), ['.', '..']);
    $used_files = [];

    // Config
    $q_config = $conn->query("SELECT app_logo, app_background, update_apk_url FROM config");
    if ($q_config) {
        while ($r = $q_config->fetch_assoc()) {
            if (!empty($r['app_logo']))
                $used_files[basename($r['app_logo'])] = true;
            if (!empty($r['app_background']))
                $used_files[basename($r['app_background'])] = true;
            if (!empty($r['update_apk_url']))
                $used_files[basename($r['update_apk_url'])] = true;
        }
    }

    // Propaganda
    $q_prop = $conn->query("SELECT image_url FROM propaganda");
    if ($q_prop) {
        while ($r = $q_prop->fetch_assoc()) {
            if (!empty($r['image_url']))
                $used_files[basename($r['image_url'])] = true;
        }
    }

    // Vertical Buttons
    $q_buttons = $conn->query("SELECT icon_url FROM vertical_buttons");
    if ($q_buttons) {
        while ($r = $q_buttons->fetch_assoc()) {
            if (!empty($r['icon_url']))
                $used_files[basename($r['icon_url'])] = true;
        }
    }

    // App Store
    $q_store = $conn->query("SELECT icon_url, apk_url FROM app_store");
    if ($q_store) {
        while ($r = $q_store->fetch_assoc()) {
            if (!empty($r['icon_url']))
                $used_files[basename($r['icon_url'])] = true;
            if (!empty($r['apk_url']))
                $used_files[basename($r['apk_url'])] = true;
        }
    }

    // Launcher Apps (Grid)
    $q_launcher = $conn->query("SELECT icon_url, apk_url FROM launcher_apps");
    if ($q_launcher) {
        while ($r = $q_launcher->fetch_assoc()) {
            if (!empty($r['icon_url']))
                $used_files[basename($r['icon_url'])] = true;
            if (!empty($r['apk_url']))
                $used_files[basename($r['apk_url'])] = true;
        }
    }

    foreach ($dir_files as $file) {
        if (!isset($used_files[$file])) {
            $file_path = $upload_dir . '/' . $file;
            if (is_file($file_path)) {
                $size = filesize($file_path);
                $orphan_files[] = [
                    'name' => $file,
                    'path' => $file_path,
                    'size' => $size
                ];
                $total_orphan_size += $size;
                $orphan_count++;
            }
        }
    }
}

// Handler AJAX para deletar os órfãos
if (isset($_POST['action']) && $_POST['action'] === 'clear_orphans') {
    ob_start();
    $deleted_count = 0;
    $freed_bytes = 0;
    foreach ($orphan_files as $o) {
        if (file_exists($o['path'])) {
            if (@unlink($o['path'])) {
                $deleted_count++;
                $freed_bytes += $o['size'];
            }
        }
    }
    ob_end_clean();
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'deleted_count' => $deleted_count,
        'freed_mb' => round($freed_bytes / (1024 * 1024), 2)
    ]);
    exit;
}

include 'includes/head.php';
include 'includes/sidebar.php';
include 'includes/topbar.php';
include 'includes/layout-open.php';
?>

<div class="row align-items-center mb-4">
    <div class="col">
        <h2 class="mb-1"><i class="bi bi-gear-fill me-2 text-primary"></i>Configurações do Painel</h2>
        <p class="text-white-50 small mb-0">Gerencie parâmetros e senhas de acesso do sistema</p>
    </div>
</div>

<?php if ($configSaved): ?>
    <div
        class="alert alert-success border-0 bg-success bg-opacity-10 text-success rounded-4 d-flex align-items-center mb-4 p-3 animate__animated animate__fadeIn">
        <i class="bi bi-check-circle-fill me-3 fs-4"></i>
        <div>
            <strong class="d-block">Sucesso!</strong>
            As configurações de segurança e do Mercado Pago foram atualizadas com sucesso.
        </div>
    </div>
<?php endif; ?>

<?php if ($passwordChanged): ?>
    <div
        class="alert alert-success border-0 bg-success bg-opacity-10 text-success rounded-4 d-flex align-items-center mb-4 p-3 animate__animated animate__fadeIn">
        <i class="bi bi-shield-check me-3 fs-4"></i>
        <div>
            <strong class="d-block">Senha alterada!</strong>
            Sua senha de acesso ao painel foi atualizada com sucesso.
        </div>
    </div>
<?php endif; ?>

<?php if ($passwordError): ?>
    <div
        class="alert alert-danger border-0 bg-danger bg-opacity-10 text-danger rounded-4 d-flex align-items-center mb-4 p-3 animate__animated animate__fadeIn">
        <i class="bi bi-x-circle-fill me-3 fs-4"></i>
        <div><?php echo htmlspecialchars($passwordError); ?></div>
    </div>
<?php endif; ?>

<?php if ($usernameChanged): ?>
    <div
        class="alert alert-success border-0 bg-success bg-opacity-10 text-success rounded-4 d-flex align-items-center mb-4 p-3 animate__animated animate__fadeIn">
        <i class="bi bi-person-check me-3 fs-4"></i>
        <div>
            <strong class="d-block">Usuário alterado!</strong>
            Seu nome de usuário foi atualizado para
            <strong><?php echo htmlspecialchars($_SESSION['admin_username']); ?></strong>.
        </div>
    </div>
<?php endif; ?>

<?php if ($usernameError): ?>
    <div
        class="alert alert-danger border-0 bg-danger bg-opacity-10 text-danger rounded-4 d-flex align-items-center mb-4 p-3 animate__animated animate__fadeIn">
        <i class="bi bi-x-circle-fill me-3 fs-4"></i>
        <div><?php echo htmlspecialchars($usernameError); ?></div>
    </div>
<?php endif; ?>

<style>
    /* Estilização Premium para as Abas de Configurações */
    .nav-pills .nav-link {
        transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
        background: rgba(255, 255, 255, 0.02);
        border: 1px solid rgba(255, 255, 255, 0.04);
        color: rgba(255, 255, 255, 0.6) !important;
        margin-right: 8px;
        border-radius: 12px !important;
    }

    .nav-pills .nav-link:hover {
        background: rgba(255, 255, 255, 0.06);
        color: #fff !important;
        border-color: rgba(255, 255, 255, 0.08);
    }

    .nav-pills .nav-link.active {
        background: rgba(13, 202, 240, 0.12) !important;
        border-color: rgba(13, 202, 240, 0.3) !important;
        color: #0dcaf0 !important;
        box-shadow: 0 4px 20px rgba(13, 202, 240, 0.08);
    }
</style>

<div class="row g-4">
    <div class="col-xl-8">

        <!-- Seleção de Abas Bootstrap 5 -->
        <ul class="nav nav-pills nav-fill mb-4 p-1 rounded-4 bg-dark bg-opacity-25" id="configTabs" role="tablist"
            style="border: 1px solid rgba(255,255,255,0.03);">
            <li class="nav-item" role="presentation">
                <button class="nav-link active fw-bold py-3" id="geral-tab" data-bs-toggle="tab"
                    data-bs-target="#geral-pane" type="button" role="tab" aria-controls="geral-pane"
                    aria-selected="true">
                    <i class="bi bi-sliders me-2 text-info"></i>Geral & Suporte
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link fw-bold py-3" id="update-tab" data-bs-toggle="tab" data-bs-target="#update-pane"
                    type="button" role="tab" aria-controls="update-pane" aria-selected="false">
                    <i class="bi bi-arrow-up-circle-fill me-2 text-info"></i>Atualização da Launcher
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link fw-bold py-3" id="perfil-tab" data-bs-toggle="tab" data-bs-target="#perfil-pane"
                    type="button" role="tab" aria-controls="perfil-pane" aria-selected="false">
                    <i class="bi bi-person-fill-lock me-2 text-warning"></i>Acesso & Perfil
                </button>
            </li>
        </ul>

        <div class="tab-content" id="configTabsContent">

            <!-- ABA 1: GERAL & SUPORTE -->
            <div class="tab-pane fade show active" id="geral-pane" role="tabpanel" aria-labelledby="geral-tab"
                tabindex="0">
                <form method="POST" id="configuracoesForm">
                    <input type="hidden" name="save_configuracoes" value="1">

                    <div class="app-card border border-primary border-opacity-10 mb-4">
                        <h5 class="app-card__title mb-4"><i class="bi bi-window-sidebar me-2 text-primary"></i>Identificação do Painel</h5>
                        <div class="row g-3 mb-4">
                            <div class="col-md-7">
                                <label class="form-label text-white-50">Nome do Painel (Título das Páginas)</label>
                                <div class="input-group">
                                    <span class="input-group-text border-opacity-10 text-white-50" style="background: rgba(8, 15, 37, 0.4);"><i class="bi bi-fonts"></i></span>
                                    <input type="text" name="panel_title" value="<?php echo htmlspecialchars($config['panel_title'] ?? 'Painel Admin'); ?>" class="form-control rounded-end-3" placeholder="Ex: Meu Painel Admin" required>
                                </div>
                                <small class="text-white-50 mt-1 d-block"><i class="bi bi-info-circle me-1"></i>Nome personalizado exibido nas abas, tela de login e cabeçalho do painel.</small>
                            </div>
                            <div class="col-md-5">
                                <label class="form-label text-white-50">Tamanho da Logo no Sidebar (px)</label>
                                <div class="input-group">
                                    <span class="input-group-text border-opacity-10 text-white-50" style="background: rgba(8, 15, 37, 0.4);"><i class="bi bi-aspect-ratio"></i></span>
                                    <input type="number" name="panel_logo_size" value="<?php echo (int)($config['panel_logo_size'] ?? 42); ?>" class="form-control rounded-end-3" min="15" max="120" placeholder="Ex: 42">
                                </div>
                                <small class="text-white-50 mt-1 d-block"><i class="bi bi-info-circle me-1"></i>Altura da logo na barra lateral (Padrão: 42px).</small>
                            </div>
                        </div>

                        <hr class="border-secondary border-opacity-20 my-4">

                        <h5 class="app-card__title mb-4"><i
                                class="bi bi-shield-lock-fill me-2 text-primary"></i>Controle de Acesso Técnico</h5>
                        <p class="text-white-50 small mb-4">
                            Esta senha protege a opção <strong>"CONSOLE DE ENGENHARIA"</strong> dentro da aba de
                            configurações específicas do aplicativo no dispositivo.
                            Ao ser digitada corretamente, ela concede acesso às configurações nativas completas do
                            sistema operacional do aparelho.
                        </p>

                        <div class="mb-4">
                            <label class="form-label text-white-50">Senha do Console de Engenharia (PIN)</label>
                            <div class="input-group">
                                <span class="input-group-text border-opacity-10 text-white-50"
                                    style="background: rgba(8, 15, 37, 0.4);"><i class="bi bi-key-fill"></i></span>
                                <input type="text" name="tech_password" id="techPasswordInput"
                                    value="<?php echo htmlspecialchars($config['tech_password'] ?? '8899'); ?>"
                                    class="form-control rounded-end-3" placeholder="Ex: 8899" required minlength="4">
                            </div>
                            <small class="text-white-50 mt-2 d-block"><i class="bi bi-info-circle me-1"></i>Recomendado
                                utilizar um PIN numérico fácil de digitar no controle remoto da TV (mínimo de 4
                                caracteres).</small>
                        </div>

                        <hr class="border-secondary border-opacity-20 my-4">

                        <!-- Card Mercado Pago -->
                        <h5 class="app-card__title mb-4"><i class="bi bi-wallet2 me-2 text-primary"></i>Pagamento
                            Automático (Mercado Pago)</h5>
                        <p class="text-white-50 small mb-4">
                            Insira o seu <strong>Access Token do Mercado Pago</strong> (Produção ou Credenciais de
                            Teste) para automatizar a liberação de acessos quando o cliente pagar via PIX pela TV.
                        </p>

                        <div class="mb-4">
                            <label class="form-label text-white-50">Mercado Pago Access Token</label>
                            <div class="input-group">
                                <span class="input-group-text border-opacity-10 text-white-50"
                                    style="background: rgba(8, 15, 37, 0.4);"><i class="bi bi-shield-check"></i></span>
                                <input type="password" name="mercado_pago_token" id="mpTokenInput"
                                    value="<?php echo htmlspecialchars($config['mercado_pago_token'] ?? ''); ?>"
                                    class="form-control rounded-end-3"
                                    placeholder="Ex: APP_USR-xxxxxxxxxxxx-xxxxxx-xxxxxxxxxxxxxxxx-xxxxxxxx">
                                <button type="button" class="btn btn-outline-light border-opacity-10 px-3"
                                    onclick="toggleTokenVisibility()"><i class="bi bi-eye" id="toggleIcon"></i></button>
                            </div>
                            <small class="text-white-50 mt-2 d-block"><i class="bi bi-info-circle me-1"></i>Mantenha
                                este token seguro. Ele é utilizado para gerar os QR Codes de PIX no aplicativo.</small>
                        </div>

                        <hr class="border-secondary border-opacity-20 my-4">

                        <!-- Suporte WhatsApp -->
                        <h5 class="app-card__title mb-4"><i class="bi bi-whatsapp me-2 text-success"></i>Suporte ao
                            Cliente (WhatsApp)</h5>
                        <p class="text-white-50 small mb-4">
                            Insira o número do seu WhatsApp de atendimento comercial. Ele será exibido na tela de
                            bloqueio do aplicativo para que o cliente possa entrar em contato com o suporte e efetuar
                            pagamentos manuais.
                        </p>

                        <div class="mb-4">
                            <label class="form-label text-white-50">Número do WhatsApp (com código do país e
                                DDD)</label>
                            <div class="input-group">
                                <span class="input-group-text border-opacity-10 text-white-50"
                                    style="background: rgba(8, 15, 37, 0.4);"><i
                                        class="bi bi-whatsapp text-success"></i></span>
                                <input type="text" name="support_whatsapp"
                                    value="<?php echo htmlspecialchars($config['support_whatsapp'] ?? ''); ?>"
                                    class="form-control rounded-end-3" placeholder="Ex: 5511999999999">
                            </div>
                            <small class="text-white-50 mt-2 d-block"><i class="bi bi-info-circle me-1"></i>Digite
                                apenas números (Ex: 55 para Brasil + DDD + número). Sem espaços ou hífens.</small>
                        </div>

                        <div class="mt-4 pt-2">
                            <button type="submit" class="btn btn-app-primary py-3 px-5 rounded-4 shadow-lg w-100"
                                id="saveConfigBtn">
                                <i class="bi bi-cloud-check-fill me-2"></i>SALVAR CONFIGURAÇÕES GERAIS
                            </button>
                        </div>
                    </div>
                </form>
            </div>

            <!-- ABA 2: ATUALIZAÇÃO DA LAUNCHER -->
            <div class="tab-pane fade" id="update-pane" role="tabpanel" aria-labelledby="update-tab" tabindex="0">
                <form method="POST" enctype="multipart/form-data" id="launcherUpdateForm">
                    <input type="hidden" name="save_launcher_update" value="1">
                    <div class="app-card border border-info border-opacity-10 mb-4">
                        <div
                            class="d-flex align-items-center justify-content-between mb-4 border-bottom border-secondary border-opacity-20 pb-3">
                            <h5 class="app-card__title mb-0"><i
                                    class="bi bi-arrow-up-circle-fill me-2 text-info"></i>Lançar Atualização da Launcher
                            </h5>
                            <span class="badge bg-info bg-opacity-10 text-info px-3 py-2 rounded-pill small">
                                Ativo: v<?php echo htmlspecialchars($config['update_version_name'] ?? '1.0.0'); ?>
                                (Code: <?php echo htmlspecialchars($config['update_version_code'] ?? '1'); ?>)
                            </span>
                        </div>

                        <p class="text-white-50 small mb-4">Envie o novo arquivo APK da Launcher. O sistema irá ler o
                            código da versão e o nome da versão automaticamente.</p>

                        <?php if ($config['update_apk_url']): ?>
                            <div class="p-3 rounded-3 mb-4 d-flex align-items-center justify-content-between"
                                style="background: rgba(13, 202, 240, 0.04); border: 1px solid rgba(13, 202, 240, 0.15);">
                                <div class="text-truncate me-2">
                                    <span class="d-block text-white-50 small" style="font-size: 0.75rem;">APK Ativo
                                        Atualmente:</span>
                                    <code class="text-info small text-truncate d-block"
                                        style="max-width: 420px;"><?php echo htmlspecialchars($config['update_apk_url']); ?></code>
                                </div>
                                <a href="<?php echo htmlspecialchars($config['update_apk_url']); ?>"
                                    class="btn btn-sm btn-outline-info rounded-pill px-3" download>
                                    <i class="bi bi-download me-1"></i> Baixar APK
                                </a>
                            </div>
                        <?php endif; ?>

                        <?php if ($launcherUpdateMsg): ?>
                            <?php
                            $upMsgParts = explode(':', $launcherUpdateMsg, 2);
                            $upMsgType = $upMsgParts[0];
                            $upMsgText = $upMsgParts[1] ?? '';
                            $upAlertClass = $upMsgType === 'success' ? 'alert-success text-success' : 'alert-danger text-danger';
                            $upAlertIcon = $upMsgType === 'success' ? 'bi-check-circle-fill' : 'bi-x-circle-fill';
                            ?>
                            <div
                                class="alert <?php echo $upAlertClass; ?> bg-opacity-10 border-0 rounded-4 p-3 d-flex align-items-center mb-4">
                                <i class="bi <?php echo $upAlertIcon; ?> me-2 fs-4"></i>
                                <div><?php echo htmlspecialchars($upMsgText); ?></div>
                            </div>
                        <?php endif; ?>

                        <!-- Dropzone de APK -->
                        <div class="mb-4">
                            <label class="form-label text-white-50 fw-bold small mb-3">Selecione ou Arraste o
                                APK</label>
                            <div id="apkDropzone"
                                class="p-5 rounded-4 d-flex flex-column align-items-center justify-content-center cursor-pointer"
                                style="border: 2px dashed rgba(13, 202, 240, 0.3); background: rgba(13, 202, 240, 0.02); transition: all 0.3s ease;">
                                <i class="bi bi-file-earmark-arrow-up text-info fs-1 mb-3"></i>
                                <h6 class="text-white mb-2" id="apkDropzoneTitle">Arraste o APK da Launcher aqui</h6>
                                <p class="text-white-50 small mb-0" id="apkDropzoneDesc">ou clique para selecionar o
                                    arquivo</p>
                                <input type="file" name="launcher_apk_file" id="launcherApkFileInput" accept=".apk"
                                    style="display: none;">
                            </div>
                        </div>

                        <!-- Loader de Análise -->
                        <div id="apkAnalysisLoader" class="text-center py-4" style="display: none;">
                            <div class="spinner-border text-info mb-3" role="status"></div>
                            <p class="text-white-50 small">Analisando o APK da Launcher... Extraindo versão...</p>
                        </div>

                        <!-- Detalhes extraídos / Form de Confirmação -->
                        <div id="apkPublishDetails" style="display: none;">
                            <div class="p-4 rounded-4 mb-4"
                                style="background: rgba(255, 255, 255, 0.02); border: 1px solid rgba(255, 255, 255, 0.05);">
                                <h6 class="text-info fw-bold mb-3"><i
                                        class="bi bi-info-circle-fill me-2"></i>Informações do APK Selecionado</h6>

                                <div class="row g-3 mb-3">
                                    <div class="col-md-6">
                                        <label class="form-label text-white-50 small">Código da Versão (Version
                                            Code)</label>
                                        <input type="number" name="update_version_code" id="txtVersionCode"
                                            class="form-control" required readonly>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label text-white-50 small">Nome da Versão (Version
                                            Name)</label>
                                        <input type="text" name="update_version_name" id="txtVersionName"
                                            class="form-control" required readonly>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label text-white-50 small">Nome do Pacote (Package Name)</label>
                                    <input type="text" id="txtPackage" class="form-control text-white-50" readonly
                                        style="background: rgba(0,0,0,0.2);">
                                </div>
                            </div>
                        </div>

                        <div class="d-flex align-items-center justify-content-center my-4" id="directUrlDivider">
                            <div style="height: 1px; background: rgba(255,255,255,0.1); flex-grow: 1;"></div>
                            <span class="px-3 text-white-50 small fw-bold"
                                style="font-size: 0.8rem; letter-spacing: 1px;">OU PREENCHER COM URL DIRETA</span>
                            <div style="height: 1px; background: rgba(255,255,255,0.1); flex-grow: 1;"></div>
                        </div>

                        <div class="mb-4" id="directUrlFormGroup">
                            <div class="row g-3 mb-3">
                                <div class="col-md-4">
                                    <label class="form-label text-white-50 small">Código da Versão (Manual)</label>
                                    <input type="number" name="update_version_code_manual" id="valVersionCodeManual"
                                        value="<?php echo htmlspecialchars($config['update_version_code'] ?? '1'); ?>"
                                        class="form-control" min="1">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label text-white-50 small">Nome da Versão (Manual)</label>
                                    <input type="text" name="update_version_name_manual" id="valVersionNameManual"
                                        value="<?php echo htmlspecialchars($config['update_version_name'] ?? '1.0.0'); ?>"
                                        class="form-control" placeholder="Ex: 1.0.1">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label text-white-50 small">URL Direta Externa do APK</label>
                                    <input type="url" name="update_apk_url_direct" id="updateApkUrlDirect"
                                        value="<?php echo htmlspecialchars($config['update_apk_url'] ?? ''); ?>"
                                        class="form-control" placeholder="https://exemplo.com/onelauncher.apk">
                                </div>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-info py-3 px-5 rounded-4 shadow-lg w-100 fw-bold text-dark"
                            id="btnPublishUpdate">
                            <i class="bi bi-cloud-arrow-up-fill me-2"></i>PUBLICAR NOVA VERSÃO
                        </button>
                    </div>
                </form>
            </div>

            <!-- ABA 3: ACESSO & PERFIL -->
            <div class="tab-pane fade" id="perfil-pane" role="tabpanel" aria-labelledby="perfil-tab" tabindex="0">
                <!-- Card Alterar Senha do Painel -->
                <form method="POST" id="changePasswordForm">
                    <input type="hidden" name="change_password" value="1">
                    <div class="app-card border border-warning border-opacity-10 mb-4">
                        <h5 class="app-card__title mb-4"><i class="bi bi-lock-fill me-2 text-warning"></i>Alterar Senha do Painel</h5>
                        <p class="text-white-50 small mb-4">Altere a sua senha de acesso ao painel administrativo.</p>

                        <div class="mb-3">
                            <label class="form-label text-white-50">Senha Atual</label>
                            <div class="input-group">
                                <span class="input-group-text border-opacity-10 text-white-50"
                                    style="background: rgba(8, 15, 37, 0.4);"><i class="bi bi-lock"></i></span>
                                <input type="password" name="current_password" class="form-control rounded-end-3"
                                    placeholder="Digite sua senha atual" required>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label text-white-50">Nova Senha</label>
                            <div class="input-group">
                                <span class="input-group-text border-opacity-10 text-white-50"
                                    style="background: rgba(8, 15, 37, 0.4);"><i class="bi bi-key"></i></span>
                                <input type="password" name="new_password" id="newPasswordInput"
                                    class="form-control rounded-end-3" placeholder="Mínimo 6 caracteres" required
                                    minlength="6">
                                <button type="button" class="btn btn-outline-light border-opacity-10 px-3"
                                    onclick="toggleNewPassword()"><i class="bi bi-eye" id="toggleNewIcon"></i></button>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label text-white-50">Confirmar Nova Senha</label>
                            <div class="input-group">
                                <span class="input-group-text border-opacity-10 text-white-50"
                                    style="background: rgba(8, 15, 37, 0.4);"><i class="bi bi-key-fill"></i></span>
                                <input type="password" name="confirm_password" id="confirmPasswordInput"
                                    class="form-control rounded-end-3" placeholder="Repita a nova senha" required
                                    minlength="6">
                            </div>
                            <div id="passwordMatchMsg" class="small mt-2" style="display: none;"></div>
                        </div>

                        <button type="submit"
                            class="btn btn-warning py-3 px-5 rounded-4 shadow-lg w-100 fw-bold text-dark">
                            <i class="bi bi-shield-lock me-2"></i>ALTERAR SENHA
                        </button>
                    </div>
                </form>

                <!-- Card Alterar Nome de Usuário -->
                <form method="POST" id="changeUsernameForm">
                    <input type="hidden" name="change_username" value="1">
                    <div class="app-card border border-info border-opacity-10">
                        <h5 class="app-card__title mb-1"><i class="bi bi-person-gear me-2 text-info"></i>Alterar Nome de
                            Usuário</h5>
                        <p class="text-white-50 small mb-4">Altere o seu nome de usuário de acesso ao painel. Usuário
                            atual: <strong
                                class="text-info"><?php echo htmlspecialchars($_SESSION['admin_username'] ?? 'admin'); ?></strong>
                        </p>

                        <div class="mb-3">
                            <label class="form-label text-white-50">Novo Nome de Usuário</label>
                            <div class="input-group">
                                <span class="input-group-text border-opacity-10 text-white-50"
                                    style="background: rgba(8, 15, 37, 0.4);"><i class="bi bi-person"></i></span>
                                <input type="text" name="new_username" id="newUsernameInput"
                                    class="form-control rounded-end-3" placeholder="Ex: admin2" required minlength="3"
                                    pattern="[a-zA-Z0-9_.\-]+">
                            </div>
                            <small class="text-white-50 mt-1 d-block"><i class="bi bi-info-circle me-1"></i>Apenas
                                letras, números, pontos, hífens e underscores.</small>
                        </div>

                        <div class="mb-4">
                            <label class="form-label text-white-50">Confirme sua Senha</label>
                            <div class="input-group">
                                <span class="input-group-text border-opacity-10 text-white-50"
                                    style="background: rgba(8, 15, 37, 0.4);"><i class="bi bi-lock"></i></span>
                                <input type="password" name="confirm_password_username"
                                    class="form-control rounded-end-3" placeholder="Digite sua senha para confirmar"
                                    required>
                            </div>
                            <small class="text-white-50 mt-1 d-block"><i class="bi bi-info-circle me-1"></i>Por
                                segurança, confirme sua senha antes de alterar o usuário.</small>
                        </div>

                        <button type="submit"
                            class="btn btn-info py-3 px-5 rounded-4 shadow-lg w-100 fw-bold text-dark">
                            <i class="bi bi-person-check me-2"></i>ALTERAR USUÁRIO
                        </button>
                    </div>
                </form>
            </div> <!-- Fim perfil-pane -->

        </div> <!-- Fim tab-content -->
    </div> <!-- Fim col-xl-8 -->

    <div class="col-xl-4">
        <!-- Card Upload da Logo -->
        <div class="app-card border border-primary border-opacity-10 mb-4">
            <h5 class="app-card__title mb-1"><i class="bi bi-image-fill me-2 text-primary"></i>Logo do Painel</h5>
            <p class="text-white-50 small mb-3">Substitui a logo exibida na barra lateral. O arquivo sempre será salvo
                como <code>logo.png</code>.</p>

            <?php
            $logoPath = __DIR__ . '/assets/upload/logo.png';
            $logoCacheBust = file_exists($logoPath) ? filemtime($logoPath) : 0;
            ?>
            <div class="mb-3 text-center">
                <img src="assets/upload/logo.png?v=<?php echo $logoCacheBust; ?>" alt="Logo Atual" id="logoPreviewImg"
                    style="max-height: 60px; max-width: 100%; object-fit: contain; display: block; margin: 0 auto 12px;"
                    onerror="this.style.opacity='0.3';">
            </div>

            <?php if ($logoUploadMsg): ?>
                <?php
                $logoMsgParts = explode(':', $logoUploadMsg, 2);
                $logoMsgType = $logoMsgParts[0];
                $logoMsgText = $logoMsgParts[1] ?? '';
                $logoAlertClass = $logoMsgType === 'success' ? 'alert-success text-success' : 'alert-danger text-danger';
                $logoAlertIcon = $logoMsgType === 'success' ? 'bi-check-circle-fill' : 'bi-x-circle-fill';
                ?>
                <div class="alert <?php echo $logoAlertClass; ?> bg-opacity-10 border-0 rounded-3 py-2 px-3 small mb-3">
                    <i class="bi <?php echo $logoAlertIcon; ?> me-1"></i><?php echo htmlspecialchars($logoMsgText); ?>
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data" id="logoUploadForm">
                <div class="mb-3">
                    <label class="form-label text-white-50 small">Selecionar novo arquivo</label>
                    <input type="file" name="logo_upload" id="logoFileInput"
                        accept="image/png,image/jpeg,image/gif,image/webp,image/svg+xml"
                        class="form-control form-control-sm"
                        style="background: rgba(8,15,37,0.4); border-color: rgba(255,255,255,0.1); color: #fff;">
                    <small class="text-white-50 mt-1 d-block"><i class="bi bi-info-circle me-1"></i>PNG, JPG, GIF, WEBP
                        ou SVG · Máx. 2MB</small>
                </div>
                <button type="submit" class="btn btn-primary rounded-4 w-100 py-2">
                    <i class="bi bi-upload me-2"></i>ENVIAR LOGO
                </button>
            </form>
        </div>

        <!-- Card Limpeza de Armazenamento -->
        <div class="app-card border border-info border-opacity-10 mb-4">
            <h5 class="app-card__title mb-1"><i class="bi bi-trash3-fill me-2 text-info"></i>Limpeza de Armazenamento
            </h5>
            <p class="text-white-50 small mb-3">Remova arquivos de uploads antigos (APKs, ícones, imagens) que foram
                excluídos e não estão mais em uso.</p>

            <div class="d-flex align-items-center justify-content-between p-3 rounded-3 mb-3"
                style="background: rgba(13, 202, 240, 0.05); border: 1px dashed rgba(13, 202, 240, 0.2);">
                <div>
                    <span class="d-block text-white-50 small" style="font-size: 0.75rem;">Espaço Órfão:</span>
                    <strong class="fs-5 text-info"
                        id="freedSpaceText"><?php echo formatBytes($total_orphan_size); ?></strong>
                </div>
                <div class="text-end">
                    <span class="d-block text-white-50 small" style="font-size: 0.75rem;">Arquivos Não Usados:</span>
                    <strong class="fs-5 text-info" id="freedCountText"><?php echo $orphan_count; ?></strong>
                </div>
            </div>

            <?php if ($orphan_count > 0): ?>
                <button type="button" class="btn btn-info text-dark rounded-4 w-100 py-2 fw-bold" id="clearOrphansBtn"
                    onclick="clearUnusedFiles()">
                    <i class="bi bi-stars me-2"></i>LIMPAR ARQUIVOS ÓRFÃOS
                </button>
            <?php else: ?>
                <button type="button" class="btn btn-secondary rounded-4 w-100 py-2" disabled>
                    <i class="bi bi-check-all me-2"></i>TUDO LIMPO!
                </button>
            <?php endif; ?>
        </div>

        <div class="app-card bg-secondary bg-opacity-10 border-0 mb-4">
            <h6 class="text-primary fw-bold mb-2"><i class="bi bi-shield-shaded me-2"></i>Segurança do Dispositivo</h6>
            <p class="small text-white-50 mb-0">
                Mantenha esta senha em sigilo. Ela impede que clientes finais ou usuários indesejados acessem os
                parâmetros internos do Android e modifiquem as configurações de rede, aplicativos ou sistemas nativos.
            </p>
        </div>
        <div class="app-card bg-danger bg-opacity-10 border-0 mb-4">
            <h6 class="text-danger fw-bold mb-2"><i class="bi bi-exclamation-triangle me-2"></i>Cuidado ao Alterar
                Senha</h6>
            <p class="small text-white-50 mb-0">
                Ao alterar a senha do painel, você precisará fazer login novamente com a nova senha. Certifique-se de
                anotá-la em um local seguro antes de confirmar.
            </p>
        </div>


        <?php
        $devName = base64_decode("U3RvcmVBcnQ=");
        $devTitle = base64_decode("RGVzZW52b2x2aWRvIHBvcg==");
        $devSupport = base64_decode("U3Vwb3J0ZSBkbyBEZXNlbnZvbHZpZG9y");
        $waLink = base64_decode("aHR0cHM6Ly93YS5tZS80NDczODM5MTEzMTA=");
        $tgLink = base64_decode("aHR0cHM6Ly90Lm1lL3N0b3JlYXJ0X2RpZ2l0YWw=");
        ?>
        <div class="app-card border border-secondary border-opacity-10 mb-4 text-center py-4">
            <div class="mb-2">
                <i class="bi bi-code-slash text-info fs-3"></i>
            </div>
            <span class="text-white-50 small d-block"><?php echo htmlspecialchars($devTitle); ?></span>
            <strong class="text-white fs-5 d-block mb-3"
                style="letter-spacing: 0.5px;"><?php echo htmlspecialchars($devName); ?></strong>

            <div class="px-2">
                <p class="text-white-50 small mb-4" style="font-size: 0.8rem;">
                    <?php echo htmlspecialchars($devSupport); ?></p>
                <div class="row g-2">
                    <div class="col-6">
                        <a href="<?php echo htmlspecialchars($waLink); ?>" target="_blank"
                            class="btn btn-sm btn-outline-success w-100 rounded-3 py-2 fw-bold"
                            style="font-size: 0.75rem;">
                            <i class="bi bi-whatsapp me-1"></i> WhatsApp
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="<?php echo htmlspecialchars($tgLink); ?>" target="_blank"
                            class="btn btn-sm btn-outline-info w-100 rounded-3 py-2 fw-bold"
                            style="font-size: 0.75rem;">
                            <i class="bi bi-telegram me-1"></i> Telegram
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Preview logo antes de enviar
    document.getElementById('logoFileInput').addEventListener('change', function () {
        const file = this.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = function (e) {
            const img = document.getElementById('logoPreviewImg');
            img.src = e.target.result;
            img.style.opacity = '1';
        };
        reader.readAsDataURL(file);
    });
</script>

<script>
    function toggleTokenVisibility() {
        const input = document.getElementById('mpTokenInput');
        const icon = document.getElementById('toggleIcon');
        if (input.type === 'password') {
            input.type = 'text';
            icon.classList.replace('bi-eye', 'bi-eye-slash');
        } else {
            input.type = 'password';
            icon.classList.replace('bi-eye-slash', 'bi-eye');
        }
    }

    function toggleNewPassword() {
        const input = document.getElementById('newPasswordInput');
        const icon = document.getElementById('toggleNewIcon');
        if (input.type === 'password') {
            input.type = 'text';
            icon.classList.replace('bi-eye', 'bi-eye-slash');
        } else {
            input.type = 'password';
            icon.classList.replace('bi-eye-slash', 'bi-eye');
        }
    }

    // Verificação em tempo real das senhas
    const newPw = document.getElementById('newPasswordInput');
    const confirmPw = document.getElementById('confirmPasswordInput');
    const matchMsg = document.getElementById('passwordMatchMsg');

    function checkPasswordMatch() {
        if (!confirmPw.value) { matchMsg.style.display = 'none'; return; }
        if (newPw.value === confirmPw.value) {
            matchMsg.style.display = 'block';
            matchMsg.innerHTML = '<i class="bi bi-check-circle-fill text-success me-1"></i><span class="text-success">Senhas conferem!</span>';
        } else {
            matchMsg.style.display = 'block';
            matchMsg.innerHTML = '<i class="bi bi-x-circle-fill text-danger me-1"></i><span class="text-danger">As senhas não conferem.</span>';
        }
    }

    newPw.addEventListener('input', checkPasswordMatch);
    confirmPw.addEventListener('input', checkPasswordMatch);

    function clearUnusedFiles() {
        Swal.fire({
            title: 'Limpar arquivos não utilizados?',
            text: "Esta ação apagará permanentemente todos os APKs e imagens antigos que não estão cadastrados no banco de dados.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#0dcaf0',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Sim, limpar tudo',
            cancelButtonText: 'Cancelar',
            background: '#111827',
            color: '#f1f5f9'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Limpando...',
                    html: 'Aguarde enquanto os arquivos inúteis são removidos.',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    },
                    background: '#111827',
                    color: '#f1f5f9'
                });

                const formData = new FormData();
                formData.append('action', 'clear_orphans');

                fetch('configuracoes.php', {
                    method: 'POST',
                    body: formData
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                title: 'Limpeza Concluída!',
                                text: `Foram excluídos ${data.deleted_count} arquivo(s), liberando ${data.freed_mb} MB de espaço.`,
                                icon: 'success',
                                background: '#111827',
                                color: '#f1f5f9',
                                confirmButtonColor: '#0dcaf0'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Erro',
                                text: 'Erro ao limpar arquivos.',
                                icon: 'error',
                                background: '#111827',
                                color: '#f1f5f9'
                            });
                        }
                    })
                    .catch(() => {
                        Swal.fire({
                            title: 'Erro',
                            text: 'Erro de conexão com o servidor.',
                            icon: 'error',
                            background: '#111827',
                            color: '#f1f5f9'
                        });
                    });
            }
        });
    }

    // ========== ANÁLISE DE APK NO UPDATE DA LAUNCHER ==========
    const apkDropzone = document.getElementById('apkDropzone');
    const launcherApkFileInput = document.getElementById('launcherApkFileInput');
    const apkAnalysisLoader = document.getElementById('apkAnalysisLoader');
    const apkPublishDetails = document.getElementById('apkPublishDetails');
    const txtVersionCode = document.getElementById('txtVersionCode');
    const txtVersionName = document.getElementById('txtVersionName');
    const txtPackage = document.getElementById('txtPackage');

    const directUrlDivider = document.getElementById('directUrlDivider');
    const directUrlFormGroup = document.getElementById('directUrlFormGroup');
    const apkDropzoneTitle = document.getElementById('apkDropzoneTitle');
    const apkDropzoneDesc = document.getElementById('apkDropzoneDesc');

    if (apkDropzone) {
        apkDropzone.addEventListener('click', () => launcherApkFileInput.click());

        apkDropzone.addEventListener('dragover', (e) => {
            e.preventDefault();
            apkDropzone.style.borderColor = 'var(--info)';
            apkDropzone.style.background = 'rgba(13, 202, 240, 0.08)';
        });

        apkDropzone.addEventListener('dragleave', () => {
            apkDropzone.style.borderColor = 'rgba(13, 202, 240, 0.3)';
            apkDropzone.style.background = 'rgba(13, 202, 240, 0.02)';
        });

        apkDropzone.addEventListener('drop', (e) => {
            e.preventDefault();
            apkDropzone.style.borderColor = 'rgba(13, 202, 240, 0.3)';
            apkDropzone.style.background = 'rgba(13, 202, 240, 0.02)';
            if (e.dataTransfer.files.length) {
                launcherApkFileInput.files = e.dataTransfer.files;
                handleLauncherApkFile(e.dataTransfer.files[0]);
            }
        });

        launcherApkFileInput.addEventListener('change', () => {
            if (launcherApkFileInput.files.length) {
                handleLauncherApkFile(launcherApkFileInput.files[0]);
            }
        });
    }

    function handleLauncherApkFile(file) {
        if (!file.name.endsWith('.apk')) {
            Swal.fire('Erro', 'Selecione apenas arquivos .apk válidos.', 'error');
            launcherApkFileInput.value = '';
            return;
        }

        apkDropzone.style.display = 'none';
        apkAnalysisLoader.style.display = 'block';
        apkPublishDetails.style.display = 'none';

        const parser = new AppInfoParser(file);
        parser.parse().then(result => {
            apkAnalysisLoader.style.display = 'none';

            txtVersionCode.value = result.versionCode || '';
            txtVersionName.value = result.versionName || '';
            txtPackage.value = result.package || '';

            apkPublishDetails.style.display = 'block';

            if (directUrlDivider) directUrlDivider.style.display = 'none';
            if (directUrlFormGroup) directUrlFormGroup.style.display = 'none';

            Swal.fire({
                title: 'APK Analisado!',
                text: `Versão detectada: ${result.versionName} (Code: ${result.versionCode})`,
                icon: 'success',
                background: '#111827',
                color: '#f1f5f9',
                confirmButtonColor: '#0dcaf0'
            });
        }).catch(err => {
            console.error(err);
            apkAnalysisLoader.style.display = 'none';
            apkDropzone.style.display = 'flex';
            launcherApkFileInput.value = '';
            Swal.fire('Erro', 'Falha ao analisar o arquivo APK. Verifique se o arquivo está corrompido.', 'error');
        });
    }
</script>
<script src="https://cdn.jsdelivr.net/npm/app-info-parser/dist/app-info-parser.min.js"></script>

<?php
include 'includes/layout-close.php';
include 'includes/footer.php';
?>