<?php 

//db call
$db = new SQLite3("./api/db/studiolivecode_imagens.db");

//table name
$table_name = "logo";

//current file var
$base_file = basename($_SERVER['SCRIPT_NAME']);
$target_dir = 'banners/';
$file_path = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] !== 'off') ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/' . $target_dir;

if (!file_exists($target_dir)) {
    mkdir($target_dir, 511, true);
}

$db->exec('CREATE TABLE IF NOT EXISTS logo(id INT PRIMARY KEY NOT NULL, path TEXT)');
$rows = $db->query('SELECT COUNT(*) as count FROM logo');
$numRows = $rows->fetchArray(SQLITE3_ASSOC);

if ($numRows['count'] == 0) {
    $queries = [
        "INSERT INTO logo(id, path) VALUES('1', '')"
    ];

    foreach ($queries as $query) {
        $db->exec($query);
    }
}

$res = $db->query("SELECT * FROM " . $table_name . " WHERE id='1'");
$row = $res->fetchArray();
$logo = $row["path"];

if (isset($_POST['submit'])) {
    if ($_POST['type'] == '0') {
        $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        $random_name = bin2hex(random_bytes(9)) . '.' . $file_ext; // Generate random name with 18 characters
        $target_file = $target_dir . $random_name;
        $uploadOk = 1;
        $allowed_extensions = ['gif', 'png', 'jpg', 'jpeg', 'mp4'];

        // Verifica se a extensão do arquivo é permitida
        if (!in_array($file_ext, $allowed_extensions)) {
            header("Location: logo.php?r=erro_att");
            exit();
        }

        // Remove o arquivo antigo se existir
        if (!empty($logo) && file_exists($target_dir . basename($logo))) {
            unlink($target_dir . basename($logo));
        }

        // Move o arquivo e atualiza o banco de dados...
        if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
            $adsimg = $file_path . $random_name;
            $db->exec("UPDATE logo SET path='" . $adsimg . "' WHERE id='1'");
            $db->close();
            header("Location: logo.php?r=atualizado");
            exit();
        } else {
            header("Location: logo.php?r=erro_att");
            exit();
        }
    } else {
        $url = $_POST['path'];
        $file_ext = strtolower(pathinfo($url, PATHINFO_EXTENSION));
        $allowed_extensions = ['gif', 'png', 'jpg', 'jpeg', 'mp4'];

        // Verifica se a extensão do arquivo é permitida
        if (!in_array($file_ext, $allowed_extensions)) {
            header("Location: logo.php?r=erro_att");
            exit();
        }

        // Remove o arquivo antigo se for um arquivo local
        if (!empty($logo) && file_exists($target_dir . basename($logo))) {
            unlink($target_dir . basename($logo));
        }

        // Atualiza o banco de dados...
        $db->exec("UPDATE logo SET path='" . $_POST["path"] . "' WHERE id='1'");
        $db->close();
        header("Location: logo.php?r=atualizado");
        exit();
    }
}

?>

<?php include './includes/header.php';?>
<div class="card radius-10">
        <div class="card-body">
         <center><h4 class="card-title">Logo Atual:</h4>
                        <img class="preview-image" src="<?php
                                    if (empty($logo)) {
                                        echo 'assets/images/logo1.png';
                                    } else {
                                        echo $logo;
                                    } ?>" alt="Uploaded Image" width="50%" height="auto"></center>
         <form class="forms-sample" method="post" enctype="multipart/form-data">
                <div class="form-group mb-4">
                    <label for="url"><strong>Selecione como quer adicionar a imagem Logo</strong></label>
                    <div class="form-group mb-4">
                        <select class="form-control type" id="type" name="type">
                            <option data-value="op0" value="0" selected>Enviar o arquivo de imagem</option>
                            <option data-value="op1" value="1">Digitar URL externa da imagem</option>
                        </select>
                    </div>
                </div>

                <div class="activeu">
                    <div class="form-group mb-4">
                        <label class="control-label"><strong>Digite o endereço da imagem</strong></label>
                        <div class="form-group mb-4">
                            <input class="form-control" type="hidden" name="del" value="<?php echo $logo ?>" hidden>
                            <input class="form-control" type="text" name="path" value="<?php echo $logo ?>" placeholder="Digite o endereço do arquivo de imagem no formato (.gif, .png ou .jpg)">
                        </div>
                    </div>
                </div>

                <div class="actived">
                    <div class="form-group mb-4">
                        <label class="form-label"><strong>Selecione o arquivo para envio</strong></label>
                        <input class="form-control" type="file" name="image" id="intro" placeholder="Escolher Imagem" onchange="uploadintro(this)" aria-describedby="intro">
                    </div>
                </div>
                <button type="submit" name="submit" class="btn btn-primary mr-2"><i class='bx bx-check mr-1'></i>Editar</button>
            </form>
        </div>
    </div>
</div>

<?php
if (isset($_GET["r"])) {
    $result = $_GET["r"];
    switch ($result) {
        case "atualizado":
            echo "<script>
            const Toast = Swal.mixin({
                toast: true,
                position: 'bottom',
                showConfirmButton: false,
                timer: 2000,
            })
            Toast.fire({
                icon: 'success',
                title: 'Logo Atualizada com Sucesso!'
            })</script>";
            break;
        case "erro_att":
            echo "<script>
            const Toast = Swal.mixin({
                toast: true,
                position: 'bottom',
                showConfirmButton: false,
                timer: 2000,
            })
            Toast.fire({
                icon: 'success',
                title: 'Erro ao atualizar a Logo!'
            })</script>";
            break;
    }
}
?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
//hide activecode form
      $('.actived').show(); 
      $('.activeu').hide(); 

//Show/hide activecode select
$(document).ready(function(){
  $('.type').change(function(){
    if($('.type').val() < 1) {
      $('.actived').show(); 
      $('.activeu').hide(); 
    }else {
      $('.activeu').show();
      $('.actived').hide();
    } 
  });
});
</script>
<?php include './includes/footer.php';?>