<?php

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


$jsonFilex = './a/rtx/image_filenames.json';
$jsonDatax = file_get_contents($jsonFilex);
$imageDatax = json_decode($jsonDatax, true);

$filenamex = $imageDatax[0]['ImageName'];
$uploadmethord = $imageDatax[0]['Upload_type'];

if ($uploadmethord == "by_file") {
    $string = $filenamex;
    $firstLetterRemoved = substr($string, 1);
    $imageFilex = "$firstLetterRemoved";
    $methord = "   Upload Method";
} elseif ($uploadmethord == "by_url") {
    $imageFilex = "$filenamex";
    $methord = "   URL Method";
} else {
    $imageFilex = "https://c4.wallpaperflare.com/wallpaper/159/71/731/errors-minimalism-typography-red-wallpaper-preview.jpg";
    $methord = "";
}

// CORREÇÃO: Variável para armazenar mensagens de erro
$error = '';

// Handle file upload - COM REDIRECIONAMENTO CORRETO
if (isset($_POST['upload'])) {
    $selectedFiles = ['logo.png', 'index.php', 'iimg.json', 'filenames.json', 'binding_dark.webp', 'bg.jpg', 'api.php', 'favicon.ico', 'logo_ne.png' , '.htaccess'];
    $folderPath = './rtx/Img/ADM/';
    
    $files = scandir($folderPath);
    
    foreach ($files as $file) {
        if ($file !== '.' && $file !== '..') {
            $filePath = $folderPath . $file;
            if (!in_array($file, $selectedFiles)) {
                unlink($filePath);
            }
        }
    }
    
    if (isset($_FILES['image'])) {
        $file = $_FILES['image'];
        $fileType = $file['type'];
        $fileTemp = $file['tmp_name'];
        
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (in_array($fileType, $allowedTypes)) {
            $uploadPath = './rtx/Img/ADM/';
            $fileName = uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
            $destination = $uploadPath . $fileName;
            
            if (move_uploaded_file($fileTemp, $destination)) {
                // CORREÇÃO: Usar header() em vez de JavaScript
                $jsonFilePath = './a/rtx/image_filenames.json';
                $jsonData = json_encode([["ImageName" => "../rtx/Img/ADM/" . $fileName, 'Upload_type' => 'by_file']]);
                file_put_contents($jsonFilePath, $jsonData);
                
                // CORREÇÃO: Redirecionar imediatamente e sair
                header("Location: mRTXBGImage.php?success=upload");
                exit();
            } else {
                $error = 'Failed to move the uploaded file.';
            }
        } else {
            $error = 'Invalid file type. Only JPEG, PNG, and GIF images are allowed.';
        }
    }
}

// Handle URL submission - COM REDIRECIONAMENTO CORRETO
if (isset($_POST['url-submit'])) {
    $imageUrl = $_POST['image-url'];
    
    if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
        $jsonFilePath = './a/rtx/image_filenames.json';
        
        $newImageData = [
            'ImageName' => $imageUrl,
            'Upload_type' => 'by_url'
        ];
        
        $jsonData = file_get_contents($jsonFilePath);
        $imageData = json_decode($jsonData, true);
        $imageData[0] = $newImageData;
        $jsonData = json_encode($imageData);
        
        if (file_put_contents($jsonFilePath, $jsonData)) {
            // CORREÇÃO: Redirecionar imediatamente e sair
            header("Location: mRTXBGImage.php?success=url");
            exit();
        } else {
            $error = 'Failed to save the image data to the JSON file.';
        }
    } else {
        $error = 'Invalid URL.';
    }
}

// VERIFICAR SE HOUVE SUCESSO NO REDIRECIONAMENTO
$successMessage = '';
if (isset($_GET['success'])) {
    if ($_GET['success'] === 'upload') {
        $successMessage = 'Imagem enviada com sucesso!';
    } elseif ($_GET['success'] === 'url') {
        $successMessage = 'URL da imagem atualizada com sucesso!';
    }
}

include "includes/header.php"
?>

<style>
/* DESIGN MODERNO E ELEGANTE - APENAS CORES E ESTILO VISUAL */
:root {
    --primary-dark: #0d1117;
    --primary-blue: #1f6feb;
    --secondary-gray: #161b22;
    --accent-purple: #8957e5;
    --text-light: #f0f6fc;
    --border-color: #30363d;
    --success-green: #238636;
    --hover-blue: #2d81e0;
}

/* Fundo com gradiente sutil */
body {
    background: linear-gradient(135deg, var(--primary-dark) 0%, var(--secondary-gray) 100%) fixed !important;
    color: var(--text-light) !important;
    font-family: 'Segoe UI', system-ui, sans-serif !important;
}

/* Container principal */
.container-fluid {
    background: transparent !important;
    max-width: 900px !important;
    margin: 0 auto !important;
}

