<?php
// Ativa buffer e inicia sessão antes de qualquer saída
ob_start();
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Conexão com banco SQLite
$db = new SQLite3("./api/db/studiolivecode_imagens.db");
$table_name = "logo";

// Diretório de upload e URL base
$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, 0777, true);
}

// Cria tabela se não existir
$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) {
    $db->exec("INSERT INTO logo(id, path) VALUES('1', '')");
}

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

// Upload ou URL externa
if (isset($_POST['submit'])) {
    if ($_POST['type'] == '0') {
        // Upload de arquivo
        $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        $random_name = bin2hex(random_bytes(9)) . '.' . $file_ext;
        $target_file = $target_dir . $random_name;
        $allowed_extensions = ['gif', 'png', 'jpg', 'jpeg', 'mp4'];

        if (!in_array($file_ext, $allowed_extensions)) {
            header("Location: logo.php?r=erro_att");
            exit();
        }

        if (!empty($logo) && file_exists($target_dir . basename($logo))) {
            unlink($target_dir . basename($logo));
        }

        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 externa
        $url = $_POST['path'];
        $file_ext = strtolower(pathinfo($url, PATHINFO_EXTENSION));
        $allowed_extensions = ['gif', 'png', 'jpg', 'jpeg', 'mp4'];

        if (!in_array($file_ext, $allowed_extensions)) {
            header("Location: logo.php?r=erro_att");
            exit();
        }

        if (!empty($logo) && file_exists($target_dir . basename($logo))) {
            unlink($target_dir . basename($logo));
        }

        $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 echo empty($logo) ? 'assets/images/logo1.png' : $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>

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
// Controle de exibição dos campos
$('.actived').show(); 
$('.activeu').hide(); 

$(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'; ?>
<?php ob_end_flush(); ?>
