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

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

<div class="card radius-10">
<div class="card-body">

<center>
<h4>Background Atual</h4>
<img src="<?= $fundoUrl ?>?v=<?= time() ?>" style="max-width:80%">
</center>

<form method="post" enctype="multipart/form-data">

<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">
</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.png">
</div>
</div>

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

</form>

</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('.type').change(function(){
    if($(this).val()=="0"){
        $('.actived').show();
        $('.activeu').hide();
    }else{
        $('.activeu').show();
        $('.actived').hide();
    }
});
</script>

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