<?php

$db = new SQLite3('./api/db/studiolivecode_banner.db');
$table_name = 'banner';
$target_dir = 'banners/';
$file_path = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] !== 'off') ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/' . $target_dir;

// Verifica e cria a pasta banners, se não existir
if (!file_exists($target_dir)) {
    mkdir($target_dir, 0755, true);
}

// Criação das tabelas necessárias
$db->exec("CREATE TABLE IF NOT EXISTS type(id INTEGER PRIMARY KEY AUTOINCREMENT, type INT)");
$db->exec("CREATE TABLE IF NOT EXISTS banner(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, path TEXT)");

// Inicializa a tabela `type` se estiver vazia
$res = $db->query("SELECT COUNT(*) as count FROM type");
$numRowst = $res->fetchArray(SQLITE3_ASSOC);
if ($numRowst['count'] == 0) {
    $db->exec("INSERT INTO type(id, type) VALUES('1', '0')");
}

$rest = $db->query('SELECT * FROM type');
$rowt = $rest->fetchArray();
$id = $rowt['id'];
$type = $rowt['type'];

// Adicionar ou editar banners
if (isset($_GET["create"]) || isset($_GET["edit"])) {
    $edit_id = isset($_GET['edit']) ? intval($_GET['edit']) : null;
    $edit_banner = null;

    if ($edit_id) {
        $result_edit = $db->query('SELECT * FROM banner WHERE id=' . $edit_id);
        $edit_banner = $result_edit->fetchArray(SQLITE3_ASSOC);
    }

    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        $type = $_POST['type'];

        if ($type == '0') { // Upload de arquivo local
            $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
            $uploadOk = 1;
            $extensions = ['gif', 'png', 'jpg', 'jpeg', 'mp4'];

            if ($_FILES['image']['size'] > 5000000) {
                $uploadOk = 0;
                header("Location: banners.php?r=erro_att");
                exit;
            }

            if (!in_array($file_ext, $extensions)) {
                $uploadOk = 0;
                header("Location: banners.php?r=erro_att");
                exit;
            }

            // Renomeia o arquivo com base no próximo ID ou o ID existente
            $new_name = $edit_id ? 'banner' . $edit_id . '.' . $file_ext : 'banner' . (time()) . '.' . $file_ext;
            $target_file = $target_dir . $new_name;

            if ($uploadOk && move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
                $realm_patch = $file_path . $new_name;
                if ($edit_id) {
                    $db->exec("UPDATE banner SET path='$realm_patch' WHERE id=$edit_id");
                } else {
                    $db->exec("INSERT INTO banner(path) VALUES('$realm_patch')");
                }
                header("Location: banners.php?r=adicionado");
                exit;
            } else {
                header("Location: banners.php?r=erro_att");
                exit;
            }
        } else { // URL externa
            $url = $_POST['path'];
            $file_ext = strtolower(pathinfo($url, PATHINFO_EXTENSION));
            $extensions = ['gif', 'png', 'jpg', 'jpeg', 'mp4'];

            if (!in_array($file_ext, $extensions)) {
                header("Location: banners.php?r=erro_att");
                exit;
            } else {
                if ($edit_id) {
                    $db->exec("UPDATE banner SET path='$url' WHERE id=$edit_id");
                } else {
                    $db->exec("INSERT INTO banner(path) VALUES('$url')");
                }
                header("Location: banners.php?r=adicionado");
                exit;
            }
        }
    }

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

    <div class="card radius-10">
        <div class="card-body">
            <h4 class="card-title"><?= $edit_id ? 'Editar' : 'Adicionar'; ?> Banner</h4>
            <form class="forms-sample" method="post" enctype="multipart/form-data">
                <div class="form-group mb-4">
                    <label><strong>Selecione como <?= $edit_id ? 'editar' : 'adicionar'; ?> o banner</strong></label>
                    <select class="form-control type" id="type" name="type">
                        <option value="0" <?= $edit_id && !$edit_banner['path'] ? 'selected' : ''; ?>>Enviar arquivo</option>
                        <option value="1" <?= $edit_id && $edit_banner['path'] ? 'selected' : ''; ?>>Inserir URL</option>
                    </select>
                </div>
                <div class="actived">
                    <div class="form-group mb-4">
                        <label><strong>Selecione o arquivo</strong></label>
                        <input class="form-control" type="file" name="image">
                    </div>
                </div>
                <div class="activeu">
                    <div class="form-group mb-4">
                        <label><strong>Digite a URL do banner</strong></label>
                        <input class="form-control" type="text" name="path" value="<?= $edit_id ? $edit_banner['path'] : ''; ?>">
                    </div>
                </div>
                <button type="submit" class="btn btn-primary"><?= $edit_id ? 'Salvar' : 'Adicionar'; ?></button>
            </form>
        </div>
    </div>
    <script>
        $('.actived').show();
        $('.activeu').hide();

        $('.type').change(function() {
            if ($(this).val() == '0') {
                $('.actived').show();
                $('.activeu').hide();
            } else {
                $('.activeu').show();
                $('.actived').hide();
            }
        });
    </script>
    <?php
    include './includes/footer.php';

} elseif (isset($_GET['delete'])) {
    // Deleta o banner
    $resd = $db->query('SELECT * FROM banner WHERE id=' . $_GET['delete']);
    $rowd = $resd->fetchArray();
    $file_to_delete = $target_dir . basename($rowd['path']);

    if (file_exists($file_to_delete)) {
        unlink($file_to_delete);
    }

    $db->exec('DELETE FROM banner WHERE id=' . $_GET['delete']);
    header("Location: banners.php?r=excluido");
    exit;

} else {
    include './includes/header.php';
    ?>

    <div class="card radius-10">
        <div class="card-body">
            <h4 class="card-title">Gerenciar Banners</h4>
            <a href="?create" class="btn btn-success mb-3">Adicionar Banner</a>
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Banner</th>
                        <th>Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $result = $db->query('SELECT * FROM banner');
                    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
                        ?>
                        <tr>
                            <td><?= $row['id']; ?></td>
                            <td><img src="<?= $row['path']; ?>" width="100"></td>
                            <td>
                                <a href="?edit=<?= $row['id']; ?>" class="btn btn-warning">Editar</a>
                                <a href="?delete=<?= $row['id']; ?>" class="btn btn-danger">Excluir</a>
                            </td>
                        </tr>
                        <?php
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php
    include './includes/footer.php';
}
?>
