<?php
$fundoPath = dirname(__DIR__) . "/api/img/fundo.png";
$fundoUrl  = "api/img/fundo.png";

if(isset($_POST["submit"])){

    if($_POST["type"] == "0"){

        if(!isset($_FILES["image"]) || $_FILES["image"]["error"] != 0){
            header("Location: bg.php?r=erro");
            exit;
        }

        $ext = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
        $allowed = ["png","jpg","jpeg","gif"];

        if(!in_array($ext,$allowed)){
            header("Location: bg.php?r=erro");
            exit;
        }

        move_uploaded_file($_FILES["image"]["tmp_name"], $fundoPath);
        header("Location: bg.php?r=ok");
        exit;
    }

    if($_POST["type"] == "1"){
        $url = trim($_POST["path"]);
        if($url==""){
            header("Location: bg.php?r=erro");
            exit;
        }

        $ext = strtolower(pathinfo($url, PATHINFO_EXTENSION));
        $allowed = ["png","jpg","jpeg","gif"];

        if(!in_array($ext,$allowed)){
            header("Location: bg.php?r=erro");
            exit;
        }

        $img = @file_get_contents($url);
        if($img === false){
            header("Location: bg.php?r=erro");
            exit;
        }

        file_put_contents($fundoPath, $img);
        header("Location: bg.php?r=ok");
        exit;
    }
}

require_once __DIR__ . '/../includes/header.php';
?>

<div class="card">
  <div class="card-header d-flex align-items-center justify-content-between flex-wrap gap-3">
    <div class="d-flex align-items-center gap-3">
      <span class="topbar-page-icon"><i class="bx bx-image"></i></span>
      <div><h4 class="mb-1">Imagem de fundo</h4><p class="text-muted mb-0">Envie um arquivo ou informe uma URL para atualizar o fundo do aplicativo.</p></div>
    </div>
    <span class="badge bg-primary"><i class="bx bx-image-alt"></i> Pré-visualização</span>
  </div>
  <div class="card-body">
    <div class="preview-frame mb-4"><img src="<?= htmlspecialchars($fundoUrl, ENT_QUOTES, 'UTF-8') ?>?v=<?= time() ?>" alt="Imagem de fundo atual"></div>
    <form method="post" enctype="multipart/form-data">
      <div class="mb-3">
        <label class="form-label" for="backgroundType">Como deseja enviar?</label>
        <select name="type" id="backgroundType" class="form-select type">
          <option value="0">Enviar arquivo do dispositivo</option>
          <option value="1">Usar endereço de uma imagem</option>
        </select>
      </div>
      <div class="actived mb-3"><label class="form-label" for="backgroundFile">Arquivo da imagem</label><input type="file" id="backgroundFile" name="image" class="form-control" accept="image/png,image/jpeg,image/gif"></div>
      <div class="activeu mb-3" hidden><label class="form-label" for="backgroundUrl">URL da imagem</label><input type="url" id="backgroundUrl" name="path" class="form-control" placeholder="https://site.com/fundo.png"></div>
      <div class="d-flex justify-content-end"><button class="btn btn-primary" name="submit" type="submit"><i class="bx bx-cloud-upload"></i> Atualizar imagem</button></div>
    </form>
  </div>
</div>
<?php if (isset($_GET['r'])): ?>
<div id="backgroundAlert" hidden data-status="<?= $_GET['r'] === 'ok' ? 'success' : 'error' ?>" data-title="<?= htmlspecialchars($_GET['r'] === 'ok' ? 'Imagem atualizada' : 'Erro ao salvar a imagem', ENT_QUOTES, 'UTF-8') ?>"></div>
<?php endif; ?>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