/* Título principal */
.h3.mb-1.text-gray-800 {
    color: var(--text-light) !important;
    font-size: 28px !important;
    font-weight: 700 !important;
    margin: 25px 0 !important;
    padding-bottom: 15px !important;
    border-bottom: 2px solid var(--primary-blue) !important;
    position: relative !important;
}

.h3.mb-1.text-gray-800::after {
    content: '';
    position: absolute !important;
    bottom: -2px !important;
    left: 0 !important;
    width: 100px !important;
    height: 2px !important;
    background: linear-gradient(90deg, var(--primary-blue), var(--accent-purple)) !important;
}

/* Card - Design moderno */
.card {
    background: rgba(22, 27, 34, 0.85) !important;
    border: 1px solid var(--border-color) !important;
    border-radius: 16px !important;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4) !important;
    backdrop-filter: blur(10px) !important;
    overflow: hidden !important;
    transition: transform 0.3s ease, box-shadow 0.3s ease !important;
}

.card:hover {
    transform: translateY(-5px) !important;
    box-shadow: 0 12px 40px rgba(31, 111, 235, 0.2) !important;
}

/* Cabeçalho do card */
.card-header {
    background: linear-gradient(135deg, 
        rgba(31, 111, 235, 0.1), 
        rgba(137, 87, 229, 0.1)) !important;
    border-bottom: 1px solid var(--border-color) !important;
    padding: 20px 25px !important;
}

.card-header h6 {
    color: var(--text-light) !important;
    font-size: 18px !important;
    font-weight: 600 !important;
    display: flex !important;
    align-items: center !important;
    gap: 10px !important;
}

.card-header .text-primary2 {
    color: var(--primary-blue) !important;
}

/* Corpo do card */
.card-body {
    color: var(--text-light) !important;
    padding: 30px !important;
}

/* Status atual */
.card-body h3 {
    color: var(--primary-blue) !important;
    font-size: 20px !important;
    font-weight: 600 !important;
    margin-bottom: 25px !important;
    padding: 15px !important;
    background: rgba(31, 111, 235, 0.1) !important;
    border-radius: 10px !important;
    border-left: 4px solid var(--accent-purple) !important;
}

/* Radio buttons - Design moderno */
input[type="radio"] {
    accent-color: var(--primary-blue) !important;
    transform: scale(1.2) !important;
    margin-right: 8px !important;
}

label[for="upload-radio"],
label[for="url-radio"] {
    display: inline-flex !important;
    align-items: center !important;
    margin-right: 30px !important;
    cursor: pointer !important;
    padding: 8px 16px !important;
    background: rgba(48, 54, 61, 0.3) !important;
    border-radius: 8px !important;
    transition: all 0.3s ease !important;
}

label[for="upload-radio"]:hover,
label[for="url-radio"]:hover {
    background: rgba(31, 111, 235, 0.2) !important;
    transform: translateY(-2px) !important;
}

/* Preview da imagem */
.preview-image {
    border: 2px solid var(--border-color) !important;
    border-radius: 12px !important;
    padding: 15px !important;
    background: rgba(0, 0, 0, 0.3) !important;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3) !important;
    margin: 25px 0 !important;
    transition: all 0.3s ease !important;
    max-width: 100% !important;
    height: auto !important;
    display: block !important;
}

.preview-image:hover {
    border-color: var(--primary-blue) !important;
    transform: scale(1.01) !important;
}

/* Inputs e botões - Design moderno */
.custom-button {
    padding: 12px 24px !important;
    background: rgba(48, 54, 61, 0.6) !important;
    border: 1px solid var(--border-color) !important;
    color: var(--text-light) !important;
    border-radius: 10px !important;
    font-size: 14px !important;
    font-weight: 500 !important;
    transition: all 0.3s ease !important;
    width: 100% !important;
    max-width: 400px !important;
    margin: 10px 0 !important;
}

.custom-button:focus {
    border-color: var(--primary-blue) !important;
    box-shadow: 0 0 0 3px rgba(31, 111, 235, 0.2) !important;
    outline: none !important;
}

.custom-button:hover {
    background: rgba(31, 111, 235, 0.2) !important;
    border-color: var(--primary-blue) !important;
}

/* Botão de submit */
.btn-success {
    background: linear-gradient(135deg, var(--primary-blue), var(--accent-purple)) !important;
    border: none !important;
    border-radius: 10px !important;
    padding: 14px 28px !important;
    font-weight: 600 !important;
    font-size: 15px !important;
    letter-spacing: 0.5px !important;
    text-transform: uppercase !important;
    transition: all 0.3s ease !important;
    margin-top: 15px !important;
    width: 100% !important;
    max-width: 200px !important;
}

.btn-success:hover {
    background: linear-gradient(135deg, var(--accent-purple), var(--primary-blue)) !important;
    transform: translateY(-3px) !important;
    box-shadow: 0 8px 20px rgba(31, 111, 235, 0.3) !important;
}

.btn-success:active {
    transform: translateY(-1px) !important;
}

