<?php
// Silencia avisos para manter o visual limpo
ini_set('display_errors', 0);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);

include "includes/header.php";

$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 = "Arquivo Local";
} elseif ($uploadmethord == "by_url") {
    $imageFilex = "$filenamex";
    $methord = "Link Externo (URL)";
} else {
    $imageFilex = "https://c4.wallpaperflare.com/wallpaper/159/71/731/errors-minimalism-typography-red-wallpaper-preview.jpg";
    $methord = "Padrão";
}

// Lógica de Upload de Arquivo
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/';
    $files = scandir($folderPath);
    foreach ($files as $file) {
        if ($file !== '.' && $file !== '..' && !in_array($file, $selectedFiles)) {
            unlink($folderPath . $file);
        }
    }
    if (isset($_FILES['image'])) {
        $file = $_FILES['image'];
        $fileType = $file['type'];
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (in_array($fileType, $allowedTypes)) {
            $uploadPath = './rtx/Img/';
            $fileName = uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
            $destination = $uploadPath . $fileName;
            if (move_uploaded_file($file['tmp_name'], $destination)) {
                $jsonData = json_encode([["ImageName" => "../rtx/Img/" . $fileName, 'Upload_type' => 'by_file']]);
                file_put_contents($jsonFilex, $jsonData);
                echo "<script>window.location.href='Image.php';</script>";
            }
        }
    }
}

// Lógica de URL
if (isset($_POST['url-submit'])) {
    $imageUrl = $_POST['image-url'];
    if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
        $newImageData = [['ImageName' => $imageUrl, 'Upload_type' => 'by_url']];
        file_put_contents($jsonFilex, json_encode($newImageData));
        echo "<script>window.location.href='Image.php';</script>";
    }
}
?>

<style>
    /* REMOVE FUNDO BRANCO */
    #content-wrapper, #content, .container-fluid, main {
        background-color: #06070a !important;
    }

    .flux-card {
        background: #0f111a !important;
        border: 1px solid rgba(255,255,255,0.05) !important;
        border-radius: 2rem !important;
    }

    .preview-container {
        border-radius: 1.5rem;
        overflow: hidden;
        border: 2px solid rgba(139, 92, 246, 0.3);
        box-shadow: 0 0 30px rgba(139, 92, 246, 0.1);
        background: #000;
        margin: 20px 0;
    }

    .preview-image {
        width: 100%;
        height: auto;
        max-height: 350px;
        object-fit: cover;
        display: block;
    }

    .flux-input {
        background: rgba(255,255,255,0.03) !important;
        border: 1px solid rgba(139, 92, 246, 0.2) !important;
        border-radius: 12px !important;
        color: white !important;
        padding: 10px 15px !important;
    }

    /* Custom Radio */
    input[type="radio"] {
        accent-color: #8b5cf6;
        transform: scale(1.2);
        margin-right: 8px;
    }

    label { color: #94a3b8; font-size: 13px; font-weight: 600; }
</style>

<main class="py-8 px-4">
    <div class="max-w-4xl mx-auto">
        
        <div class="mb-8">
            <h1 class="text-3xl font-black text-white tracking-tighter italic uppercase">Wallpaper App</h1>
            <p class="text-[10px] text-violet-500 font-bold uppercase tracking-[0.4em]">VU FLUX • FUNDO PERSONALIZADO</p>
        </div>

        <div class="flux-card p-8 shadow-2xl">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
                <div>
                    <h3 class="text-white font-bold mb-1">Escolha o Método</h3>
                    <p class="text-xs text-gray-500">Método Atual: <span class="text-violet-400 font-bold"><?php echo $methord; ?></span></p>
                </div>
                
                <div class="flex gap-6 bg-white/5 p-4 rounded-2xl border border-white/5">
                    <label class="flex items-center cursor-pointer text-white hover:text-violet-400 transition-colors">
                        <input type="radio" name="upload-type" id="upload-radio" <?php echo ($uploadmethord == 'by_file' || !$uploadmethord) ? 'checked' : ''; ?>> 
                        Enviar Arquivo
                    </label>
                    <label class="flex items-center cursor-pointer text-white hover:text-violet-400 transition-colors">
                        <input type="radio" name="upload-type" id="url-radio" <?php echo ($uploadmethord == 'by_url') ? 'checked' : ''; ?>> 
                        Usar URL
                    </label>
                </div>
            </div>

            <div class="preview-container">
                <img class="preview-image" src="<?php echo $imageFilex; ?>" alt="Preview FLUX">
            </div>

            <form method="post" enctype="multipart/form-data" id="upload-form" class="space-y-4" style="display: <?php echo ($uploadmethord == 'by_file' || !$uploadmethord) ? 'block' : 'none'; ?>;">
                <div class="p-6 border-2 border-dashed border-white/10 rounded-3xl text-center bg-white/[0.01]">
                    <i class="fas fa-cloud-upload-alt text-3xl text-violet-500 mb-3"></i>
                    <p class="text-xs text-gray-400 mb-4 uppercase tracking-widest">Formatos aceitos: JPG, PNG, WEBP</p>
                    <input class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-black file:bg-violet-600 file:text-white hover:file:bg-violet-700 cursor-pointer" type="file" name="image" id="image" accept="image/*">
                </div>
                <button class="w-full py-4 bg-emerald-500 hover:bg-emerald-600 text-white rounded-2xl text-xs font-black shadow-lg transition-all flex items-center justify-center gap-2" type="submit" name="upload">
                    <i class="fas fa-check"></i> APLICAR NOVO ARQUIVO
                </button>
            </form>

            <form method="post" id="url-form" class="space-y-4" style="display: <?php echo ($uploadmethord == 'by_url') ? 'block' : 'none'; ?>;">
                <div class="form-group">
                    <label class="block mb-2">URL da Imagem</label>
                    <input class="w-full flux-input font-mono text-xs" type="text" name="image-url" id="image-url" placeholder="https://exemplo.com/fundo-flux.jpg" value="<?php echo ($uploadmethord == 'by_url') ? $filenamex : ''; ?>">
                </div>
                <button class="w-full py-4 bg-violet-600 hover:bg-violet-700 text-white rounded-2xl text-xs font-black shadow-lg transition-all flex items-center justify-center gap-2" type="submit" name="url-submit">
                    <i class="fas fa-link"></i> SALVAR URL DO WALLPAPER
                </button>
            </form>

        </div>
    </div>
</main>

<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');

    uploadRadio.addEventListener('change', () => {
        uploadForm.style.display = 'block';
        urlForm.style.display = 'none';
    });

    urlRadio.addEventListener('change', () => {
        uploadForm.style.display = 'none';
        urlForm.style.display = 'block';
    });
</script>

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