<?php
/*
 * @ https://hospedagem.matrixch.store 
 * @ PHP 7.4
 * @ Decoder version: 1.0.2
 * @ Release: 17/06/2024
*/

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

include "includes/header.php";
$table_name = "ads";
$base_file = basename($_SERVER["SCRIPT_NAME"]);
$adb->exec("CREATE TABLE IF NOT EXISTS " . $table_name . "(id INTEGER PRIMARY KEY\tAUTOINCREMENT  NOT NULL, title VARCHAR(100), url TEXT)");
$res = $adb->query("SELECT * FROM " . $table_name);
$resU = @$adb->query("SELECT * FROM " . $table_name . " WHERE id='" . $_GET["update"] . "'");
$rowU = @$resU->fetchArray();

$domain = "https://" . $_SERVER['HTTP_HOST']; // Captura automaticamente o domínio atual.

if (isset($_POST["submitU"])) {
    // 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($_POST["submit"])) {
    // Verifica se um arquivo foi enviado
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $target_dir = "img/"; // Diretório para salvar as imagens
        $target_file = $target_dir . basename($_FILES["image"]["name"]);
        $image_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        // Verifica se o arquivo é uma imagem válida (GIF, PNG, JPG, SVG)
        $valid_types = array("gif", "png", "jpg", "jpeg", "svg");
        if (in_array($image_type, $valid_types)) {
            // Redimensionar a imagem
            list($original_width, $original_height) = getimagesize($_FILES['image']['tmp_name']); // Obtém as dimensões originais
            $new_width = 304; // Largura desejada
            $new_height = 358; // Altura desejada

            // Cria a imagem redimensionada
            $image_p = imagecreatetruecolor($new_width, $new_height);
            switch ($image_type) {
                case "jpeg":
                case "jpg":
                    $image = imagecreatefromjpeg($_FILES['image']['tmp_name']);
                    break;
                case "png":
                    $image = imagecreatefrompng($_FILES['image']['tmp_name']);
                    break;
                case "gif":
                    $image = imagecreatefromgif($_FILES['image']['tmp_name']);
                    break;
                case "svg":
                    // SVG não pode ser redimensionado com GD diretamente
                    echo "Formato de imagem SVG não suportado para redimensionamento.";
                    exit;
            }

            // Redimensiona a imagem
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);

            // Salva a imagem redimensionada no diretório
            switch ($image_type) {
                case "jpeg":
                case "jpg":
                    imagejpeg($image_p, $target_file);
                    break;
                case "png":
                    imagepng($image_p, $target_file);
                    break;
                case "gif":
                    imagegif($image_p, $target_file);
                    break;
            }

            // Libera a memória
            imagedestroy($image);
            imagedestroy($image_p);

            // Recupera o URL da imagem
            $image_url = $domain . "/" . $target_file;

            // Insere 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 "Formato de imagem inválido. Somente GIF, PNG, JPG, SVG são permitidos.";
        }
    }
}


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();
    $image_path = str_replace($domain . "/", "", $rowDel['url']); // Remove o domínio da URL para obter o caminho do arquivo

    // 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["create"])) {
    echo "            <div class=\"col-md-8 mx-auto\">\n                <center>\n\t\t        <h1 class=\"colorboard\"></i>Banners</h1>\n\t            </center>\n\t\t\t\t<div class=\"card bg-primary text-white\">\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";
} else {
    if (isset($_GET["update"])) {
        echo "            <div class=\"col-md-8 mx-auto\">\n                <center>\n\t\t        <h1 class=\"colorboard\"></i>Editar Anúncios</h1>\n\t            </center>\n\t\t\t\t<div class=\"card bg-primary text-white\">\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-file-image-o\"></i> Editar Ad</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                            <form method=\"post\" enctype=\"multipart/form-data\">\n                                  <input type=\"hidden\" class=\"form-control\" name=\"id\" value=\"";
        echo $_GET["update"];
        echo "\">\n                                <div class=\"user-box\">\n                                  <input type=\"text\" name=\"title\" class=\"form-control\" value=\"";
        echo $rowU["title"];
        echo "\">\n                                  <label>Titulo</label>\n                                </div>\n                                <div class=\"user-box\">\n                                  <input type=\"text\" class=\"form-control\" name=\"url\" value=\"";
        echo $rowU["url"];
        echo "\">\n                                  <label>URL IMAGE ( GIF,PNG,JPG,SVG )</label>\n                                </div>  \n                                <div class=\"form-group\">\n                                  <label>Preview</label><br>\n                                  <img src=\"" . $rowU["url"] . "\" width=\"100px\" height=\"100px\">\n                                </div>\n                                <div class=\"col-12\"> <button type=\"submit\" name=\"submitU\" 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\t</div>\n";
    } else {
        echo "\n\t<div class=\"col-md-12 mx-auto\">\n\t<center>\n\t\t<h1 class=\"colorboard\"></i> Anúncios</h1>\n\t\t<a id=\"button\" href=\"./";
        echo $base_file;
        echo "?create\" class=\"btn btn-primary\">Adicionar</a>\n\t</center>\n\t<br>\n\t<div class=\"table-responsive\">\n\t\t<table class=\"table table-striped table-sm\">\n\t\t\t<thead style=\"color:white!important\">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Index</th>\n\t\t\t\t\t<th>Title</th>\n\t\t\t\t\t<th>Ad Url</th>\n\t\t\t\t\t<th>Preview</th>\n\t\t\t\t\t<th>Edit&nbsp;&nbsp;&nbsp;Delete</th>\n\t\t\t\t</tr>\n\t\t\t</thead>\n\t\t\t<tbody>\n";
        $row_index = 0;
        while ($row = $res->fetchArray()) {
            echo "\t\t\t\t<tr>\n\t\t\t\t\t<td>" . ++$row_index . "</td>\n\t\t\t\t\t<td>" . $row["title"] . "</td>\n\t\t\t\t\t<td>" . $row["url"] . "</td>\n\t\t\t\t\t<td><img src=\"" . $row["url"] . "\" width=\"50px\"></td>\n\t\t\t\t\t<td><a href=\"";
            echo $base_file . "?update=" . $row["id"];
            echo "\" class=\"btn btn-primary btn-sm\">Editar</a> <a href=\"" . $base_file . "?delete=" . $row["id"] . "\" class=\"btn btn-danger btn-sm delete-btn\">Excluir</a></td>\n\t\t\t\t</tr>\n";
        }
        echo "\t\t\t</tbody>\n\t\t</table>\n\t</div>\n</div>";
    }
}
?>
