<?php
$logoPath = dirname(__DIR__) . "/api/img/logo.png";
$logoUrl  = "api/img/logo.png";

if (isset($_GET["app_image"])) {
    if (!is_file($logoPath)) {
        http_response_code(404);
        exit;
    }

    $ext = strtolower(pathinfo($logoPath, PATHINFO_EXTENSION));
    $mime = "image/png";
    if ($ext === "jpg" || $ext === "jpeg") {
        $mime = "image/jpeg";
    } elseif ($ext === "webp") {
        $mime = "image/webp";
    } elseif ($ext === "gif") {
        $mime = "image/gif";
    }

    header("Content-Type: " . $mime);
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    readfile($logoPath);
    exit;
}

if (!is_dir(dirname($logoPath))) {
    mkdir(dirname($logoPath), 0755, true);
}

if (isset($_POST["submit"])) {
    $type = isset($_POST["type"]) ? (string)$_POST["type"] : "0";

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

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

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

        if (!move_uploaded_file($_FILES["image"]["tmp_name"], $logoPath)) {
            header("Location: logo.php?r=erro");
            exit;
        }

        header("Location: logo.php?r=ok");
        exit;
    }

    if ($type === "1") {
        $url = trim($_POST["path"] ?? "");
        if ($url === "" || !filter_var($url, FILTER_VALIDATE_URL)) {
            header("Location: logo.php?r=erro");
            exit;
        }

        $urlPath = parse_url($url, PHP_URL_PATH);
        $ext = strtolower(pathinfo($urlPath ?: "", PATHINFO_EXTENSION));
        $allowed = ["png", "jpg", "jpeg", "gif", "webp"];

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

        $context = stream_context_create([
            "http" => [
                "timeout" => 20,
                "follow_location" => 1,
                "user_agent" => "Mozilla/5.0"
            ],
            "https" => [
                "timeout" => 20,
                "follow_location" => 1,
                "user_agent" => "Mozilla/5.0"
            ]
        ]);

        $img = @file_get_contents($url, false, $context);
        if ($img === false || strlen($img) < 10) {
            header("Location: logo.php?r=erro");
            exit;
        }

        if (@file_put_contents($logoPath, $img) === false) {
            header("Location: logo.php?r=erro");
            exit;
        }

        header("Location: logo.php?r=ok");
        exit;
    }

    header("Location: logo.php?r=erro");
    exit;
}

include "./includes/header.php";
?>
<style>
/* SCROLLBAR CINZA - PC E MOBILE */
html{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

body{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

*::-webkit-scrollbar{
  width: 10px;
  height: 10px;
}

*::-webkit-scrollbar-track{
  background: #1f1f1f;
  border-radius: 999px;
}

*::-webkit-scrollbar-thumb{
  background: linear-gradient(180deg, #b8b8b8, #7c7c7c);
  border-radius: 999px;
  border: 2px solid #1f1f1f;
}

*::-webkit-scrollbar-thumb:hover{
  background: linear-gradient(180deg, #d0d0d0, #909090);
}

.table-responsive{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

@media (max-width: 768px){
  *::-webkit-scrollbar{
    width: 7px;
    height: 7px;
  }
}
</style>

<div class="card radius-10">
    <div class="card-body">
        <center>
            <h4>Logo Atual</h4>
            <?php if (is_file($logoPath)) { ?>
                <img src="<?= htmlspecialchars($logoUrl, ENT_QUOTES, "UTF-8") ?>?v=<?= time() ?>" style="max-width:300px">
            <?php } else { ?>
                <p>Nenhuma logo cadastrada.</p>
            <?php } ?>
        </center>

        <form method="post" enctype="multipart/form-data" class="mt-4">
            <div class="form-group mb-3">
                <label>Como deseja enviar</label>
                <select name="type" class="form-control type">
                    <option value="0">Enviar arquivo</option>
                    <option value="1">Usar URL</option>
                </select>
            </div>

            <div class="actived">
                <div class="form-group mb-3">
                    <label>Arquivo</label>
                    <input type="file" name="image" class="form-control" accept=".png,.jpg,.jpeg,.gif,.webp">
                </div>
            </div>

            <div class="activeu" style="display:none">
                <div class="form-group mb-3">
                    <label>URL da imagem</label>
                    <input type="text" name="path" class="form-control" placeholder="https://site/logo.png">
                </div>
            </div>

            <button type="submit" class="btn btn-primary" name="submit">Salvar</button>
        </form>
    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const select = document.querySelector(".type");
    const arquivo = document.querySelector(".actived");
    const url = document.querySelector(".activeu");

    function atualizarTipo() {
        if (!select || !arquivo || !url) return;
        if (select.value === "0") {
            arquivo.style.display = "";
            url.style.display = "none";
        } else {
            arquivo.style.display = "none";
            url.style.display = "";
        }
    }

    if (select) {
        select.addEventListener("change", atualizarTipo);
        atualizarTipo();
    }
});
</script>

<?php
if (isset($_GET["r"])) {
    if ($_GET["r"] === "ok") {
        echo "<script>Swal.fire('Logo atualizada','','success')</script>";
    }
    if ($_GET["r"] === "erro") {
        echo "<script>Swal.fire('Erro ao salvar logo','','error')</script>";
    }
}
include "./includes/footer.php";
?>
