<?php
//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/eonbry------------------>
//<-------------DEVELOPER: EMANUEL NASCIMENTO----------------->
//<----------------------------------------------------------->

session_start();

if (!isset($_SESSION['eggzie_iboPlayer'])) {
    header('Location: login.php');
    exit();
}

include("./includes/header.php");

// =========== CONFIGURAÇÕES DO UPLOAD ===========
$uploadDir = __DIR__ . "/apkupdate/"; // Diretório CORRIGIDO: apkupdate/
$finalApkName = "ibo.apk"; // NOME FIXO DO ARQUIVO
$maxFileSize = 500 * 1024 * 1024; // 500MB
$allowedExtensions = ['apk'];

// Criar diretório se não existir
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// Função para formatar tamanho do arquivo
function formatFileSize($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}

// ===============================================

// CAMINHO ABSOLUTO CORRETO
$path = __DIR__ . "/./a/ibo.json";

// SE NÃO EXISTIR, CRIA PADRÃO COM FORMATO CORRETO
if (!file_exists($path)) {
    $defaultData = [
        "app_info" => [
            "android_version_code" => "1.0",
            "apk_url" => "",
            "changelog" => "• Correções de bugs\n• Melhorias de performance\n• Novas funcionalidades",
            "mandatory" => false,
            "release_date" => date("Y-m-d")
        ]
    ];
    file_put_contents($path, json_encode($defaultData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

// LÊ O JSON
$data = [];
if (file_exists($path)) {
    $jsonContent = file_get_contents($path);
    if ($jsonContent !== false) {
        $data = json_decode($jsonContent, true);
        if ($data === null) {
            $data = [
                "app_info" => [
                    "android_version_code" => "1.0",
                    "apk_url" => "",
                    "changelog" => "• Correções de bugs\n• Melhorias de performance\n• Novas funcionalidades",
                    "mandatory" => false,
                    "release_date" => date("Y-m-d")
                ]
            ];
            file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }
    }
}

// Garante que todos os campos existam
if (!isset($data["app_info"]) || !is_array($data["app_info"])) {
    $data["app_info"] = [];
}

$defaults = [
    "android_version_code" => "1.0",
    "apk_url" => "",
    "changelog" => "• Correções de bugs\n• Melhorias de performance\n• Novas funcionalidades",
    "mandatory" => false,
    "release_date" => date("Y-m-d")
];

foreach ($defaults as $key => $value) {
    if (!isset($data["app_info"][$key])) {
        $data["app_info"][$key] = $value;
    }
}

$msg = "";
$msg_type = "";

// =========== PROCESSAMENTO DO FORMULÁRIO ===========
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $uploadedFile = null;
    $uploadedUrl = '';
    $fileSize = "25 MB";
    
   
    // =========== PROCESSAR UPLOAD DE ARQUIVO ===========
if (isset($_FILES['apk_file']) && $_FILES['apk_file']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['apk_file'];
    
    // Validar tamanho
    if ($file['size'] > $maxFileSize) {
        $msg = "⚠️ ARQUIVO MUITO GRANDE! Máximo: 500MB";
        $msg_type = "error";
    } else {
        // Validar extensão
        $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (in_array($fileExtension, $allowedExtensions)) {
            // ⭐⭐ NOME FIXO: SEMPRE ibo.apk ⭐⭐
            $targetPath = $uploadDir . $finalApkName;
            
            // ⭐⭐ APAGAR VERSÃO ANTERIOR SE EXISTIR ⭐⭐
            if (file_exists($targetPath)) {
                unlink($targetPath);
            }
            
            // Mover arquivo
            if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                $uploadedFile = $targetPath;
                
                // ⭐⭐ GERAR URL COMPLETA CORRETA DO SERVIDOR ⭐⭐
                $serverBase = getServerBasePath();
                
                // ⭐⭐ URL COMPLETA CORRETA: domínio/apkupdate/ibo.apk ⭐⭐
                $uploadedUrl = $serverBase . '/apkupdate/' . $finalApkName;
                
                // Obter tamanho real do arquivo
                $fileSize = formatFileSize(filesize($targetPath));
                
                $msg .= "✅ APK UPLOADED COM SUCESSO!<br>";
                $msg_type = "success";
            } else {
                $msg = "⚠️ ERRO AO MOVER ARQUIVO";
                $msg_type = "error";
            }
        } else {
            $msg = "⚠️ FORMATO INVÁLIDO! Apenas arquivos .APK são permitidos";
            $msg_type = "error";
        }
    }
}
    
    // =========== PROCESSAR DADOS DO FORMULÁRIO ===========
    $version = trim($_POST["version"] ?? '');
    $url = trim($_POST["url"] ?? '');
    $changelog = trim($_POST["changelog"] ?? '');
    $mandatory = isset($_POST["mandatory"]) ? true : false;
    $release_date = $_POST["release_date"] ?? date("Y-m-d");
    
    // Se fez upload, usar URL do arquivo carregado (com caminho completo)
    if ($uploadedUrl) {
        $url = $uploadedUrl;
    } else {
        // Se é URL externa e não tem http:// ou https://, adiciona
        if (!empty($url) && !preg_match('/^https?:\/\//i', $url)) {
            $url = "http://" . $url;
        }
    }
    
    // VALIDAÇÃO
    $version_pattern = '/^\d+(\.\d+)*$/';
    
    // Validar apenas a versão
    if (!preg_match($version_pattern, $version)) {
        $msg = "⚠️ VERSÃO INVÁLIDA! Use formato numérico (ex: 1.0, 2.1, 3.9)";
        $msg_type = "error";
    } 
    // Validar se tem URL (upload ou externa)
    elseif (empty($url)) {
        $msg = "⚠️ URL REQUERIDA! Faça upload de um APK ou insira uma URL externa";
        $msg_type = "error";
    }
    // Se tem URL externa, validar formato
    elseif (!$uploadedUrl && !filter_var($url, FILTER_VALIDATE_URL)) {
        $msg = "⚠️ URL EXTERNA INVÁLIDA! Use formato: https://exemplo.com/app.apk";
        $msg_type = "error";
    }
    // Tudo válido, salvar dados
    else {
        // Se não fez upload mas tem URL externa, usar tamanho padrão
        if (!$uploadedFile) {
            $fileSize = getFileSizeFromVersion($version);
        }
        
        // ⭐⭐ ESTRUTURA ATUALIZADA COM URL COMPLETA ⭐⭐
        $data["app_info"] = [
            "android_version_code" => $version,
            "apk_url" => $url, // ⭐⭐ URL COMPLETA: domínio/apkupdate/ibo.apk ⭐⭐
            "changelog" => $changelog,
            "mandatory" => $mandatory,
            "release_date" => $release_date,
            "file_size" => $fileSize,
            "upload_date" => date("Y-m-d H:i:s"),
            "filename" => $finalApkName, // ⭐⭐ SEMPRE ibo.apk ⭐⭐
            "server_path" => "/apkupdate/" . $finalApkName, // ⭐⭐ CAMINHO NO SERVIDOR ⭐⭐
            // ⭐⭐ NOTIFICAÇÃO DE UPDATE ⭐⭐
            "update_notification" => [
                "enabled" => true,
                "title" => "📱 Nova Atualização Disponível!",
                "content" => "Versão " . $version . " disponível!\n\n" . 
                            ($mandatory ? "⚠️ ATUALIZAÇÃO OBRIGATÓRIA\n" : "") .
                            "Tamanho: " . $fileSize . "\n" .
                            "Clique em ATUALIZAR para instalar.",
                "type" => "app_update",
                "version_code" => $version,
                "apk_url" => $url // ⭐⭐ MESMA URL COMPLETA ⭐⭐
            ]
        ];
        
        // SALVAR JSON
        $result = file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        
        if ($result !== false) {
            $msg = "🎉 ATUALIZAÇÃO CONFIGURADA COM SUCESSO!<br>";
            $msg .= "<small>Arquivo salvo como: <strong>/apkupdate/ibo.apk</strong><br>";
            $msg .= "URL gerada: <strong>" . htmlspecialchars($url) . "</strong></small>";
            $msg_type = "success";
        } else {
            $msg = "⚠️ ERRO AO SALVAR O ARQUIVO JSON";
            $msg_type = "error";
        }
    }
}

// FUNÇÃO PARA CALCULAR TAMANHO DO ARQUIVO
function getFileSizeFromVersion($version) {
    $parts = explode('.', $version);
    $major = isset($parts[0]) ? intval($parts[0]) : 1;
    $minor = isset($parts[1]) ? intval($parts[1]) : 0;
    
    $baseSize = 25; // MB
    $increment = 3; // MB por versão
    
    $total = $baseSize + ($major * $increment) + ($minor * 0.5);
    return round($total, 2) . ' MB';
}

// Adicione esta função para obter o caminho base correto do servidor:
function getServerBasePath() {
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    
    // Obtém o diretório atual do script
    $script_path = dirname($_SERVER['SCRIPT_NAME']);
    
    // Remove barras duplicadas e ajusta o caminho
    $base_path = rtrim($script_path, '/');
    
    // Se estiver na raiz, retorna apenas o domínio
    if ($base_path === '') {
        return $protocol . "://" . $host;
    }
    
    return $protocol . "://" . $host . $base_path;
}

// FUNÇÃO PARA FORMATAR DATA DE FORMA SEGURA
function formatDateSafely($dateString) {
    try {
        $date = new DateTime($dateString);
        return $date->format('d/m/Y');
    } catch (Exception $e) {
        return date('d/m/Y');
    }
}

// GERAR URL COMPLETA PARA EXIBIÇÃO
$serverBase = getServerBasePath();

// ⭐⭐ VERIFICAR SE EXISTE APK ATUAL NA PASTA CORRETA ⭐⭐
$currentApkPath = $uploadDir . $finalApkName;
$apkExists = file_exists($currentApkPath);
$apkSize = $apkExists ? formatFileSize(filesize($currentApkPath)) : 'Nenhum APK carregado';
$apkModified = $apkExists ? date('d/m/Y H:i', filemtime($currentApkPath)) : 'N/A';

// ⭐⭐ GERAR URL COMPLETA CORRETA DO APK PARA EXIBIÇÃO ⭐⭐
$currentApkUrl = $apkExists ? $serverBase . '/apkupdate/' . $finalApkName : '';

// ⭐⭐ VERIFICAR SE EXISTE APK ATUAL NA PASTA CORRETA ⭐⭐
$currentApkPath = $uploadDir . $finalApkName;
$apkExists = file_exists($currentApkPath);
$apkSize = $apkExists ? formatFileSize(filesize($currentApkPath)) : 'Nenhum APK carregado';
$apkModified = $apkExists ? date('d/m/Y H:i', filemtime($currentApkPath)) : 'N/A';

// ⭐⭐ GERAR URL COMPLETA DO APK PARA EXIBIÇÃO ⭐⭐
$currentApkUrl = $apkExists ? $serverUrl . '/apkupdate/' . $finalApkName : '';
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestor de Atualizações APK</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Exo+2:wght@300;400;500;600;700;800;900&family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
    /* DESIGN ULTRA MODERNO DE ATUALIZAÇÃO DE APK */
    :root {
        --neon-cyan: #00ffea;
        --neon-purple: #8a2be2;
        --neon-pink: #ff00ff;
        --matrix-green: #00ff41;
        --dark-space: #0a0a0f;
        --space-gray: #1a1a2e;
        --hologram-blue: #4cc9f0;
        --android-green: #3ddc84;
        --android-blue: #4285f4;
        --glow-intensity: 0.8;
    }

    /* Fundo futurista */
    body {
        background: linear-gradient(135deg, #0a0a0f 0%, #1a1a2e 50%, #0f0f1f 100%) fixed !important;
        color: #ffffff !important;
        font-family: 'Exo 2', 'Inter', 'Segoe UI', sans-serif !important;
        min-height: 100vh;
        overflow-x: hidden;
        position: relative;
        margin: 0;
        padding: 0;
    }

    /* Efeito de partículas */
    body::before {
        content: '';
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: 
            radial-gradient(circle at 20% 80%, rgba(0, 255, 234, 0.05) 0%, transparent 50%),
            radial-gradient(circle at 80% 20%, rgba(138, 43, 226, 0.05) 0%, transparent 50%),
            radial-gradient(circle at 40% 40%, rgba(61, 220, 132, 0.03) 0%, transparent 50%);
        pointer-events: none;
        z-index: -2;
    }

    /* Grade holográfica */
    body::after {
        content: '';
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-image: 
            linear-gradient(rgba(0, 255, 234, 0.03) 1px, transparent 1px),
            linear-gradient(90deg, rgba(0, 255, 234, 0.03) 1px, transparent 1px);
        background-size: 50px 50px;
        mask-image: radial-gradient(circle at center, black 30%, transparent 70%);
        pointer-events: none;
        z-index: -1;
    }

    /* Container principal */
    .container-fluid {
        background: transparent !important;
        max-width: 1400px !important;
        margin: 30px auto !important;
        padding: 30px 20px !important;
        position: relative;
        z-index: 1;
    }

    /* Título principal futurista */
    .main-title {
        text-align: center;
        margin-bottom: 50px !important;
        position: relative;
    }

    .main-title h1 {
        font-size: 3.5rem !important;
        font-weight: 900 !important;
        background: linear-gradient(135deg, 
            var(--neon-cyan) 0%, 
            var(--android-green) 50%, 
            var(--neon-purple) 100%) !important;
        -webkit-background-clip: text !important;
        background-clip: text !important;
        color: transparent !important;
        margin-bottom: 20px !important;
        text-transform: uppercase;
        letter-spacing: 2px;
        animation: titleGlow 3s ease-in-out infinite alternate;
    }

    @keyframes titleGlow {
        0% { 
            text-shadow: 
                0 0 20px rgba(0, 255, 234, 0.5),
                0 0 40px rgba(61, 220, 132, 0.3);
        }
        100% { 
            text-shadow: 
                0 0 30px rgba(0, 255, 234, 0.8),
                0 0 60px rgba(138, 43, 226, 0.5),
                0 0 80px rgba(138, 43, 226, 0.3);
        }
    }

    .title-sub {
        font-size: 1.2rem;
        color: rgba(255, 255, 255, 0.7);
        font-weight: 300;
        letter-spacing: 1px;
    }

    /* Layout de duas colunas */
    .dashboard-layout {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 30px;
        margin-bottom: 40px;
    }

    @media (max-width: 992px) {
        .dashboard-layout {
            grid-template-columns: 1fr;
        }
    }

    /* Painel esquerdo - Configuração */
    .config-panel {
        background: rgba(26, 26, 46, 0.9);
        backdrop-filter: blur(20px);
        border-radius: 25px;
        border: 1px solid rgba(0, 255, 234, 0.2);
        box-shadow: 
            0 20px 60px rgba(0, 0, 0, 0.6),
            0 0 0 1px rgba(255, 255, 255, 0.05),
            inset 0 1px 0 rgba(255, 255, 255, 0.1);
        overflow: hidden;
        position: relative;
        padding: 0;
    }

    .config-panel::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, 
            var(--neon-cyan) 0%, 
            var(--android-green) 50%, 
            var(--neon-purple) 100%);
        animation: scanline 3s linear infinite;
    }

    @keyframes scanline {
        0% { background-position: -200% 0; }
        100% { background-position: 200% 0; }
    }

    /* Cabeçalho do painel */
    .panel-header {
        background: linear-gradient(135deg, 
            rgba(0, 255, 234, 0.1) 0%, 
            rgba(138, 43, 226, 0.1) 100%);
        padding: 25px 35px;
        border-bottom: 1px solid rgba(0, 255, 234, 0.2);
        display: flex;
        align-items: center;
        gap: 15px;
    }

    .panel-header h3 {
        color: white;
        font-size: 1.8rem;
        font-weight: 700;
        margin: 0;
        flex: 1;
    }

    .panel-header i {
        font-size: 2.2rem;
        background: linear-gradient(135deg, var(--neon-cyan), var(--android-green));
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
    }

    /* Corpo do painel */
    .panel-body {
        padding: 35px;
    }

    /* Mensagens */
    .notification {
        background: linear-gradient(135deg, 
            rgba(0, 255, 234, 0.15) 0%, 
            rgba(61, 220, 132, 0.15) 100%);
        border: 1px solid rgba(0, 255, 234, 0.3);
        border-radius: 15px;
        padding: 20px 25px;
        margin-bottom: 30px;
        color: white;
        text-align: center;
        animation: pulseNotification 2s ease-in-out infinite;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 15px;
        font-weight: 600;
        font-size: 1.1rem;
        letter-spacing: 1px;
        transition: all 0.3s ease !important;
    }

    .notification.success {
        background: linear-gradient(135deg, 
            rgba(61, 220, 132, 0.2) 0%, 
            rgba(0, 255, 106, 0.2) 100%);
        border-color: rgba(61, 220, 132, 0.4);
    }

    .notification.error {
        background: linear-gradient(135deg, 
            rgba(255, 0, 0, 0.2) 0%, 
            rgba(255, 107, 107, 0.2) 100%);
        border-color: rgba(255, 0, 0, 0.4);
    }

    .notification.error small {
        display: block;
        font-size: 0.85rem;
        margin-top: 10px;
        font-weight: normal;
        opacity: 0.9;
    }

    @keyframes pulseNotification {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.02); }
    }

    /* Info do APK atual */
    .apk-info-card {
        background: rgba(10, 10, 15, 0.8);
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 25px;
        border: 1px solid rgba(61, 220, 132, 0.3);
    }

    .apk-info-card h4 {
        color: var(--android-green);
        font-size: 1.1rem;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .apk-details {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
        margin-bottom: 15px;
    }

    .apk-detail {
        display: flex;
        flex-direction: column;
    }

    .detail-label {
        color: rgba(255, 255, 255, 0.6);
        font-size: 0.85rem;
        margin-bottom: 5px;
    }

    .detail-value {
        color: white;
        font-weight: 600;
        font-size: 1rem;
    }

    .apk-status {
        text-align: center;
        padding: 8px;
        border-radius: 8px;
        font-weight: 600;
        font-size: 0.9rem;
    }

    .apk-status.exists {
        background: rgba(61, 220, 132, 0.2);
        color: var(--android-green);
        border: 1px solid rgba(61, 220, 132, 0.3);
    }

    .apk-status.not-exists {
        background: rgba(255, 107, 107, 0.2);
        color: #ff6b6b;
        border: 1px solid rgba(255, 107, 107, 0.3);
    }

    /* Formulário futurista */
    .futuristic-form {
        display: flex;
        flex-direction: column;
        gap: 25px;
    }

    .input-group-future {
        position: relative;
    }

    .input-label {
        display: block;
        color: var(--neon-cyan);
        font-size: 1rem;
        font-weight: 600;
        margin-bottom: 10px;
        text-transform: uppercase;
        letter-spacing: 1px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .input-label i {
        font-size: 1.2rem;
    }

    .futuristic-input {
        width: 100%;
        background: rgba(10, 10, 15, 0.8);
        border: 2px solid rgba(0, 255, 234, 0.2);
        border-radius: 15px;
        color: white;
        padding: 18px 20px;
        font-size: 1.1rem;
        font-family: 'Consolas', 'Courier New', monospace;
        transition: all 0.3s ease;
        outline: none;
        box-shadow: inset 0 2px 15px rgba(0, 0, 0, 0.5);
    }

    .futuristic-input:focus {
        border-color: var(--neon-cyan);
        box-shadow: 
            inset 0 2px 15px rgba(0, 0, 0, 0.7),
            0 0 30px rgba(0, 255, 234, 0.3);
        background: rgba(10, 10, 15, 0.9);
        transform: translateY(-2px);
    }

    .futuristic-input::placeholder {
        color: rgba(255, 255, 255, 0.3);
        font-style: italic;
    }

    /* Textarea para changelog */
    .changelog-textarea {
        min-height: 150px;
        resize: vertical;
        font-family: 'Segoe UI', sans-serif;
        line-height: 1.6;
    }

    /* Switch futurista */
    .switch-group {
        display: flex;
        align-items: center;
        gap: 15px;
        margin: 10px 0;
    }

    .switch-label {
        color: white;
        font-weight: 500;
        font-size: 1.1rem;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .switch-label i {
        color: var(--android-green);
    }

    /* Custom Switch */
    .switch {
        position: relative;
        display: inline-block;
        width: 70px;
        height: 34px;
    }

    .switch input {
        opacity: 0;
        width: 0;
        height: 0;
    }

    .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(135deg, #333, #555);
        transition: .4s;
        border-radius: 34px;
        box-shadow: inset 0 2px 10px rgba(0, 0, 0, 0.5);
    }

    .slider:before {
        position: absolute;
        content: "";
        height: 26px;
        width: 26px;
        left: 4px;
        bottom: 4px;
        background: linear-gradient(135deg, #888, #aaa);
        transition: .4s;
        border-radius: 50%;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
    }

    input:checked + .slider {
        background: linear-gradient(135deg, var(--android-green), #00cc66);
        box-shadow: 0 0 20px rgba(61, 220, 132, 0.4);
    }

    input:checked + .slider:before {
        transform: translateX(36px);
        background: white;
        box-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
    }

    /* Botão de submit */
    .btn-submit-future {
        background: linear-gradient(135deg, 
            var(--neon-cyan) 0%, 
            var(--android-green) 50%, 
            var(--neon-purple) 100%);
        border: none;
        border-radius: 15px;
        color: white;
        font-weight: 700;
        font-size: 1.2rem;
        padding: 20px 40px;
        cursor: pointer;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
        margin-top: 20px;
        text-transform: uppercase;
        letter-spacing: 2px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 15px;
        box-shadow: 
            0 10px 30px rgba(0, 255, 234, 0.3),
            0 0 0 1px rgba(255, 255, 255, 0.1);
    }

    .btn-submit-future:hover {
        transform: translateY(-5px) scale(1.02);
        box-shadow: 
            0 20px 50px rgba(0, 255, 234, 0.5),
            0 0 0 1px rgba(255, 255, 255, 0.2);
        background: linear-gradient(135deg, 
            var(--android-green) 0%, 
            var(--neon-purple) 50%, 
            var(--neon-cyan) 100%);
    }

    .btn-submit-future:active {
        transform: translateY(-2px) scale(1);
    }

    .btn-submit-future::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, 
            transparent, 
            rgba(255, 255, 255, 0.3), 
            transparent);
        transition: left 0.7s ease;
    }

    .btn-submit-future:hover::before {
        left: 100%;
    }

    /* Painel direito - Preview Android */
    .preview-panel {
        background: rgba(26, 26, 46, 0.9);
        backdrop-filter: blur(20px);
        border-radius: 25px;
        border: 1px solid rgba(61, 220, 132, 0.2);
        box-shadow: 
            0 20px 60px rgba(0, 0, 0, 0.6),
            0 0 0 1px rgba(255, 255, 255, 0.05),
            inset 0 1px 0 rgba(255, 255, 255, 0.1);
        overflow: hidden;
        position: relative;
        padding: 0;
    }

    .preview-panel::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, 
            var(--android-green) 0%, 
            var(--android-blue) 50%, 
            var(--neon-cyan) 100%);
        animation: scanline 3s linear infinite reverse;
    }

    /* Preview Header */
    .preview-header {
        background: linear-gradient(135deg, 
            rgba(61, 220, 132, 0.1) 0%, 
            rgba(66, 133, 244, 0.1) 100%);
        padding: 25px 35px;
        border-bottom: 1px solid rgba(61, 220, 132, 0.2);
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .preview-header h3 {
        color: white;
        font-size: 1.8rem;
        font-weight: 700;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 15px;
    }

    .preview-header h3 i {
        font-size: 2.2rem;
        color: var(--android-green);
    }

    .android-badge {
        background: linear-gradient(135deg, var(--android-green), var(--android-blue));
        color: white;
        padding: 8px 20px;
        border-radius: 12px;
        font-weight: 700;
        font-size: 0.9rem;
        letter-spacing: 1px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    /* Preview Body */
    .preview-body {
        padding: 30px;
        height: 500px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        position: relative;
    }

    /* Celular Android Preview */
    .android-phone {
        width: 300px;
        height: 600px;
        background: linear-gradient(135deg, #1a1a1a, #2d2d2d);
        border-radius: 40px;
        position: relative;
        box-shadow: 
            0 20px 50px rgba(0, 0, 0, 0.8),
            inset 0 0 0 1px rgba(255, 255, 255, 0.1);
        overflow: hidden;
        border: 12px solid #0a0a0a;
    }

    .android-screen {
        width: 100%;
        height: 100%;
        background: linear-gradient(135deg, #0f0f1f, #1a1a2e);
        border-radius: 28px;
        overflow: hidden;
        position: relative;
        padding: 25px;
        display: flex;
        flex-direction: column;
    }

    /* Status bar */
    .status-bar {
        height: 30px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: white;
        font-size: 12px;
        font-weight: 500;
        margin-bottom: 20px;
    }

    .status-left, .status-right {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .status-left i {
        color: var(--android-green);
    }

    /* App content */
    .app-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-align: center;
        gap: 20px;
    }

    .app-icon {
        width: 100px;
        height: 100px;
        background: linear-gradient(135deg, var(--android-green), var(--android-blue));
        border-radius: 25px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 20px;
        box-shadow: 0 10px 30px rgba(61, 220, 132, 0.3);
        animation: iconFloat 3s ease-in-out infinite;
    }

    @keyframes iconFloat {
        0%, 100% { transform: translateY(0); }
        50% { transform: translateY(-10px); }
    }

    .app-icon i {
        font-size: 50px;
        color: white;
    }

    .update-info {
        color: white;
        text-align: center;
    }

    .update-info h2 {
        color: var(--android-green);
        font-size: 1.8rem;
        margin-bottom: 10px;
        font-weight: 700;
    }

    .version-badge {
        background: rgba(61, 220, 132, 0.2);
        color: var(--android-green);
        padding: 8px 20px;
        border-radius: 20px;
        font-weight: 600;
        font-size: 1.1rem;
        margin-bottom: 20px;
        display: inline-block;
        border: 1px solid rgba(61, 220, 132, 0.3);
    }

    .update-details {
        text-align: left;
        margin-top: 20px;
        max-width: 250px;
    }

    .update-details p {
        color: rgba(255, 255, 255, 0.7);
        font-size: 0.9rem;
        margin: 5px 0;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .update-details i {
        color: var(--android-blue);
        font-size: 1rem;
    }

    .update-button {
        background: linear-gradient(135deg, var(--android-green), var(--android-blue));
        color: white;
        border: none;
        padding: 12px 30px;
        border-radius: 12px;
        font-weight: 600;
        font-size: 1rem;
        cursor: pointer;
        margin-top: 25px;
        transition: all 0.3s ease;
        box-shadow: 0 5px 20px rgba(61, 220, 132, 0.3);
    }

    .update-button:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 30px rgba(61, 220, 132, 0.5);
    }

    /* Botão físico do celular */
    .phone-button {
        position: absolute;
        bottom: 25px;
        left: 50%;
        transform: translateX(-50%);
        width: 50px;
        height: 50px;
        background: linear-gradient(135deg, #333, #555);
        border-radius: 50%;
        border: 3px solid #0a0a0a;
    }

    /* JSON Endpoint Preview */
    .endpoint-preview {
        background: rgba(10, 10, 15, 0.8);
        border-radius: 15px;
        padding: 25px;
        margin-top: 30px;
        border: 1px solid rgba(0, 255, 234, 0.2);
    }

    .endpoint-preview h4 {
        color: var(--neon-cyan);
        font-size: 1.2rem;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .endpoint-code {
        background: rgba(0, 0, 0, 0.6);
        border-radius: 10px;
        padding: 15px;
        font-family: 'Consolas', 'Courier New', monospace;
        color: var(--matrix-green);
        font-size: 0.9rem;
        overflow-x: auto;
        white-space: nowrap;
        margin-bottom: 15px;
        border: 1px solid rgba(0, 255, 234, 0.1);
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .endpoint-code:hover {
        border-color: var(--neon-cyan);
        box-shadow: 0 0 20px rgba(0, 255, 234, 0.2);
        transform: translateY(-2px);
    }

    .copy-hint {
        color: rgba(255, 255, 255, 0.5);
        font-size: 0.85rem;
        text-align: center;
        font-style: italic;
    }

    /* Exemplos de versão */
    .version-examples {
        display: flex;
        gap: 10px;
        margin-top: 8px;
        flex-wrap: wrap;
        justify-content: center;
    }

    .version-example {
        background: rgba(61, 220, 132, 0.1);
        border: 1px solid rgba(61, 220, 132, 0.3);
        color: var(--android-green);
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .version-example:hover {
        background: rgba(61, 220, 132, 0.2);
        transform: translateY(-2px);
    }

    /* Estilos para Upload de Arquivo */
    .upload-container {
        display: flex;
        flex-direction: column;
        gap: 20px;
    }

    .file-upload-area {
        background: rgba(10, 10, 15, 0.8);
        border: 2px dashed rgba(0, 255, 234, 0.3);
        border-radius: 15px;
        padding: 40px 20px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }

    .file-upload-area:hover {
        background: rgba(0, 255, 234, 0.05);
        border-color: var(--neon-cyan);
        transform: translateY(-2px);
    }

    .file-upload-area i {
        color: var(--neon-cyan);
        margin-bottom: 15px;
        font-size: 3rem;
    }

    .file-upload-area h4 {
        color: white;
        margin: 10px 0 5px;
        font-size: 1.2rem;
    }

    .file-upload-area p {
        color: rgba(255, 255, 255, 0.6);
        font-size: 0.9rem;
        margin-bottom: 20px;
    }

    .file-input-hidden {
        display: none;
    }

    .btn-upload {
        background: linear-gradient(135deg, var(--android-green), var(--android-blue));
        color: white;
        border: none;
        padding: 12px 25px;
        border-radius: 10px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        display: inline-flex;
        align-items: center;
        gap: 10px;
    }

    .btn-upload:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 20px rgba(61, 220, 132, 0.3);
    }

    .file-info {
        margin-top: 20px;
        padding: 15px;
        background: rgba(61, 220, 132, 0.1);
        border-radius: 10px;
        border: 1px solid rgba(61, 220, 132, 0.3);
        display: none;
    }

    .file-info.active {
        display: block;
        animation: fadeIn 0.3s ease;
    }

    .file-details {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: white;
    }

    .file-name {
        font-weight: 600;
        color: var(--android-green);
        max-width: 70%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .file-size {
        color: rgba(255, 255, 255, 0.7);
        font-size: 0.9rem;
    }

    .upload-progress {
        height: 6px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 3px;
        margin-top: 10px;
        overflow: hidden;
    }

    .progress-bar {
        height: 100%;
        background: linear-gradient(90deg, var(--android-green), var(--android-blue));
        width: 0%;
        transition: width 0.3s ease;
    }

    .upload-divider {
        text-align: center;
        position: relative;
        margin: 10px 0;
    }

    .upload-divider::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        height: 1px;
        background: linear-gradient(90deg, 
            transparent, 
            rgba(0, 255, 234, 0.3), 
            transparent);
    }

    .upload-divider span {
        background: var(--space-gray);
        padding: 0 15px;
        color: rgba(255, 255, 255, 0.5);
        font-size: 0.9rem;
        position: relative;
        z-index: 1;
    }

    .url-alternative {
        margin-top: 10px;
    }

    .url-hint {
        color: rgba(255, 255, 255, 0.5);
        font-size: 0.85rem;
        margin-top: 8px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    /* Animações */
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }

    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .config-panel, .preview-panel, .main-title {
        animation: fadeInUp 0.8s ease forwards;
    }

    .config-panel { animation-delay: 0.1s; }
    .preview-panel { animation-delay: 0.3s; }

    /* Responsividade */
    @media (max-width: 1200px) {
        .container-fluid {
            max-width: 95% !important;
        }
    }

    @media (max-width: 992px) {
        .dashboard-layout {
            grid-template-columns: 1fr;
        }
        
        .android-phone {
            width: 250px;
            height: 500px;
        }
        
        .main-title h1 {
            font-size: 2.8rem !important;
        }
    }

    @media (max-width: 768px) {
        .container-fluid {
            padding: 20px 15px !important;
            margin: 20px auto !important;
        }
        
        .main-title h1 {
            font-size: 2.2rem !important;
        }
        
        .panel-header, .preview-header {
            padding: 20px 25px;
        }
        
        .panel-body, .preview-body {
            padding: 25px;
        }
        
        .android-phone {
            width: 200px;
            height: 400px;
        }
        
        .btn-submit-future {
            padding: 18px 30px;
            font-size: 1.1rem;
        }
    }

    @media (max-width: 480px) {
        .main-title h1 {
            font-size: 1.8rem !important;
        }
        
        .panel-header h3, .preview-header h3 {
            font-size: 1.4rem;
        }
        
        .futuristic-input {
            padding: 15px 18px;
            font-size: 1rem;
        }
        
        .android-phone {
            width: 180px;
            height: 360px;
        }
        
        .app-icon {
            width: 80px;
            height: 80px;
        }
        
        .app-icon i {
            font-size: 40px;
        }
    }
    </style>
</head>
<body>
<div class="container-fluid">
    <!-- Título Principal -->
    <div class="main-title">
        <h1><i class="fab fa-android"></i> GESTOR DE ATUALIZAÇÕES</h1>
        <div class="title-sub">Configure e visualize as atualizações do seu APK em tempo real</div>
    </div>
    
    <!-- Layout de Dashboard -->
    <div class="dashboard-layout">
        <!-- Painel Esquerdo: Configuração -->
        <div class="config-panel">
            <div class="panel-header">
                <i class="fas fa-sliders-h"></i>
                <h3>CONFIGURAÇÃO DA ATUALIZAÇÃO</h3>
            </div>
            
            <div class="panel-body">
                <?php if ($msg): ?>
                    <div class="notification <?php echo $msg_type; ?>" id="successMessage">
                        <i class="fas <?php echo $msg_type == 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'; ?>"></i>
                        <div><?php echo $msg; ?></div>
                    </div>
                <?php endif; ?>
                
                <!-- Info do APK Atual -->
                <div class="apk-info-card">
                    <h4><i class="fas fa-info-circle"></i> APK ATUAL NO SERVIDOR</h4>
                    <div class="apk-details">
                        <div class="apk-detail">
                            <div class="detail-label">PASTA NO SERVIDOR:</div>
                            <div class="detail-value">/apkupdate/ibo.apk</div>
                        </div>
                        <div class="apk-detail">
                            <div class="detail-label">STATUS:</div>
                            <div class="apk-status <?php echo $apkExists ? 'exists' : 'not-exists'; ?>">
                                <?php echo $apkExists ? '✓ DISPONÍVEL' : '✗ NÃO ENCONTRADO'; ?>
                            </div>
                        </div>
                        <div class="apk-detail">
                            <div class="detail-label">TAMANHO:</div>
                            <div class="detail-value"><?php echo $apkSize; ?></div>
                        </div>
                        <div class="apk-detail">
                            <div class="detail-label">ÚLTIMA ATUALIZAÇÃO:</div>
                            <div class="detail-value"><?php echo $apkModified; ?></div>
                        </div>
                    </div>
                    <?php if ($apkExists && $currentApkUrl): ?>
                    <div class="url-hint" style="margin-top: 10px; background: rgba(61, 220, 132, 0.1); padding: 10px; border-radius: 8px;">
                        <i class="fas fa-link"></i>
                        <strong>URL COMPLETA:</strong> 
                        <a href="<?php echo $currentApkUrl; ?>" target="_blank" style="color: var(--neon-cyan); word-break: break-all;">
                            <?php echo $currentApkUrl; ?>
                        </a>
                    </div>
                    <?php endif; ?>
                    <div class="url-hint" style="margin-top: 10px;">
                        <i class="fas fa-exclamation-circle"></i>
                        <strong>ATENÇÃO:</strong> Todo APK enviado será salvo como <strong>/apkupdate/ibo.apk</strong>
                    </div>
                </div>
                
                <form method="POST" class="futuristic-form" id="updateForm" enctype="multipart/form-data">
                    <!-- Version Code -->
                    <div class="input-group-future">
                        <label class="input-label">
                            <i class="fas fa-code-branch"></i>
                            VERSÃO DO APK
                        </label>
                        <input type="text" 
                               class="futuristic-input"
                               name="version" 
                               value="<?php echo htmlspecialchars($displayData['version']); ?>" 
                               required
                               placeholder="Ex: 1.0, 2.1, 3.9, 4.3...">
                        <div class="version-examples">
                            <div class="version-example" data-version="1.0">1.0</div>
                            <div class="version-example" data-version="2.1">2.1</div>
                            <div class="version-example" data-version="3.9">3.9</div>
                            <div class="version-example" data-version="4.3">4.3</div>
                            <div class="version-example" data-version="1.2.3">1.2.3</div>
                        </div>
                    </div>
                    
                    <!-- Upload de Arquivo APK -->
                    <div class="input-group-future">
                        <label class="input-label">
                            <i class="fas fa-cloud-upload-alt"></i>
                            UPLOAD DO NOVO APK
                        </label>
                        
                        <div class="upload-container">
                            <!-- Input de arquivo estilizado -->
                            <div class="file-upload-area" id="fileUploadArea">
                                <i class="fas fa-cloud-upload-alt fa-3x"></i>
                                <h4>ARRASTE OU CLIQUE PARA ENVIAR APK</h4>
                                <p>Arquivos .APK até 500MB • Será salvo como <strong>/apkupdate/ibo.apk</strong></p>
                                <input type="file" 
                                       name="apk_file" 
                                       id="apk_file" 
                                       accept=".apk" 
                                       class="file-input-hidden">
                                <button type="button" class="btn-upload" onclick="document.getElementById('apk_file').click()">
                                    <i class="fas fa-search"></i> ESCOLHER ARQUIVO
                                </button>
                                <div class="file-info" id="fileInfo"></div>
                            </div>
                            
                            <!-- OU -->
                            <div class="upload-divider">
                                <span>OU</span>
                            </div>
                            
                            <!-- URL Externa (alternativa) -->
                            <div class="url-alternative">
                                <label class="input-label">
                                    <i class="fas fa-link"></i>
                                    URL EXTERNA DO APK (alternativa)
                                </label>
                                <input type="text" 
                                       class="futuristic-input"
                                       name="url" 
                                       value="<?php echo htmlspecialchars($displayData['url']); ?>"
                                       placeholder="https://exemplo.com/ibo.apk"
                                       id="externalUrl">
                                <div class="url-hint">
                                    <i class="fas fa-info-circle"></i>
                                    Use esta opção se o APK já estiver hospedado externamente
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Changelog -->
                    <div class="input-group-future">
                        <label class="input-label">
                            <i class="fas fa-clipboard-list"></i>
                            CHANGELOG
                        </label>
                        <textarea class="futuristic-input changelog-textarea"
                                  name="changelog" 
                                  rows="5"
                                  placeholder="• Nova funcionalidade X
• Correção de bug Y
• Melhoria de performance Z"><?php echo htmlspecialchars($displayData['changelog']); ?></textarea>
                    </div>
                    
                    <!-- Data de Release -->
                    <div class="input-group-future">
                        <label class="input-label">
                            <i class="fas fa-calendar-alt"></i>
                            DATA DE RELEASE
                        </label>
                        <input type="date" 
                               class="futuristic-input"
                               name="release_date" 
                               value="<?php echo htmlspecialchars($displayData['release_date']); ?>">
                    </div>
                    
                    <!-- Atualização Obrigatória -->
                    <div class="switch-group">
                        <label class="switch">
                            <input type="checkbox" 
                                   name="mandatory" 
                                   <?php echo $displayData['mandatory'] ? 'checked' : ''; ?>>
                            <span class="slider"></span>
                        </label>
                        <div class="switch-label">
                            <i class="fas fa-exclamation-circle"></i>
                            ATUALIZAÇÃO OBRIGATÓRIA
                        </div>
                    </div>
                    
                    <!-- Botão Submit -->
                    <button type="submit" class="btn-submit-future">
                        <i class="fas fa-rocket"></i>
                        PUBLICAR ATUALIZAÇÃO
                    </button>
                </form>
            </div>
        </div>
        
        <!-- Painel Direito: Preview Android -->
        <div class="preview-panel">
            <div class="preview-header">
                <h3>
                    <i class="fab fa-android"></i>
                    PREVIEW DA ATUALIZAÇÃO
                </h3>
                <div class="android-badge">
                    <i class="fas fa-mobile-alt"></i>
                    ANDROID
                </div>
            </div>
            
            <div class="preview-body">
                <!-- Celular Android Preview -->
                <div class="android-phone">
                    <div class="android-screen">
                        <!-- Status Bar -->
                        <div class="status-bar">
                            <div class="status-left">
                                <i class="fas fa-signal"></i>
                                <i class="fas fa-wifi"></i>
                            </div>
                            <div class="status-right">
                                16:20
                            </div>
                        </div>
                        
                        <!-- Conteúdo do App -->
                        <div class="app-content">
                            <div class="app-icon">
                                <i class="fas fa-sync-alt"></i>
                            </div>
                            
                            <div class="update-info">
                                <h2>ATUALIZAÇÃO DISPONÍVEL</h2>
                                <div class="version-badge" id="previewVersion">
                                    v<?php echo htmlspecialchars($displayData['version']); ?> • <?php echo formatDateSafely($displayData['release_date']); ?>
                                </div>
                                
                                <div class="update-details" id="previewDetails">
                                    <?php if ($displayData['mandatory']): ?>
                                        <p><i class="fas fa-exclamation-triangle"></i> <strong>OBRIGATÓRIA:</strong> Necessária para continuar</p>
                                    <?php endif; ?>
                                    <p><i class="fas fa-download"></i> <strong>TAMANHO:</strong> <?php echo htmlspecialchars($displayData['file_size']); ?></p>
                                    <p><i class="fas fa-calendar"></i> <strong>LANÇAMENTO:</strong> <?php echo formatDateSafely($displayData['release_date']); ?></p>
                                    <p><i class="fas fa-server"></i> <strong>SERVER:</strong> /apkupdate/ibo.apk</p>
                                    <p><i class="fas fa-file"></i> <strong>ARQUIVO:</strong> ibo.apk</p>
                                </div>
                                
                                <button class="update-button" id="previewButton">
                                    <i class="fas fa-download"></i>
                                    ATUALIZAR AGORA
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="phone-button"></div>
                </div>
            </div>
            
            // Endpoint JSON
<div class="endpoint-preview">
    <h4><i class="fas fa-code"></i> ENDPOINT JSON</h4>
    <div class="endpoint-code" id="endpointCode">
        <?php echo $serverBase; ?>/a/ibo.json
    </div>
    <div class="copy-hint">Clique para copiar o endpoint</div>
    
    <!-- URL do APK -->
    <div style="margin-top: 15px;">
        <h4><i class="fas fa-link"></i> URL COMPLETA DO APK</h4>
        <div class="endpoint-code" id="apkUrl">
            <?php echo $serverBase; ?>/apkupdate/ibo.apk
        </div>
        <div class="copy-hint">Clique para copiar a URL completa do APK</div>
    </div>
                
            <!-- Estrutura do JSON -->
<div style="margin-top: 15px;">
    <h4><i class="fas fa-file-code"></i> ESTRUTURA DO JSON</h4>
    <div class="endpoint-code" id="jsonStructure">
{
  "app_info": {
    "android_version_code": "<?php echo htmlspecialchars($displayData['version']); ?>",
    "apk_url": "<?php echo htmlspecialchars($displayData['url'] ?: $serverBase . '/apkupdate/ibo.apk'); ?>",
    "changelog": "<?php echo addslashes($displayData['changelog']); ?>",
    "mandatory": <?php echo $displayData['mandatory'] ? 'true' : 'false'; ?>,
    "release_date": "<?php echo htmlspecialchars($displayData['release_date']); ?>",
    "server_path": "/apkupdate/ibo.apk"
  }
}
    </div>
    <div class="copy-hint">Estrutura atual do arquivo JSON</div>
</div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Elementos
    const form = document.getElementById('updateForm');
    const submitBtn = document.querySelector('.btn-submit-future');
    const endpointCode = document.getElementById('endpointCode');
    const apkUrl = document.getElementById('apkUrl');
    const jsonStructure = document.getElementById('jsonStructure');
    const previewVersion = document.getElementById('previewVersion');
    const previewDetails = document.getElementById('previewDetails');
    const previewButton = document.getElementById('previewButton');
    
    // Mensagem de sucesso que desaparece
    const successMessage = document.getElementById('successMessage');
    if (successMessage) {
        setTimeout(function() {
            successMessage.style.opacity = '0';
            successMessage.style.transform = 'translateY(-10px)';
            setTimeout(function() {
                successMessage.remove();
            }, 300);
        }, 5000);
    }
    
    // Atualizar preview em tempo real
    const versionInput = document.querySelector('input[name="version"]');
    const urlInput = document.getElementById('externalUrl');
    const changelogInput = document.querySelector('textarea[name="changelog"]');
    const mandatoryInput = document.querySelector('input[name="mandatory"]');
    const dateInput = document.querySelector('input[name="release_date"]');
    
    // Exemplos de versão
    document.querySelectorAll('.version-example').forEach(example => {
        example.addEventListener('click', function() {
            versionInput.value = this.getAttribute('data-version');
            versionInput.focus();
            updatePreview();
        });
    });
    
    function updatePreview() {
        // Versão
        const version = versionInput.value || "1.0";
        const date = dateInput.value || new Date().toISOString().split('T')[0];
        const formattedDate = formatDate(date);
        
        if (previewVersion) {
            previewVersion.textContent = `v${version} • ${formattedDate}`;
        }
        
        // Mandatory
        const detailsHTML = [];
        
        if (mandatoryInput.checked) {
            detailsHTML.push(`
                <p><i class="fas fa-exclamation-triangle"></i> 
                <strong>OBRIGATÓRIA:</strong> Necessária para continuar</p>
            `);
        }
        
        detailsHTML.push(`
            <p><i class="fas fa-download"></i> 
            <strong>TAMANHO:</strong> ${getFileSize(version)}</p>
            <p><i class="fas fa-calendar"></i> 
            <strong>LANÇAMENTO:</strong> ${formattedDate}</p>
            <p><i class="fas fa-server"></i> 
            <strong>SERVER PATH:</strong> /apkupdate/ibo.apk</p>
            <p><i class="fas fa-file"></i> 
            <strong>ARQUIVO:</strong> ibo.apk</p>
        `);
        
        if (previewDetails) {
            previewDetails.innerHTML = detailsHTML.join('');
        }
        
        // Atualizar botão de download
        if (previewButton) {
            previewButton.innerHTML = `
                <i class="fas fa-download"></i> 
                ATUALIZAR AGORA
            `;
        }
    }
    
    function formatDate(dateStr) {
        try {
            const date = new Date(dateStr);
            return date.toLocaleDateString('pt-BR');
        } catch (e) {
            return new Date().toLocaleDateString('pt-BR');
        }
    }
    
    function getFileSize(version) {
        // Calcula tamanho baseado na versão (simulação)
        const parts = version.split('.');
        const major = parseInt(parts[0]) || 1;
        const minor = parseInt(parts[1]) || 0;
        
        // Tamanho base + incremento por versão
        const baseSize = 25; // MB
        const increment = 3; // MB por versão
        
        const total = baseSize + (major * increment) + (minor * 0.5);
        return Math.round(total) + ' MB';
    }
    
    // Event listeners para atualização em tempo real
    [versionInput, changelogInput, mandatoryInput, dateInput].forEach(input => {
        if (input) {
            input.addEventListener('input', updatePreview);
            input.addEventListener('change', updatePreview);
        }
    });
    
    // Validação da versão em tempo real
    if (versionInput) {
        versionInput.addEventListener('input', function() {
            const version = this.value;
            const versionPattern = /^\d+(\.\d+)*$/;
            
            if (version && !versionPattern.test(version)) {
                this.style.borderColor = '#ff4757';
                this.style.boxShadow = '0 0 0 3px rgba(255, 71, 87, 0.2)';
            } else if (version) {
                this.style.borderColor = '#00ff41';
                this.style.boxShadow = '0 0 0 3px rgba(0, 255, 65, 0.2)';
            } else {
                this.style.borderColor = 'rgba(0, 255, 234, 0.2)';
                this.style.boxShadow = 'none';
            }
        });
    }
    
    // Validação da URL em tempo real
    if (urlInput) {
        urlInput.addEventListener('input', function() {
            const url = this.value;
            const urlPattern = /^(https?:\/\/)[^\s]+$/;
            
            if (url && !urlPattern.test(url)) {
                this.style.borderColor = '#ff4757';
                this.style.boxShadow = '0 0 0 3px rgba(255, 71, 87, 0.2)';
            } else if (url) {
                this.style.borderColor = '#00ff41';
                this.style.boxShadow = '0 0 0 3px rgba(0, 255, 65, 0.2)';
            } else {
                this.style.borderColor = 'rgba(0, 255, 234, 0.2)';
                this.style.boxShadow = 'none';
            }
        });
    }
    
    // Inicializar preview
    updatePreview();
    
    // Efeito de loading no botão submit
    if (submitBtn && form) {
        form.addEventListener('submit', function(e) {
            // Validar versão
            const version = versionInput ? versionInput.value : '';
            const versionPattern = /^\d+(\.\d+)*$/;
            
            if (!versionPattern.test(version)) {
                e.preventDefault();
                
                // Mostrar mensagem de erro
                const errorMsg = document.createElement('div');
                errorMsg.className = 'notification error';
                errorMsg.innerHTML = `
                    <i class="fas fa-exclamation-triangle"></i>
                    <div>Versão inválida! Use formato: 1.0, 2.1, 3.9</div>
                `;
                
                const panelBody = document.querySelector('.panel-body');
                if (panelBody) {
                    const formElement = document.querySelector('.futuristic-form');
                    if (formElement) {
                        panelBody.insertBefore(errorMsg, formElement);
                    }
                }
                
                setTimeout(() => {
                    errorMsg.remove();
                }, 5000);
                return false;
            }
            
            // Mostrar loading
            const originalHTML = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> PUBLICANDO...';
            submitBtn.disabled = true;
            
            // Simular delay para mostrar animação
            setTimeout(() => {
                submitBtn.innerHTML = originalHTML;
                submitBtn.disabled = false;
            }, 2000);
        });
    }
    
    // Copiar endpoint
    if (endpointCode) {
        endpointCode.addEventListener('click', function() {
            const text = this.textContent;
            navigator.clipboard.writeText(text).then(() => {
                const originalText = this.textContent;
                this.textContent = '✓ Endpoint copiado!';
                this.style.color = '#00ff41';
                
                setTimeout(() => {
                    this.textContent = originalText;
                    this.style.color = '';
                }, 2000);
            });
        });
    }
    
    // Copiar URL do APK
    if (apkUrl) {
        apkUrl.addEventListener('click', function() {
            const text = this.textContent;
            navigator.clipboard.writeText(text).then(() => {
                const originalText = this.textContent;
                this.textContent = '✓ URL completa copiada!';
                this.style.color = '#00ff41';
                
                setTimeout(() => {
                    this.textContent = originalText;
                    this.style.color = '';
                }, 2000);
            });
        });
    }
    
    // Copiar estrutura JSON
    if (jsonStructure) {
        jsonStructure.addEventListener('click', function() {
            const text = this.textContent;
            navigator.clipboard.writeText(text).then(() => {
                const originalText = this.textContent;
                this.textContent = '✓ Estrutura JSON copiada!';
                this.style.color = '#00ff41';
                
                setTimeout(() => {
                    this.textContent = originalText;
                    this.style.color = '';
                }, 2000);
            });
        });
    }
    
    // Simular download no preview
    if (previewButton) {
        previewButton.addEventListener('click', function(e) {
            e.preventDefault();
            
            const originalText = this.innerHTML;
            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> BAIXANDO...';
            this.disabled = true;
            
            setTimeout(() => {
                this.innerHTML = '<i class="fas fa-check"></i> INSTALAR AGORA';
                this.disabled = false;
                
                setTimeout(() => {
                    this.innerHTML = originalText;
                }, 2000);
            }, 1500);
        });
    }
    
    // Efeito de digitação no changelog
    if (changelogInput) {
        changelogInput.addEventListener('focus', function() {
            this.style.minHeight = '200px';
        });
        
        changelogInput.addEventListener('blur', function() {
            this.style.minHeight = '150px';
        });
    }
    
    // Animação do ícone do app
    const appIcon = document.querySelector('.app-icon i');
    if (appIcon) {
        let rotation = 0;
        
        setInterval(() => {
            rotation = (rotation + 1) % 360;
            appIcon.style.transform = `rotate(${rotation}deg)`;
        }, 50);
    }
    
    // =========== SISTEMA DE UPLOAD ===========
    const fileInput = document.getElementById('apk_file');
    const fileUploadArea = document.getElementById('fileUploadArea');
    const fileInfo = document.getElementById('fileInfo');
    const externalUrl = document.getElementById('externalUrl');
    
    // Drag and drop
    if (fileUploadArea) {
        // Prevent default drag behaviors
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            fileUploadArea.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        // Highlight drop area
        ['dragenter', 'dragover'].forEach(eventName => {
            fileUploadArea.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            fileUploadArea.addEventListener(eventName, unhighlight, false);
        });
        
        function highlight() {
            fileUploadArea.style.background = 'rgba(0, 255, 234, 0.1)';
            fileUploadArea.style.borderColor = 'var(--neon-cyan)';
            fileUploadArea.style.transform = 'scale(1.02)';
        }
        
        function unhighlight() {
            fileUploadArea.style.background = '';
            fileUploadArea.style.borderColor = '';
            fileUploadArea.style.transform = '';
        }
        
        // Handle drop
        fileUploadArea.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length > 0) {
                fileInput.files = files;
                updateFileInfo(files[0]);
            }
        }
    }
    
    // Handle file selection
    if (fileInput) {
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                updateFileInfo(this.files[0]);
            }
        });
    }
    
    function updateFileInfo(file) {
        if (!fileInfo) return;
        
        const fileName = file.name;
        const fileSize = formatBytes(file.size);
        
        // Validar se é APK
        if (!fileName.toLowerCase().endsWith('.apk')) {
            fileInfo.innerHTML = `
                <div style="color: #ff4757; text-align: center;">
                    <i class="fas fa-times-circle"></i>
                    <div>APENAS ARQUIVOS .APK SÃO PERMITIDOS</div>
                </div>
            `;
            fileInfo.className = 'file-info active';
            return;
        }
        
        // Mostrar informações do arquivo
        fileInfo.innerHTML = `
            <div class="file-details">
                <div class="file-name" title="${fileName}">
                    <i class="fas fa-file-android"></i> ${fileName}
                </div>
                <div class="file-size">${fileSize}</div>
            </div>
            <div class="upload-progress">
                <div class="progress-bar" id="progressBar"></div>
            </div>
            <div style="text-align: center; margin-top: 10px;">
                <div style="color: var(--neon-cyan); margin-bottom: 5px;">
                    <i class="fas fa-info-circle"></i>
                    <strong>Será salvo como:</strong> /apkupdate/ibo.apk
                </div>
                <div style="color: #00ff41;">
                    <i class="fas fa-check-circle"></i> PRONTO PARA ENVIAR
                </div>
            </div>
        `;
        fileInfo.className = 'file-info active';
        
        // Quando arquivo é selecionado, limpar URL externa
        if (externalUrl) {
            externalUrl.value = '';
        }
    }
    
    function formatBytes(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // Quando URL externa é preenchida, limpar arquivo
    if (externalUrl) {
        externalUrl.addEventListener('input', function() {
            if (this.value.trim() !== '') {
                fileInput.value = '';
                fileInfo.className = 'file-info';
                fileInfo.innerHTML = '';
            }
        });
    }
    
    // Mostrar upload progress (simulado)
    if (form) {
        form.addEventListener('submit', function(e) {
            const file = fileInput.files[0];
            const url = externalUrl ? externalUrl.value : '';
            
            // Validar que pelo menos um dos dois foi preenchido
            if (!file && (!url || url.trim() === '')) {
                e.preventDefault();
                alert('⚠️ Selecione um arquivo APK ou insira uma URL externa!');
                return false;
            }
            
            // Se tem arquivo, mostrar progresso
            if (file) {
                const progressBar = document.getElementById('progressBar');
                if (progressBar) {
                    progressBar.style.width = '100%';
                    progressBar.style.transition = 'width 2s ease';
                }
            }
        });
    }
});
</script>

<?php
include "includes/footer.php";
?>
</body>
</html>