<?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";

echo '<style>
/* Transição suave para imagens de banner */
.banner-preview {
    transition: opacity 0.6s ease-in-out;
    animation: none !important;
    opacity: 1 !important;
}
</style>';

$table_name = "ads4";
$base_file = basename($_SERVER["SCRIPT_NAME"]);
$adb->exec("CREATE TABLE IF NOT EXISTS " . $table_name . "(id INTEGER PRIMARY KEY AUTOINCREMENT 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"])) {
    $adb->exec("UPDATE " . $table_name . " SET title='" . $_POST["title"] . "',url='" . $_POST["url"] . "' WHERE id='" . $_POST["id"] . "'");
    $adb->close();
    echo "<script>window.location.href='ads4.php';</script>";
    exit;
}

if (isset($_POST["submit"])) {
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $target_dir = "img/";
        $target_file = $target_dir . basename($_FILES["image"]["name"]);
        $image_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        $valid_types = array("gif", "png", "jpg", "jpeg", "svg");
        if (in_array($image_type, $valid_types)) {
            list($original_width, $original_height) = getimagesize($_FILES['image']['tmp_name']);
            $new_width = 450;
            $new_height = 650;

            $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":
                    echo "Formato de imagem SVG não suportado para redimensionamento.";
                    exit;
            }

            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);

            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;
            }

            imagedestroy($image);
            imagedestroy($image_p);

            $image_url = $domain . "/" . $target_file;

            $adb->exec("INSERT INTO " . $table_name . "(title, url) VALUES('" . $_POST["title"] . "', '" . $image_url . "')");
            echo "<script>window.location.href='ads4.php';</script>";
            exit;
        } else {
            echo "Formato de imagem inválido. Somente GIF, PNG, JPG, SVG são permitidos.";
        }
    }
}

if (isset($_GET["delete"])) {
    $id_to_delete = intval($_GET["delete"]);
    $resDel = $adb->query("SELECT url FROM " . $table_name . " WHERE id=" . $id_to_delete);
    $rowDel = $resDel->fetchArray();
    $image_path = str_replace($domain . "/", "", $rowDel['url']);

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

    $adb->exec("DELETE FROM " . $table_name . " WHERE id=" . $id_to_delete);
    echo "<script>window.location.href='ads4.php';</script>";
    exit;
}

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