<?php

$db = new SQLite3('./api/db/3studiolivecode_banner.db');
$table_name = 'banner';
$base_file = basename($_SERVER['SCRIPT_NAME']);
$target_dir = 'banners3/';
$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 type(id INTEGER PRIMARY KEY AUTOINCREMENT, type INT)");

// Check if the 'type' table is empty and insert data if it is
$res = $db->query("SELECT COUNT(*) as count FROM type");
$numRowst = $res->fetchArray(SQLITE3_ASSOC);

if ($numRowst['count'] == 0) {
    $query = "INSERT INTO type(id, type) VALUES('1', '0')";
    $db->exec($query);
}
$rest = $db->query('SELECT * FROM type');
$rowt = $rest->fetchArray();
$id = $rowt['id'];
$type = $rowt['type'];

$db->exec('CREATE TABLE IF NOT EXISTS banner(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, path TEXT)');

if (isset($_GET["create"])) {
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        if ($_POST['type'] == '0') {
            $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: banners3.php?r=erro_att");
                exit;
            }

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

            // Buscar o próximo número disponível para renomear a imagem
            $result = $db->query('SELECT COUNT(*) as total FROM banner');
            $row = $result->fetchArray(SQLITE3_ASSOC);
            $next_id = $row['total'] + 1; // Exemplo: banner1, banner2, etc.
            $new_name = 'banner' . $next_id . '.' . $file_ext;
            $target_file = $target_dir . $new_name;

            if ($uploadOk == 0) {
                header("Location: banners3.php?r=erro_att");
            } else if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
                $realm_patch = $file_path . $new_name;
                $adsimg = $realm_patch;
                $db->exec("INSERT INTO banner(path) VALUES('" . $adsimg . "')");
                $db->close();
                header("Location: banners3.php?r=adicionado");
            }
        } else {
            $url = $_POST['path'];
            $file_ext = strtolower(pathinfo($url, PATHINFO_EXTENSION));
            $extensions = ['gif', 'png', 'jpg', 'jpeg', 'mp4'];

            if (!in_array($file_ext, $extensions)) {
                header("Location: banners3.php?r=erro_att");
            } else {
                // Remover arquivo antigo se for local
                $res = $db->query('SELECT path FROM banner WHERE id = 1');
                $row = $res->fetchArray();
                if (!empty($row['path']) && file_exists($target_dir . basename($row['path']))) {
                    unlink($target_dir . basename($row['path']));
                }

                $adsimg = $url;
                $db->exec("INSERT INTO banner(path) VALUES('" . $adsimg . "')");
                $db->close();
                header("Location: banners3.php?r=adicionado");
            }
        }
    }
    include './includes/header.php';
    ?>
    <div class="card radius-10">
        <div class="card-body">
            <h4 class="card-title">Adicionar Banner</h4>
            <form class="forms-sample" method="post" enctype="multipart/form-data">
                <input type="hidden" class="form-control" name="id" value="<?=$id;?>">
                <div class="form-group mb-4">
                    <label for="url"><strong>Selecione como quer adicionar a imagem Banner</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="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>
                <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="<?=$path;?>" hidden>
                            <input class="form-control" type="text" name="path" value="<?=$path;?>" placeholder="Digite o endereço do arquivo de imagem no formato (.gif ou png ou jpg...)">
                        </div>
                    </div>
                </div>
                <button type="submit" name="submit" class="btn btn-primary mr-2"><i class='bx bx-check mr-1'></i>Adicionar</button>
            </form>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    

    <script>
        $('.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';
} elseif (isset($_GET['update'])) {
    // Formulário de atualização de revenda
    $res = $db->query('SELECT * FROM banner WHERE id=' . $_GET['update']);
    $row = $res->fetchArray();
    $id = $row['id'];
    $path = $row['path'];

    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        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;
            $extensions = ['gif', 'png', 'jpg', 'jpeg', 'mp4'];

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

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

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

            if ($uploadOk == 0) {
                header("Location: banners3.php?r=erro_att");
            } else if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
                $realm_patch = $file_path . $random_name;
                $adsimg = $realm_patch;
                $db->exec("UPDATE banner SET path='$adsimg' WHERE id='$id'");
                $db->close();
                header("Location: banners3.php?r=atualizado");
            }
        } else {
            $url = $_POST['path'];
            $file_ext = strtolower(pathinfo($url, PATHINFO_EXTENSION));
            $extensions = ['gif', 'png', 'jpg', 'jpeg', 'mp4'];

            if (!in_array($file_ext, $extensions)) {
                header("Location: banners3.php?r=erro_att");
            } else {
                // Remove o arquivo antigo se for um arquivo local
                if (!empty($path) && file_exists($target_dir . basename($path))) {
                    unlink($target_dir . basename($path));
                }

                $adsimg = $url;
                $db->exec("UPDATE banner SET path='$adsimg' WHERE id='$id'");
                $db->close();
                header("Location: banners3.php?r=atualizado");
            }
        }
    }
    include './includes/header.php';
    ?>
    <div class="card radius-10">
        <div class="card-body">
            <h4 class="card-title">Editar Banners</h4>
            <form class="forms-sample" method="post" enctype="multipart/form-data">
                <input type="hidden" class="form-control" name="id" value="<?= $id ?>">
                <div class="form-group mb-4">
                    <label for="url"><strong>Selecione como quer adicionar a imagem Banner</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="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>
                <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="<?= $row['path'] ?>" hidden>
                            <input class="form-control" type="text" name="path" value="<?= $row['path'] ?>" placeholder="Digite o endereço do arquivo de imagem no formato (.gif ou png ou jpg...)">
                        </div>
                    </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>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    
    <script>
        $('.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';
} elseif (isset($_GET['delete'])) {
    $resd = $db->query('SELECT * FROM banner WHERE id=' . $_GET['delete']);
    $rowd = $resd->fetchArray();
    $id = $rowd['id'];
    $url = $rowd['path'];
    $file_to_delete = basename(parse_url($url, PHP_URL_PATH));
    $file_to_delete = 'banners3/' . $file_to_delete;

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

    $db->exec('DELETE FROM banner WHERE id=' . $_GET['delete']);
    header("Location: banners3.php?r=excluido");
    exit;
} else {
    // Tabela principal
    include './includes/header.php';
    ?>
    <div class="card radius-10">
        <div class="card-header border-bottom-0 bg-transparent">
            <div class="d-flex align-items-center">
                <div>
                    <?php
                    // Verifica o status atual do tipo
                    $type_query = $db->query("SELECT type FROM type LIMIT 1");
                    $type_row = $type_query->fetchArray();
                    $current_type = $type_row['type'];
                    ?>

                    <!-- Modifique o trecho do HTML onde o switch é criado para usar a variável $current_type -->
                    <label class="switch">
                        <?php if ($current_type == "0") {
                            echo "<input type='checkbox' onchange=\"location.href='ads_type_off.php?id=".$rowt['id']."'\">";
                        } else {
                            echo "<input type='checkbox' checked onchange=\"location.href='ads_type_on.php?id=".$rowt['id']."'\">";
                        }
                        ?>
                        <span class="slider round"></span>
                    </label>
                </div>
                &nbsp;
                <div>
                    <h5 class="font-weight-bold mb-0">Banners Automáticos</h5>
                </div>
                <div class="ms-auto">
                    <a href="banners3.php?create">
                        <button type="button" class="btn btn-white radius-10">Adicionar Banner</button>
                    </a>
                </div>
            </div>
            <br>
            <div class="d-flex align-items-center">
                <div>
                    <h5 class="font-weight-bold mb-0">Banners Cadastrados (1240x480)</h5>
                </div>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table mb-0 align-middle table-sm">
                    <thead>
                    <tr>
                        <th>Imagem</th>
                        <th>Banner URL</th>
                        <th>Editar</th>
                        <th>Apagar</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    $db = new SQLite3("./api/db/studiolivecode_banner.db");
                    $res = $db->query("SELECT * FROM banner");

                    while ($row = $res->fetchArray()) {
                        $id = $row["id"];
                        $path = $row["path"];
                        ?>
                        <tr>
                            <td>
                                <div class="product-img bg-transparent border">
                                    <?php if (strpos($row['path'], '.mp4') !== false) { ?>
                                        <img src="./assets/images/video.jpg" width="100" height="50" class="p-1" alt=""/>
                                    <?php } else if (strpos($row['path'], '.jpg') !== false || strpos($row['path'], '.jpeg') !== false || strpos($row['path'], '.png') !== false || strpos($row['path'], '.gif') !== false) { ?>
                                        <img src="<?=$row['path']?>" width="100" height="50" class="p-1" alt=""/>
                                    <?php }?>
                                </div>
                            </td>
                            <td>
                                <?php
                                if (empty($row['path'])) {
                                    echo 'nenhuma imagem cadastrada';
                                } else {
                                    echo $row['path'];
                                }
                                ?>
                            </td>
                            <td>
                                <div class="d-flex order-actions">
                                    <a href="banners3.php?update=<?= $row['id'] ?>" class="text-light bg-primary border-0"><i class='bx bxs-edit' ></i></a>
                                </div>
                            </td>
                            <td>
                                <div class="d-flex order-actions">
                                    <a class="text-light bg-danger border-0 btn-ok" data-bs-toggle="modal" data-bs-target="#confirm-delete-<?=$row['id']?>"><i class="bx bxs-trash"></i></a></div>
                                <!-- Modal -->
                                <div class="modal fade" id="confirm-delete-<?=$row['id']?>" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="exampleModalLabel">Confirmar</h5>
                                            </div>
                                            <div class="modal-body">Você realmente deseja excluir?</div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Não</button>
                                                <a href="banners3.php?delete=<?=$row['id'] ?>" class="btn btn-danger btn-ok">Sim</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php
                    }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <style>
        /* Estilos para os switches */
        .switch, .switch2 {
            position: relative;
            display: inline-block;
            width: 56px;
            height: 30px;
        }

        .switch input, .switch2 input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        /* Estilos para os sliders */
        .slider, .slider2 {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #dc3545;
            -webkit-transition: .4s;
            transition: .4s;
        }

        .slider, .slider2 {
            background-color: #dc3545;
        }

        /* Estilos para o elemento "before" dos sliders */
        .slider:before, .slider2:before {
            position: absolute;
            content: "";
            height: 22px;
            width: 22px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            -webkit-transition: .4s;
            transition: .4s;
        }

        /* Estilos quando o input está checado */
        input:checked + .slider, input:checked + .slider2 {
            background-color: #198754;
        }

        /* Estilos quando o input está focado */
        input:focus + .slider, input:focus + .slider2 {
            box-shadow: 0 0 1px #198754;
        }

        input:checked + .slider:before, input:checked + .slider2:before{
            -webkit-transform: translateX(26px);
            -ms-transform: translateX(26px);
            transform: translateX(26px);
        }

        /* Estilos adicionais para os sliders redondos */
        .slider.round, .slider2.round {
            border-radius: 34px;
        }

        .slider.round:before, .slider2.round:before {
            border-radius: 50%;
        }
    </style>

    <script>
        // JavaScript code for handling switch input
        $(document).ready(function () {
            $('.toggle-switch input[type="checkbox"]').change(function () {
                var isChecked = $(this).is(':checked');
                var adId = <?php echo $rowt['id']; ?>;
                var statusUrl = (isChecked) ? 'ads_status_on.php' : 'ads_status_off.php';
                $.ajax({
                    url: statusUrl,
                    method: 'POST',
                    data: {
                        ad_id: adId
                    },
                    success: function (response) {
                        console.log(response);
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });
        });
    </script>

    <?php
    include './includes/footer.php';
}

if (isset($_GET["r"])) {
    $result = $_GET["r"];
    switch ($result) {
        case "adicionado":
            echo "<script>
            const Toast = Swal.mixin({
              toast: true,
              position: 'bottom',
              showConfirmButton: false,
              timer: 2000,
            })
            Toast.fire({
              icon: 'success',
              title: 'Banner Adicionado com Sucesso!'
            })</script>";
            break;
        case "excluido":
            echo "<script>
            const Toast = Swal.mixin({
              toast: true,
              position: 'bottom',
              showConfirmButton: false,
              timer: 2000,
            })
            Toast.fire({
              icon: 'success',
              title: 'Banner Excluído com Sucesso!'
            })</script>";
            break;
        case "atualizado":
            echo "<script>
            const Toast = Swal.mixin({
              toast: true,
              position: 'bottom',
              showConfirmButton: false,
              timer: 2000,
            })
            Toast.fire({
              icon: 'success',
              title: 'Banner Atualizado com Sucesso!'
            })</script>";
            break;
        case "type_on":
            echo "<script>
            const Toast = Swal.mixin({
                toast: true,
                position: 'bottom',
                showConfirmButton: false,
                timer: 2000,
            })
            Toast.fire({
                icon: 'success',
                title: 'Banners Automáticos Desativados!'
            })</script>";
            break;
        case "type_off":
            echo "<script>
            const Toast = Swal.mixin({
                toast: true,
                position: 'bottom',
                showConfirmButton: false,
                timer: 2000,
            })
            Toast.fire({
                icon: 'success',
                title: 'Banners Automáticos Ativados!'
            })</script>";
            break;
    }
}
?>