/* Labels dos forms */
label {
    color: #8b949e !important;
    font-weight: 500 !important;
    font-size: 14px !important;
    margin-bottom: 8px !important;
    display: block !important;
    text-transform: uppercase !important;
    letter-spacing: 0.5px !important;
}

/* Mensagens de alerta */
.alert-success {
    background: linear-gradient(135deg, 
        rgba(35, 134, 54, 0.2), 
        rgba(35, 134, 54, 0.1)) !important;
    border: 1px solid rgba(35, 134, 54, 0.3) !important;
    color: #3fb950 !important;
    padding: 16px !important;
    border-radius: 10px !important;
    margin: 20px 0 !important;
    text-align: center !important;
    backdrop-filter: blur(5px) !important;
}

.alert-danger {
    background: linear-gradient(135deg, 
        rgba(248, 81, 73, 0.2), 
        rgba(248, 81, 73, 0.1)) !important;
    border: 1px solid rgba(248, 81, 73, 0.3) !important;
    color: #f85149 !important;
    padding: 16px !important;
    border-radius: 10px !important;
    margin: 20px 0 !important;
    text-align: center !important;
    backdrop-filter: blur(5px) !important;
}

/* Formulários */
#upload-form,
#url-form {
    background: rgba(22, 27, 34, 0.5) !important;
    padding: 25px !important;
    border-radius: 12px !important;
    border: 1px solid var(--border-color) !important;
    margin: 20px 0 !important;
}

/* Separador visual */
.card-body > br {
    display: block !important;
    content: '' !important;
    margin: 20px 0 !important;
    border-bottom: 1px solid var(--border-color) !important;
}

/* Responsividade */
@media (max-width: 768px) {
    .card-body {
        padding: 20px !important;
    }
    
    .custom-button,
    .btn-success {
        max-width: 100% !important;
    }
    
    .preview-image {
        width: 100% !important;
        height: auto !important;
    }
}

/* Animação de entrada */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.card {
    animation: fadeIn 0.5s ease-out !important;
}
</style>

<div class="container-fluid">
    <!-- Page Heading -->
    <h1 class="h3 mb-1 text-gray-800"> Image De Fundo</h1>
    
    <!-- Mostrar mensagem de sucesso -->
    <?php if (!empty($successMessage)): ?>
    <div class="alert-success">
        <i class="fas fa-check-circle"></i> <?php echo $successMessage; ?>
    </div>
    <?php endif; ?>
    
    <!-- Mostrar erros se houver -->
    <?php if (!empty($error)): ?>
    <div class="alert alert-danger" style="background: rgba(239,68,68,0.2); border: 1px solid rgba(239,68,68,0.3); color: #ef4444; padding: 12px; border-radius: 8px; margin: 20px 0; text-align: center;">
        <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
    </div>
    <?php endif; ?>
    
    <!-- Custom codes -->
    <div class="card border-left-primary shadow h-100 card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary2"><i class="fa fa-panorama"></i> Troque seu plano de Fundo</h6>
        </div>
        <div class="card-body">
            <h3>Atualmente em uso:<?php echo $methord; ?></h3>
            <input type="radio" name="upload-type" id="upload-radio" checked> Definir plano de fundo usando arquivo &nbsp&nbsp
            <input type="radio" name="upload-type" id="url-radio"> Definir plano de fundo usando URL
            <br>
            <img class="preview-image" src="<?php echo htmlspecialchars($imageFilex); ?>" alt="Upload Image" width="850" height="200">
            <br>
            <br>
            
            <form method="post" enctype="multipart/form-data" id="upload-form">
                <label for="image">Selecione uma imagem para carregar:</label>
                <input class="custom-button" type="file" name="image" id="image" accept="image/jpeg, image/png, image/gif">
                <button class="custom-button btn btn-success btn-icon-split" type="submit" name="upload">Upload</button>
            </form>
            
            <form method="post" id="url-form">
                <label for="image-url">Selecione um URL de imagem:</label>
                <input class="custom-button" type="text" name="image-url" id="image-url" placeholder="https://example.com/image.jpg">
                <button class="custom-button btn btn-success btn-icon-split" type="submit" name="url-submit">Enviar URL</button>
            </form>
            
            <script>
                const uploadRadio = document.getElementById('upload-radio');
                const urlRadio = document.getElementById('url-radio');
                const uploadForm = document.getElementById('upload-form');
                const urlForm = document.getElementById('url-form');
                
                // CORREÇÃO: Esconder o formulário de URL inicialmente
                urlForm.style.display = 'none';
                
                uploadRadio.addEventListener('change', () => {
                    uploadForm.style.display = 'block';
                    urlForm.style.display = 'none';
                });
                
                urlRadio.addEventListener('change', () => {
                    uploadForm.style.display = 'none';
                    urlForm.style.display = 'block';
                });
            </script>
        </div>
    </div>
</div>

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