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

<style>
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Poppins:wght@300;400;600&display=swap');

:root{
  --neon-cyan: #00f2ff;
  --neon-purple: #bc13fe;
  --neon-pink: #ff2bd6;
  --neon-gold: #ffcc00;
  --dark-bg: #050a0e;

  --glass-bg: rgba(255,255,255,0.02);
  --glass-border: rgba(0,242,255,0.16);
  --txt: rgba(255,255,255,0.92);
  --muted: rgba(255,255,255,0.65);
}

/* Blindagem total contra fundo branco */
html, body, #wrapper, #content-wrapper, #content, .container-fluid, .bg-white{
  background-color: var(--dark-bg) !important;
  color: #e0e0e0 !important;
  font-family:'Poppins',sans-serif;
}

/* Título estilo do modelo */
.h3{
  font-family:'Orbitron',sans-serif;
  color:#fff !important;
  text-transform:uppercase;
  letter-spacing:2px;
  text-shadow:0 0 10px rgba(0,242,255,0.22);
}

/* Card Glass (mesmo “peso” do modelo) */
.card-futuristic{
  background: var(--glass-bg) !important;
  backdrop-filter: blur(15px);
  -webkit-backdrop-filter: blur(15px);
  border: 1px solid var(--glass-border) !important;
  border-radius: 15px !important;
  box-shadow: 0 10px 30px rgba(0,0,0,0.55);
  overflow:hidden;
}

.card-header-futuristic{
  background: rgba(0,242,255,0.03) !important;
  border-bottom: 1px solid var(--glass-border) !important;
  padding: 1.5rem !important;
}

.card-header-futuristic h6{
  font-family:'Orbitron',sans-serif;
  color: var(--neon-cyan) !important;
  text-shadow: 0 0 10px rgba(0,242,255,0.25);
  margin:0;
  text-transform:uppercase;
}

/* Bloco do “Atualmente em uso” igual ao modelo */
.current-use{
  font-family:'Orbitron',sans-serif;
  font-size: 1rem;
  margin: 0 0 18px 0;
}
.current-use span{
  color: var(--neon-gold);
  text-shadow: 0 0 10px rgba(255,204,0,0.22);
}

/* Radios igual ao modelo */
input[type="radio"]{
  accent-color: var(--neon-cyan);
  cursor:pointer;
}

.preview-container{
  border: 2px solid var(--glass-border);
  border-radius: 12px;
  overflow: hidden;
  margin: 20px 0;
  background: #000;
  box-shadow: 0 0 20px rgba(0,242,255,0.10);

  /* 👇 AQUI: o container “abraça” o tamanho do logo */
  display: inline-flex;
  width: fit-content;
  max-width: 100%;
}

.preview-image{
  display: block;

  /* 👇 AQUI: não força 100% de largura */
  width: auto;
  max-width: 100%;

  /* 👇 Mantém limite de altura igual ao padrão */
  height: auto;
  max-height: 300px;
}

/* PADRONIZAÇÃO DOS CAMPOS (igual ao modelo) */
.input-group-custom{
  display:flex;
  align-items:center;
  gap: 15px;
  width: 100%;
  max-width: 800px; /* igual ao modelo */
}

.form-control-futuristic{
  background: rgba(0,0,0,0.5) !important;
  border: 1px solid rgba(255,255,255,0.14) !important;
  color:#fff !important;
  border-radius:8px !important;
  padding:12px;
  height:50px; /* igual ao modelo */
  flex-grow:1;
  transition:.3s;
}
.form-control-futuristic:focus{
  border-color: var(--neon-cyan) !important;
  box-shadow: 0 0 15px rgba(0,242,255,0.18) !important;
  outline:none;
}

/* Botão no estilo do modelo, mas com nossas cores */
.btn-neon{
  background: transparent !important;
  border: 1px solid var(--neon-cyan) !important;
  color: var(--neon-cyan) !important;
  font-family:'Orbitron',sans-serif;
  text-transform:uppercase;
  height:50px; /* igual ao modelo */
  padding: 0 30px;
  border-radius:8px;
  transition:.4s;
  cursor:pointer;
  display:flex;
  align-items:center;
  justify-content:center;
  min-width:160px; /* igual ao modelo */
  font-size:.8rem;
}
.btn-neon:hover{
  background: var(--neon-cyan) !important;
  color:#000 !important;
  box-shadow: 0 0 20px rgba(0,242,255,0.35);
}

label{
  font-weight:600;
  color: var(--neon-cyan);
  margin-bottom: 10px;
  display:block;
  font-size:.85rem;
  text-transform:uppercase;
}

#url-form{ display:none; }
</style>

