<?php
include "includes/header.php";
?>
<style>
  .custom-button {
    padding: 10px 20px;
    margin-top: 10px;
  }
  #url-form {
    display: none;
  }
  .custom-input {
    color: blue;
  }
  .preview-image {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
    margin-top: 15px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  }
  .radio-group {
    margin: 15px 0;
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: center;
  }
  .form-container {
    margin-top: 20px;
  }
  @media (max-width: 768px) {
    .custom-button {
      width: 100%;
      margin-top: 10px;
    }
    .input-group {
      flex-direction: column;
    }
    .input-group input {
      width: 100%;
      margin-bottom: 10px;
    }
  }
</style>
<div class="container-fluid">
    <h1 class="h3 mb-1 text-gray-800">Imagem de Fundo</h1>
    <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-cogs"></i> Escolher Banner</h6>
        </div>
        <div class="card-body">
           <?php
            // CORREÇÃO: Usar arquivo JSON separado para imagem de fundo (não conflitar com a logo)
            $jsonFilex = './a/rtx/background_filenames.json';
            
            // Verificar se o arquivo existe, caso contrário criar com estrutura padrão
            if (!file_exists($jsonFilex)) {
                $defaultData = [["ImageName" => "", "Upload_type" => ""]];
                file_put_contents($jsonFilex, json_encode($defaultData, JSON_PRETTY_PRINT));
            }
            
            $jsonDatax = file_get_contents($jsonFilex);
            $imageDatax = json_decode($jsonDatax, true);
            
            // Garantir que o array tenha pelo menos um índice
            if (!isset($imageDatax[0])) {
                $imageDatax = [["ImageName" => "", "Upload_type" => ""]];
            }
            
            $filenamex = $imageDatax[0]['ImageName'] ?? '';
            $uploadmethord = $imageDatax[0]['Upload_type'] ?? '';
            
            if ($uploadmethord == "by_file") {
                // Se for arquivo, a URL já está absoluta (ou relativa)
                $imageFilex = $filenamex;
                $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 = "";
            }
            
            echo '<h3>Atualmente em uso:' . $methord . '</h3>';
            echo '<div class="radio-group">';
            echo '<label><input type="radio" name="upload-type" id="upload-radio" checked> Definir plano de fundo usando arquivo</label>';
            echo '<label><input type="radio" name="upload-type" id="url-radio"> Definir plano de fundo usando URL</label>';
            echo '</div>';
            echo '<img class="preview-image" src="' . $imageFilex . '" alt="Upload Image">';
            echo '<br><br>';
            
            // Função para gerar URL absoluta
            function getAbsoluteUrl($relativePath) {
                $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
                $domain = $_SERVER['HTTP_HOST'];
                return $protocol . $domain . '/' . ltrim($relativePath, '/');
            }
            
            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/';
                
                if (!file_exists($folderPath)) {
                    mkdir($folderPath, 0777, true);
                }
                
                $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 = 'bg_' . uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
                        $destination = $uploadPath . $fileName;
                        
                        if (move_uploaded_file($fileTemp, $destination)) {
                            // Caminho relativo (acessível publicamente)
                            $relative_path = 'rtx/Img/ADM/' . $fileName;
                            $absolute_url = getAbsoluteUrl($relative_path);
                            
                            // Salvar no JSON específico de fundo
                            $jsonFilePath = './a/rtx/background_filenames.json';
                            $jsonData = json_encode([["ImageName" => $absolute_url, 'Upload_type' => 'by_file']], JSON_PRETTY_PRINT);
                            file_put_contents($jsonFilePath, $jsonData);
                            
                            // Redirecionar para a mesma página (Image.php) em vez de mRTXBGImage.php
                            echo "<script>alert('Imagem de fundo atualizada!'); window.location.href='Image.php';</script>";
                        } else {
                            echo '<div class="alert alert-danger mt-3">Falha ao mover o arquivo.</div>';
                        }
                    } else {
                        echo '<div class="alert alert-danger mt-3">Tipo de arquivo inválido. Apenas JPEG, PNG e GIF são permitidos.</div>';
                    }
                }
            }
            
            if (isset($_POST['url-submit'])) {
                $imageUrl = $_POST['image-url'];
                if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
                    $jsonFilePath = './a/rtx/background_filenames.json';
                    $newImageData = ['ImageName' => $imageUrl, 'Upload_type' => 'by_url'];
                    $jsonData = json_encode([$newImageData], JSON_PRETTY_PRINT);
                    if (file_put_contents($jsonFilePath, $jsonData)) {
                        echo "<script>alert('Imagem de fundo atualizada!'); window.location.href='Image.php';</script>";
                    } else {
                        echo '<div class="alert alert-danger mt-3">Falha ao salvar os dados da imagem no arquivo JSON.</div>';
                    }
                } else {
                    echo '<div class="alert alert-danger mt-3">URL inválida.</div>';
                }
            }
            ?>
            
            <form method="post" enctype="multipart/form-data" id="upload-form" class="form-container">
                <div class="input-group">
                    <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>
                </div>
            </form>
            
            <form method="post" id="url-form" class="form-container">
                <div class="input-group">
                    <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>
                </div>
            </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');
                
                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>