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

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

    $ext = strtolower(pathinfo($fundoPath, PATHINFO_EXTENSION));
    $mime = "image/jpeg";
    if ($ext === "png") {
        $mime = "image/png";
    } 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($fundoPath);
    exit;
}

if (!is_dir(dirname($fundoPath))) {
    mkdir(dirname($fundoPath), 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: login_fundo.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: login_fundo.php?r=erro");
            exit;
        }

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

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

    if ($type === "1") {
        $url = trim($_POST["path"] ?? "");
        if ($url === "" || !filter_var($url, FILTER_VALIDATE_URL)) {
            header("Location: login_fundo.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: login_fundo.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: login_fundo.php?r=erro");
            exit;
        }

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

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

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

include "./includes/header.php";
?>

<div class="card radius-10">
    <div class="card-body">
        <center>
            <h4>Fundo atual do login</h4>
            <?php if (is_file($fundoPath)) { ?>
                <img src="<?= htmlspecialchars($fundoUrl, ENT_QUOTES, "UTF-8") ?>?v=<?= time() ?>" style="max-width:80%;border-radius:12px;box-shadow:0 10px 30px rgba(0,0,0,.15)">
            <?php } else { ?>
                <p>Nenhum fundo cadastrado.</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/fundo_login.jpg">
                </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('Fundo do login atualizado','','success')</script>";
    }
    if ($_GET["r"] === "erro") {
        echo "<script>Swal.fire('Erro ao salvar fundo do login','','error')</script>";
    }
}
include "./includes/footer.php";
?>