<div class="container-fluid pt-4 px-5">
  <h1 class="h3 mb-4"><i class="fas fa-signature mr-2"></i> Alterar logotipo</h1>

  <div class="card card-futuristic shadow mb-4">
    <div class="card-header-futuristic">
      <h6><i class="fa fa-cogs mr-2"></i> Escolher Logo</h6>
    </div>

    <div class="card-body p-4">
      <?php
      $jsonFilex = "../a/rtx/logo_filenames_$seller_name.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 = " Enviar da Minha Galeria";
      } elseif ($uploadmethord == "by_url") {
          $imageFilex = "$filenamex";
          $methord = " Enviar Via URL";
      } else {
          $imageFilex = "https://c4.wallpaperflare.com/wallpaper/159/71/731/errors-minimalism-typography-red-wallpaper-preview.jpg";
          $methord = " Não Definido";
      }

      echo '<h4 class="current-use mb-4">Atualmente em uso: <span>' . $methord . '</span></h4>';

      echo '<div class="mb-4">';
      echo '<input type="radio" name="upload-type" id="upload-radio" checked> Definir logotipo usando arquivo &nbsp;&nbsp;';
      echo '<input type="radio" name="upload-type" id="url-radio"> Definir logotipo usando URL';
      echo '</div>';

      echo '<div class="preview-container">';
      if($uploadmethord == "by_file" ) {
          echo '<img class="preview-image" src="../' . $imageFilex . '" alt="Preview">';
      } else {
          echo '<img class="preview-image" src="'.$imageFilex . '" alt="Preview">';
      }
      echo '</div>';

      // --- LÓGICA PHP ORIGINAL (intocada) ---
      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/logo/$seller_name/";
          if (!file_exists($folderPath)) {
              if (mkdir($folderPath, 0777, true)) {
              } else {
                  echo 'Erro ao criar a pasta.';
              }
          }
          $files = scandir($folderPath);
          foreach ($files as $file) {
              if ($file !== '.' && $file !== '..') {
                  if (!in_array($file, $selectedFiles)) {
                      unlink($folderPath . $file);
                  }
              }
          }
          if (isset($_FILES['image'])) {
              $file = $_FILES['image'];
              $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
              if (in_array($file['type'], $allowedTypes)) {
                  $fileName = uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
                  if (move_uploaded_file($file['tmp_name'], $folderPath . $fileName)) {
                      $jsonFilePath = "../a/rtx/logo_filenames_$seller_name.json";
                      $jsonData = json_encode([["ImageName" => "../rtx/logo/$seller_name/" . $fileName, 'Upload_type' => 'by_file']]);
                      file_put_contents($jsonFilePath, $jsonData);
                      echo "<script>window.location.href='mRTXBGlogo.php';</script>";
                  }
              }
          }
      }

      if (isset($_POST['url-submit'])) {
            $imageUrl = $_POST['image-url'];

            if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {

                // ✅ caminho correto (igual ao resto do arquivo)
                $jsonFilePath = "../a/rtx/logo_filenames_$seller_name.json";

                // se o arquivo não existir, cria uma estrutura padrão
                if (!file_exists($jsonFilePath)) {
                    $imageData = [["ImageName" => $imageUrl, "Upload_type" => "by_url"]];
                } else {
                    $jsonData = file_get_contents($jsonFilePath);
                    $imageData = json_decode($jsonData, true);

                    // se vier vazio ou inválido, recria
                    if (!is_array($imageData) || !isset($imageData[0])) {
                        $imageData = [["ImageName" => $imageUrl, "Upload_type" => "by_url"]];
                    } else {
                        $imageData[0] = ["ImageName" => $imageUrl, "Upload_type" => "by_url"];
                    }
                }

                $jsonData = json_encode($imageData);

                if (file_put_contents($jsonFilePath, $jsonData)) {
                    echo "<script>window.location.href='mRTXBGlogo.php';</script>";
                    exit;
                } else {
                    echo 'Failed to save the image data to the JSON file.';
                }

            } else {
                echo 'Invalid URL.';
            }
        }

      ?>

      <div class="mt-4">
        <form method="post" enctype="multipart/form-data" id="upload-form">
          <label for="image">Selecione o arquivo de logo:</label>
          <div class="input-group-custom">
            <input class="form-control-futuristic" type="file" name="image" id="image" accept="image/jpeg, image/png, image/gif">
            <button class="btn-neon" type="submit" name="upload"><i class="fas fa-upload mr-2"></i> Enviar</button>
          </div>
        </form>

        <form method="post" id="url-form">
          <label for="image-url">Insira o link da logo:</label>
          <div class="input-group-custom">
            <input class="form-control-futuristic" type="text" name="image-url" id="image-url" placeholder="https://exemplo.com/logo.png">
            <button class="btn-neon" type="submit" name="url-submit"><i class="fas fa-link mr-2"></i> Salvar URL</button>
          </div>
        </form>
      </div>

      <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/footer3.php"; ?>
</body>
</html>
