<?php


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


session_start();
include 'includes/conexao.php';

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

// Processa o formulário de atualização
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $appName = $_POST['app_name'];
    $version = $_POST['version'];
    $changelog = $_POST['changelog'];
    
    // Pasta de destino
    $targetDir = "update/";
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }
    
    // Nome do arquivo APK
    $apkFileName = preg_replace('/[^a-zA-Z0-9]/', '_', strtolower($appName)) . "_v" . $version . ".apk";
    $apkFile = $targetDir . $apkFileName;
    
    // Remove arquivo APK antigo se existir
    array_map('unlink', glob($targetDir . "*.apk"));
    
    if ($_FILES['apk_file']['error'] === UPLOAD_ERR_OK) {
        if (!move_uploaded_file($_FILES['apk_file']['tmp_name'], $apkFile)) {
            $_SESSION['erro'] = "⚠️ Falha ao mover o arquivo APK!";
            header("Location: update.php");
            exit;
        }
    } else {
        $_SESSION['erro'] = "⚠️ Erro no upload do APK: " . $_FILES['apk_file']['error'];
        header("Location: update.php");
        exit;
    }
    
    // Gera a URL correta
    $baseUrl = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];
    $scriptPath = dirname($_SERVER['SCRIPT_NAME']);
    $updateUrl = rtrim($baseUrl, '/') . '/' . ltrim($scriptPath, '/') . '/' . $apkFile;
    
    // Cria o JSON no formato solicitado
    $jsonData = [
        'versao' => $version,
        'url_apk' => $updateUrl,
        'mensagem' => $changelog
    ];
    
    if (!file_put_contents($targetDir . "versao.json", json_encode($jsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))) {
        $_SESSION['erro'] = "⚠️ Erro ao salvar o arquivo JSON!";
        header("Location: update.php");
        exit;
    }
    
    $_SESSION['mensagem'] = "✅ App atualizado com sucesso!";
    $_SESSION['mensagem_tempo'] = time() + 3; // 3 segundos no futuro
    header("Location: update.php");
    exit;
}

// Verifica se a mensagem expirou
if (isset($_SESSION['mensagem_tempo']) && time() > $_SESSION['mensagem_tempo']) {
    unset($_SESSION['mensagem']);
    unset($_SESSION['mensagem_tempo']);
}

// Mensagens flash
$mensagem = $_SESSION['mensagem'] ?? '';
$erro = $_SESSION['erro'] ?? '';
unset($_SESSION['mensagem'], $_SESSION['erro']);

include 'includes/header.php';
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Atualizar App - FuturoTech</title>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --neon-cyan: #00f0ff;
            --neon-purple: #9600ff;
            --dark-space: #0f0f1a;
        }
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            background: var(--dark-space);
            color: white;
            font-family: 'Orbitron', sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            background-image: 
                radial-gradient(circle at 10% 20%, rgba(150, 0, 255, 0.1) 0%, transparent 20%),
                radial-gradient(circle at 90% 80%, rgba(0, 255, 252, 0.1) 0%, transparent 20%);
        }
        .glass-container {
            background: rgba(15, 15, 26, 0.7);
            backdrop-filter: blur(12px);
            border: 1px solid var(--neon-cyan);
            border-radius: 15px;
            padding: 30px;
            width: 100%;
            max-width: 600px;
            box-shadow: 0 0 25px rgba(0, 240, 255, 0.2);
            margin: 20px;
            animation: glow 3s infinite alternate;
        }
        @keyframes glow {
            from { box-shadow: 0 0 10px rgba(0, 240, 255, 0.5); }
            to { box-shadow: 0 0 20px rgba(150, 0, 255, 0.7); }
        }
        h1 {
            color: var(--neon-cyan);
            text-align: center;
            font-size: 1.8rem;
            margin-bottom: 25px;
            text-shadow: 0 0 10px var(--neon-cyan);
        }
        .input-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            color: var(--neon-cyan);
            font-size: 0.9rem;
        }
        input, textarea {
            width: 95%;
            padding: 12px;
            background: rgba(0, 0, 30, 0.5);
            border: 1px solid var(--neon-cyan);
            border-radius: 8px;
            color: white;
            font-family: 'Orbitron', sans-serif;
        }
        textarea {
            min-height: 100px;
            resize: vertical;
        }
        .neon-button {
            background: transparent;
            color: var(--neon-cyan);
            border: 2px solid var(--neon-cyan);
            padding: 12px;
            font-size: 1.1rem;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.3s;
            width: 100%;
            margin-top: 10px;
        }
        .neon-button:hover {
            background: var(--neon-cyan);
            color: var(--dark-space);
            box-shadow: 0 0 20px var(--neon-cyan);
        }
        .alert {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
            transition: opacity 0.5s ease;
        }
        .success {
            background: rgba(0, 255, 136, 0.1);
            border: 1px solid #00ff88;
            color: #00ff88;
        }
        .error {
            background: rgba(255, 0, 64, 0.1);
            border: 1px solid #ff0040;
            color: #ff0040;
        }
    </style>
</head>
<body>
    <div class="glass-container">
        <h1>🚀 ATUALIZAR APK</h1>
        
        <?php if ($mensagem): ?>
            <div class="alert success" id="flash-message"><?= htmlspecialchars($mensagem) ?></div>
        <?php endif; ?>
        
        <?php if ($erro): ?>
            <div class="alert error"><?= htmlspecialchars($erro) ?></div>
        <?php endif; ?>
        
        <form method="POST" enctype="multipart/form-data">
            <div class="input-group">
                <label>🔷 Nome do App</label>
                <input type="text" name="app_name" required>
            </div>
            
            <div class="input-group">
                <label>🔢 Versão (ex: 2.0 ou 2.0.0)</label>
                <input type="text" name="version" required pattern="\d+(\.\d+){0,2}" title="Formato: X, X.X ou X.X.X">
            </div>
            
            <div class="input-group">
                <label>📝 Changelog</label>
                <textarea name="changelog" required placeholder="🆕 Novidades:
- Correção de bugs
- Melhorias de performance"></textarea>
            </div>
            
            <div class="input-group">
                <label>📦 Arquivo APK</label>
                <input type="file" name="apk_file" accept=".apk" required>
            </div>
            
            <button type="submit" class="neon-button">💾 SALVAR ATUALIZAÇÃO</button>
        </form>
    </div>

    <script>
    // Remove a mensagem após 3 segundos
    document.addEventListener('DOMContentLoaded', function() {
        const flashMessage = document.getElementById('flash-message');
        if (flashMessage) {
            setTimeout(() => {
                flashMessage.style.opacity = '0';
                setTimeout(() => flashMessage.remove(), 500);
            }, 3000);
        }
    });
    </script>
</body>
</html>