<?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";
?>

<style>
.dns-wrap{
    width:100%;
    max-width:none;
    margin:0;
    padding:0 18px;
}
.dns-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
    margin-bottom:18px;
}
.dns-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:18px 22px;
}
.dns-title{
    display:flex;
    align-items:center;
    gap:14px;
}
.dns-title .ic{
    width:44px;
    height:44px;
    min-width:44px;
    border-radius:14px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    display:flex;
    align-items:center;
    justify-content:center;
}
.dns-title .ic i{
    font-size:24px;
    color:#198754;
}
.dns-title h5{
    margin:0;
    font-weight:900;
}
.dns-title span{
    display:block;
    margin-top:3px;
    font-size:13px;
    color:rgba(255,255,255,.55);
}
.badge-soft{
    display:inline-flex;
    align-items:center;
    gap:7px;
    padding:8px 12px;
    border-radius:999px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    color:#198754;
    font-weight:900;
    white-space:nowrap;
}
.input-radius{
    border-radius:14px !important;
    min-height:48px;
}
.textarea-radius{
    border-radius:14px !important;
}
.save-btn{
    border-radius:14px;
    height:46px;
    font-weight:900;
    padding-left:22px;
    padding-right:22px;
}
.table-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
}
.table thead th{
    font-weight:900;
    white-space:nowrap;
}
.table td{
    vertical-align:middle;
}
.action-btn{
    border-radius:12px;
    font-weight:800;
    margin:2px 0;
}
.img-link{
    font-weight:900;
    text-decoration:none;
}
.status-on{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:999px;
    padding:5px 10px;
    background:rgba(25,135,84,.12);
    color:#198754;
    font-weight:900;
}
.status-off{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:999px;
    padding:5px 10px;
    background:rgba(220,53,69,.12);
    color:#dc3545;
    font-weight:900;
}
@media(max-width:575px){
    .dns-wrap{
        padding:0 8px;
    }
    .dns-header{
        align-items:flex-start;
        padding:16px;
    }
    .dns-title .ic{
        width:40px;
        height:40px;
        min-width:40px;
    }
    .dns-title .ic i{
        font-size:22px;
    }
    .dns-title h5{
        font-size:18px;
    }
    .badge-soft{
        padding:7px 10px;
        font-size:12px;
    }
    .save-btn{
        width:100%;
    }
}

/* 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>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";
?>
