<?php
ini_set("display_errors", 0);
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.

$db = new SQLite3('./api/.db.db');
$table_name = 'ads';
$base_file = basename($_SERVER['SCRIPT_NAME']);


if (isset($_GET["create"])) {
     // Tabela principal
     ini_set("display_errors", 1);
    include './includes/header.php';
       echo "            <div class=\"col-md-8 mx-auto\">\n                <center>\n\t\t        <h1 class=\"colorboard\"></i></h1>\n\t            </center>\n\t\t\t\t<div class=\"card\">\n\t\t\t\t\t<div class=\"card-header\">\n\t\t\t\t\t\t<center>\n\t\t\t\t\t\t\t<h2><i class=\"fa fa-eye\"></i> Adicionar anúncios</h2>\n\t\t\t\t\t\t</center>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"card-body\">\n        \t\t\t\t<form method=\"post\" enctype=\"multipart/form-data\">\n                            <div class=\"form-group\">\n                              <input class=\"form-control\" type=\"text\" name=\"title\">\n                              <label>Nome</label>\n                            </div>\n                            <div class=\"form-group\">\n                              <input class=\"form-control\" type=\"file\" name=\"image\">\n                              <label>Imagem ( GIF, PNG, JPG, SVG )</label>\n                            </div>  \n                            <div class=\"col-12\"> <button type=\"submit\" name=\"submit\" class=\"btn btn-info \">Enviar</button> </div>\n                          </form>\n\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\n";
    
   if (isset($_POST["submit"])) {
    // Verifica se um arquivo foi enviado corretamente
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $target_dir = "img/"; // Diretório correto para salvar a imagem
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true); // Cria a pasta caso não exista
        }

        $file_name = basename($_FILES["image"]["name"]);
        $target_file = $target_dir . $file_name;
        $image_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        // Extensões permitidas
        $valid_types = array("gif", "png", "jpg", "jpeg", "svg");
        if (in_array($image_type, $valid_types)) {
            // Move a imagem para o diretório
            if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
                // URL completa da imagem salva
                $image_url = $domain . "/" . $target_file;

                // Insere a URL no banco de dados
                $adb->exec("INSERT INTO " . $table_name . "(title, url) VALUES('" . $_POST["title"] . "', '" . $image_url . "')");

                echo "<script>window.location.href='ads.php';</script>";
                exit;
            } else {
                echo "Erro ao salvar a imagem.";
            }
        } else {
            echo "Formato de imagem inválido. Apenas GIF, PNG, JPG, JPEG e SVG são permitidos.";
        }
    } else {
        echo "Nenhuma imagem foi enviada ou ocorreu um erro.";
    }
}

    
    ?>
 
    <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';
    } else {
    // Tabela principal
    include './includes/header.php';
    
        $resU = @$adb->query("SELECT * FROM " . $table_name . " WHERE id='" . $_GET["update"] . "'");
      $rowU = @$resU->fetchArray();


    if (isset($_POST["submitU"])) {
        echo "<script>console.log('oi');</script>";
        // Atualiza o título e a URL do anúncio
        $adb->exec("UPDATE " . $table_name . " SET title='" . $_POST["title"] . "',url='" . $_POST["url"] . "' WHERE id='" . $_POST["id"] . "'");
        $adb->close();
        echo "<script>window.location.href='ads.php';</script>";
        exit;
    }
     
    if (isset($_GET["delete"])) {
        // A função delete agora usa o parâmetro GET corretamente
        $id_to_delete = intval($_GET["delete"]); // Protege contra injeção de SQL
        
        // Recupera o URL da imagem antes de excluir o registro
        $resDel = $adb->query("SELECT url FROM " . $table_name . " WHERE id=" . $id_to_delete);
        $rowDel = $resDel->fetchArray();
if ($rowDel && isset($rowDel['url'])) {
    $image_path = str_replace($domain . "/", "", $rowDel['url']);
} else {
    $image_path = null; // Ou uma mensagem de erro para depuração
}
    
        // Exclui a imagem da pasta img, se existir
        if (file_exists($image_path)) {
            unlink($image_path); // Exclui a imagem
        }
        
        // Exclui o registro do banco de dados
        $adb->exec("DELETE FROM " . $table_name . " WHERE id=" . $id_to_delete);
        echo "<script>window.location.href='ads.php';</script>";
        exit;
    }
    
  
if (isset($_GET["update"])) {
    echo "
    <div class=\"card\">
       
        <div class=\"card-title\" style=\"border:none;\">
            <div class=\"card-header\">
                <center>
                    <h2><i class=\"fa fa-file-image-o\"></i> Editar Ad</h2>
                </center>
            </div>
            <div class=\"card-body\">
                <form method=\"post\" enctype=\"multipart/form-data\">
                    <input type=\"hidden\" class=\"form-control\" name=\"id\" value=\"" . htmlspecialchars($_GET["update"]) . "\">
                    
                    <div class=\"form-group\">
                        <label for=\"title\">Título</label>
                        <input type=\"text\" id=\"title\" name=\"title\" class=\"form-control\" value=\"" . htmlspecialchars($rowU["title"]) . "\">
                    </div>
                    
                    <div class=\"form-group\">
                        <label for=\"url\">URL da Imagem (GIF, PNG, JPG, SVG)</label>
                        <input type=\"text\" id=\"url\" class=\"form-control\" name=\"url\" value=\"" . htmlspecialchars($rowU["url"]) . "\">
                    </div>
                    
                    <div class=\"form-group text-center\">
                        <label>Preview</label><br>
                        <img src=\"" . htmlspecialchars($rowU["url"]) . "\" alt=\"Preview\" style=\"width: 100px; height: 100px; object-fit: cover; display: block; margin: 0 auto;\">
                    </div>
                    
                    <div class=\"col-12 text-center\">
                    <br><br>
                       <button type=\"submit\" name=\"submitU\" class=\"btn btn-primary mr-2\"><i class=\"bx bx-check mr-1\"></i>Editar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    ";
}

 else {
    
    
    
    
    
    ?>
    <div class="card radius-10">
        <div class="card-header border-bottom-0 bg-transparent">
            <div class="d-flex align-items-center">
                
              
                <div class="ms-auto">
                    <a href="ads.php?create">
                        <button type="button" class="btn btn-primary mr-2 radius-10">Adicionar anúncios</button>
                    </a>
                </div>
            </div>
            <br>
            <div class="d-flex align-items-center">
                <div>
                    <h5 class="font-weight-bold mb-0">Anuncios cadastrados</h5>
                </div>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table mb-0 align-middle table-sm">
                    <thead>
                    <tr>
                        <th>Index</th>
                        <th>Title</th>
                        <th>Preview</th>
                           <th>Delete</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                   
                     $res = $adb->query("SELECT * FROM ads");
                            $row_index = 0;
                            while ($row = $res->fetchArray()) {
                                $id = $row["id"];
                                ?>
                                <tr>
                                    <td><?php echo ++$row_index;?></td>
                                    <td><?php echo $row['title'];?></td>
                                    <td><img src="<?php echo $row["url"]; ?>" width="50px"></td>

                                    <td>
                                        <div class="d-flex order-actions">
                                            <a href="ads.php?delete=<?= $row['id'] ?>" class="text-light bg-danger border-0">
                                                <i class='bx bxs-trash'></i>
                                            </a>
                                        </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;
    }
}
}
?>