MOON
Server: Apache
System: Linux server1.studioinfinity.com.br 2.6.32-954.3.5.lve1.4.90.el6.x86_64 #1 SMP Tue Feb 21 12:26:30 UTC 2023 x86_64
User: artinside (517)
PHP: 7.4.33
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //proc/self/cwd/sabbry/source/App/Admin/Products.php
<?php

namespace Source\App\Admin;

use Source\Models\Category;
use Source\Models\Ecommerce\Collection;
use Source\Models\Ecommerce\Product;
use Source\Models\Ecommerce\ProductVariations;
use Source\Models\Ecommerce\Variation;
use Source\Models\Files;
use Source\Models\Gallery;
use Source\Support\Pager;
use Source\Support\Thumb;
use Source\Support\Upload;

/**
 * Class Products
 * @package Source\App\Admin
 */
class Products extends Admin
{

    /**
     * product constructor.
     */
    public function __construct($router)
    {
        parent::__construct();
        $this->view->addData("router", $router);
    }

    /**
     * @param array|null $data
     */
    public function home(?array $data): void
    {
        //search redirect
        if (!empty($data["s"])) {
            $s = str_search($data["s"]);
            echo json_encode(["redirect" => url("/admin/product/home/{$s}/1")]);
            return;
        }

        $search = null;
        $products = (new Product())->find("type = 'product'");

        if (!empty($data["search"]) && str_search($data["search"]) != "all") {
            $search = str_search($data["search"]);
            $products = (new Product())->find("type = 'product' AND (MATCH(title, subtitle) AGAINST(:s) OR title LIKE '%{$search}%' OR subtitle LIKE '%{$search}%')", "s={$search}");
            if (!$products->count()) {
                $this->message->info("Sua pesquisa não retornou resultados")->flash();
                redirect("/admin/product/home");
            }
        }

        $all = ($search ?? "all");
        $pager = new Pager(url("/admin/product/home/{$all}/"));
        $pager->pager($products->count(), 12, (!empty($data["page"]) ? $data["page"] : 1));

        $head = $this->seo->render(
            CONF_SITE_NAME . " | product",
            CONF_SITE_DESC,
            url("/admin"),
            url("/admin/assets/images/image.jpg"),
            false
        );

        echo $this->view->render("widgets/product/home", [
            "app" => "product/product",
            "head" => $head,
            "products" => $products->limit($pager->limit())->offset($pager->offset())->order("post_at DESC")->fetch(true),
            "paginator" => $pager->render(),
            "search" => $search
        ]);
    }

    /**
     * @param array|null $data
     */
    public function pecas(?array $data): void
    {
        //search redirect
        if (!empty($data["s"])) {
            $s = str_search($data["s"]);
            echo json_encode(["redirect" => url("/admin/product/pecas/{$s}/1")]);
            return;
        }

        $search = null;
        $products = (new Product())->find("type = 'pecas'");


        if (!empty($data["search"]) && str_search($data["search"]) != "all") {
            $search = str_search($data["search"]);
            $products = (new Product())->find("type = 'pecas' AND (MATCH(title, subtitle) AGAINST(:s) OR title LIKE '%{$search}%' OR subtitle LIKE '%{$search}%')", "s={$search}");
            if (!$products->count()) {
                $this->message->info("Sua pesquisa não retornou resultados")->flash();
                redirect("/admin/product/pecas");
            }
        }

        $all = ($search ?? "all");
        $pager = new Pager(url("/admin/product/pecas/{$all}/"));
        $pager->pager($products->count(), 12, (!empty($data["page"]) ? $data["page"] : 1));

        $head = $this->seo->render(
            CONF_SITE_NAME . " | Peças",
            CONF_SITE_DESC,
            url("/admin"),
            url("/admin/assets/images/image.jpg"),
            false
        );

        echo $this->view->render("widgets/product/pecas", [
            "app" => "pecas/pecas",
            "head" => $head,
            "products" => $products->limit($pager->limit())->offset($pager->offset())->order("post_at DESC")->fetch(true),
            "paginator" => $pager->render(),
            "search" => $search
        ]);
    }



    /**
     * @param array|null $data
     * @throws \Exception
     */
    public function product(?array $data): void
    {
    $url = explode("/",$_GET["route"]);
    $type = $url[3];

    $target= $type == "product" ? "home" : "pecas";
        //MCE Upload
        if (!empty($data["upload"]) && !empty($_FILES["image"])) {
            $files = $_FILES["image"];
            $upload = new Upload();
            $image = $upload->image($files, "product-" . time());

            if (!$image) {
                $json["message"] = $upload->message()->render();
                echo json_encode($json);
                return;
            }

            $json["mce_image"] = '<img style="width: 100%;" src="' . url("/storage/{$image}") . '" alt="{title}" title="{title}">';
            echo json_encode($json);
            return;
        }

        //create
        if (!empty($data["action"]) && $data["action"] == "create") {
            $content = $data["content"];
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $gLink = gallery_id();
            $productCreate = new Product();
            $productCreate->category = $data["category"];
            $productCreate->title = $data["title"];
            $productCreate->uri = str_slug($productCreate->title);
            $productCreate->subtitle = $data["subtitle"];
            $productCreate->content = str_replace(["{title}"], [$productCreate->title], $content);
            $productCreate->diferenciais = $data["diferenciais"];
            $productCreate->speed = $data["speed"];
            $productCreate->technology = $data["technology"];
            $productCreate->paper_size = $data["paper_size"];
            $productCreate->video = $data["video"];
            $productCreate->status = $data["status"];
            $productCreate->post_at = date_fmt_back($data["post_at"]);
            $productCreate->gallery_link = $gLink;
            $productCreate->type = $data["type"];
            //upload cover
            if (!empty($_FILES["cover"])) {
                $files = $_FILES["cover"];
                $upload = new Upload();
                $image = $upload->image($files, $productCreate->title);
                if (!$image) {
                    $json["message"] = $upload->message()->render();
                    echo json_encode($json);
                    return;
                }
                $productCreate->cover = $image;
            }

            //upload manual
            if (!empty($_FILES["manual"])) {
                $files = $_FILES["manual"];
                $upload = new Upload();
                $title = "m-".$productCreate->title;
                $manual = $upload->file($files, $title);
                if (!$manual) {
                    $json["message"] = $upload->message()->render();
                    echo json_encode($json);
                    return;
                }
                $productCreate->manual = $manual;
            }

            //upload manual
            if (!empty($_FILES["perfil"])) {
                $files = $_FILES["perfil"];
                $upload = new Upload();
                $title = "p-".$productCreate->title;
                $perfil = $upload->file($files, $title);
                if (!$perfil) {
                    $json["message"] = $upload->message()->render();
                    echo json_encode($json);
                    return;
                }
                $productCreate->perfil = $perfil;
            }

            //upload Gallery
            if (!empty($_FILES["gallery"])) {
                $files = $_FILES["gallery"];
                $gal = new Upload();
                if(!$gal->gallery($files, $productCreate->title, 1200, "products", $productCreate->gallery_link)){
                    $json["message"] = $gal->message()->render();
                    echo json_encode($json);
                    return;
                }
            }
            if (!$productCreate->save()) {
                $json["message"] = $productCreate->message()->render();
                echo json_encode($json);
                return;
            }
            $this->message->success("Produto publicado com sucesso...")->flash();
            $json["redirect"] = url("/admin/product/{$type}/{$productCreate->id}");

            echo json_encode($json);
            return;
        }
        //update
        if (!empty($data["action"]) && $data["action"] == "update") {
            $content = $data["content"];
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $productEdit = (new Product())->findById($data["product_id"]);

            if (!$productEdit) {
                $this->message->error("Você tentou atualizar um Produto que não existe ou foi removido")->flash();
                echo json_encode(["redirect" => url("/admin/product/{$target}")]);
                return;
            }
            $productEdit->category = $data["category"];
            $productEdit->title = $data["title"];
            $productEdit->uri = str_slug($productEdit->title);
            $productEdit->subtitle = $data["subtitle"];
            $productEdit->content = str_replace(["{title}"], [$productEdit->title], $content);
            $productEdit->diferenciais = $data["diferenciais"];
            $productEdit->speed = $data["speed"];
            $productEdit->technology = $data["technology"];
            $productEdit->paper_size = $data["paper_size"];
            $productEdit->video = $data["video"];
            $productEdit->status = $data["status"];
            $productEdit->post_at = date_fmt_back($data["post_at"]);
            $productEdit->type = $data["type"];


            //upload cover
            if (!empty($_FILES["cover"])) {
                if ($productEdit->cover && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productEdit->cover}")) {
                    unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productEdit->cover}");
                    (new Thumb())->flush($productEdit->cover);
                }

                $files = $_FILES["cover"];
                $upload = new Upload();
                $image = $upload->image($files, $productEdit->title);

                if (!$image) {
                    $json["message"] = $upload->message()->render();
                    echo json_encode($json);
                    return;
                }
                $productEdit->cover = $image;
            }



            //upload Manual
            if (!empty($_FILES["manual"])) {
                if ($productEdit->manual && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productEdit->manual}")) {
                    unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productEdit->manual}");
                }

                $files = $_FILES["manual"];
                $upload = new Upload();
                $title = "m-".$productEdit->title;
                $manual = $upload->file($files, $title);

                if (!$manual) {
                    $json["message"] = $upload->message()->render();
                    echo json_encode($json);
                    return;
                }
                $productEdit->manual = $manual;
            }

            //upload Manual
            if (!empty($_FILES["perfil"])) {
                if ($productEdit->perfil && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productEdit->perfil}")) {
                    unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productEdit->perfil}");
                }

                $files = $_FILES["perfil"];
                $upload = new Upload();
                $title = "p-".$productEdit->title;
                $perfil = $upload->file($files, $title);

                if (!$perfil) {
                    $json["message"] = $upload->message()->render();
                    echo json_encode($json);
                    return;
                }
                $productEdit->perfil = $perfil;
            }

            //upload Gallery
            if (!empty($_FILES["gallery"])) {
                $files = $_FILES["gallery"];
                $gal = new Upload();
                if(!$gal->gallery($files, $productEdit->title, 1200, "products", $productEdit->gallery_link)){
                    $json["message"] = $gal->message()->render();
                    echo json_encode($json);
                    return;
                }
            }

            if (!$productEdit->save()) {
                $json["message"] = $productEdit->message()->render();
                echo json_encode($json);
                return;
            }


            $this->message->success("Produto atualizado com sucesso...")->flash();
            echo json_encode(["redirect" => url("/admin/product/{$target}")]);
            return;
        }

        //delete
        if (!empty($data["action"]) && $data["action"] == "delete") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $productDelete = (new Product())->findById($data["product_id"]);

            if (!$productDelete) {
                $this->message->error("Você tentou excluir um Produto que não existe ou já foi removido")->flash();
                echo json_encode(["reload" => true]);
                return;
            }


            if ($productDelete->cover && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productDelete->cover}")) {
                unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productDelete->cover}");
                (new Thumb())->flush($productDelete->cover);
            }

            if ($productDelete->manual && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productDelete->manual}")) {
                unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productDelete->manual}");
            }

            if ($productDelete->perfil && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productDelete->perfil}")) {
                unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$productDelete->perfil}");
            }

            (new Gallery())->galDelete($productDelete->gallery_link);
            $variationDelete = (new ProductVariations())->delete("product_id = :gl", "gl={$productDelete->gallery_link}");
            $productDelete->destroy();
            $this->message->success("O Produto foi excluído com sucesso...")->flash();

            echo json_encode(["reload" => true]);
            return;
        }

        $productEdit = null;
        if (!empty($data["product_id"])) {
            $productId = filter_var($data["product_id"], FILTER_VALIDATE_INT);
            $productEdit = (new Product())->findById($productId);
        }

        $head = $this->seo->render(
            CONF_SITE_NAME . " | " . ($productEdit->title ?? "Novo Artigo"),
            CONF_SITE_DESC,
            url("/admin"),
            url("/admin/assets/images/image.jpg"),
            false
        );

        echo $this->view->render("widgets/product/{$type}", [
            "app" => $type == "product" ? "product/product": "pecas/peca",
            "head" => $head,
            "product" => $productEdit,
            "variations" =>  (new Variation())->find()->fetch(true),
            "productVariation" => (new ProductVariations())->order("variation_id")->find("product_id = :product_id","product_id={$productEdit->gallery_link}")->fetch(true),
            "gallery" => (new Gallery())->find("gallery_link IN (SELECT gallery_link FROM products WHERE id = :id)", "id={$productEdit->id}")->fetch(true),
            "files" => (new Files())->find("unique_id = :uid", "uid={$productEdit->gallery_link}")->fetch(true),

        ]);
    }


    public function files(?array $data) : void
    {

        if($data AND $data["action"] == "create"){


            if(!$data["title"] OR $data["title"] == ""){
                $json["message"] = $this->message->warning("Título inválido ou vazio")->render();
                echo json_encode($json);
                return;
            }
            //upload Files

            if (!empty($_FILES["file"])) {
                $create = new Files();
                $create->title = $data["title"];

                $create->unique_id = $data["unique_id"];

                $name = $data["title"]."-".gallery_id();
                $files = $_FILES["file"];
                $upload = new Upload();

                $file = $upload->file($files, $name);

                if(!$file){
                    $json["message"] = $file->message()->render();
                    echo json_encode($json);
                    return;
                }
                $create->file = $file;
                $create->save();

                $filesList = (new Files())->find("unique_id = :uid", "uid={$data["unique_id"]}")->fetch(true);
                $json["html"] = $this->view->render("views/fragments/files",["files" => $filesList]);
                $json["target"] = ".fileContent";
                $json["message"] = $this->message->success("Arquivo criado com sucesso")->render();
                $json["modalClose"] = "#modalFiles";
                echo json_encode($json);
                return;


            }
        }

        if($data AND $data["action"] == "delete"){
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $delete = (new Files())->findById($data["id"]);

            if (!$delete) {
                $json["message"] = $this->message->error("Você tentou excluir um arquivo que não existe ou já foi removido")->render();
                echo json_encode($json);
                return;
            }

            if ($delete->file && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$delete->file}")) {
                unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$delete->file}");
            }
            $delete->destroy();
            $filesList = (new Files())->find("unique_id = :uid", "uid={$data["unique_id"]}")->fetch(true);
            $json["html"] = $this->view->render("views/fragments/files",["files" => $filesList]);
            $json["target"] = ".fileContent";
            $json["message"] = $this->message->success("O arquivo foi excluído com sucesso...")->render();
            echo json_encode($json);
            return;
        }

    }

    /**
     * @param array|null $data
     */
    public function categories(?array $data): void
    {
        $categories = (new Category())->find("type = :type AND session = 0", "type=product");
        $pager = new Pager(url("/admin/product/categories/"));
        $pager->pager($categories->count(), 9, (!empty($data["page"]) ? $data["page"] : 1));

        $head = $this->seo->render(
            CONF_SITE_NAME . " | Categorias",
            CONF_SITE_DESC,
            url("/admin"),
            url("/admin/assets/images/image.jpg"),
            false
        );

        echo $this->view->render("widgets/product/categories", [
            "app" => "product/categories",
            "head" => $head,
            "categories" => $categories->order("title")->limit($pager->limit())->offset($pager->offset())->fetch(true),
            "paginator" => $pager->render()
        ]);
    }


    /**
     * @param array|null $data
     */
    public function categoriesPecas(?array $data): void
    {
        $categories = (new Category())->find("type = :type AND session = 0", "type=pecas");
        $pager = new Pager(url("/admin/product/categories/"));
        $pager->pager($categories->count(), 9, (!empty($data["page"]) ? $data["page"] : 1));

        $head = $this->seo->render(
            CONF_SITE_NAME . " | Categorias",
            CONF_SITE_DESC,
            url("/admin"),
            url("/admin/assets/images/image.jpg"),
            false
        );

        echo $this->view->render("widgets/product/categories-pecas", [
            "app" => "pecas/categories-pecas",
            "head" => $head,
            "categories" => $categories->order("title")->limit($pager->limit())->offset($pager->offset())->fetch(true),
            "paginator" => $pager->render()
        ]);
    }


    /**
     * @param array|null $data
     * @throws \Exception
     */
    public function category(?array $data): void
    {
        //create
        if (!empty($data["action"]) && $data["action"] == "create") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $categoryCreate = new Category();
            $categoryCreate->title = $data["title"];
            $categoryCreate->uri = str_slug($categoryCreate->title);
            $categoryCreate->description = $data["description"];
            $categoryCreate->type = "product";
            $categoryCreate->session = $data["session"];

            //upload cover
            if (!empty($_FILES["cover"])) {
                $files = $_FILES["cover"];
                $upload = new Upload();
                $image = $upload->image($files, $categoryCreate->title);

                if (!$image) {
                    $json["message"] = $upload->message()->render();
                    echo json_encode($json);
                    return;
                }

                $categoryCreate->cover = $image;
            }

            if (!$categoryCreate->save()) {
                $json["message"] = $categoryCreate->message()->render();
                echo json_encode($json);
                return;
            }

            $this->message->success("Categoria criada com sucesso...")->flash();
            $json["redirect"] = url("/admin/product/categories");

            echo json_encode($json);
            return;
        }

        //update
        if (!empty($data["action"]) && $data["action"] == "update") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $categoryEdit = (new Category())->findById($data["category_id"]);

            if (!$categoryEdit) {
                $this->message->error("Você tentou editar uma categoria que não existe ou foi removida")->flash();
                echo json_encode(["redirect" => url("/admin/product/categories")]);
                return;
            }

            $categoryEdit->title = $data["title"];
            $categoryEdit->uri = str_slug($categoryEdit->title);
            $categoryEdit->description = $data["description"];
            $categoryEdit->session = $data["session"];


            //upload cover
            if (!empty($_FILES["cover"])) {
                if ($categoryEdit->cover && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$categoryEdit->cover}")) {
                    unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$categoryEdit->cover}");
                    (new Thumb())->flush($categoryEdit->cover);
                }

                $files = $_FILES["cover"];
                $upload = new Upload();
                $image = $upload->image($files, $categoryEdit->title);

                if (!$image) {
                    $json["message"] = $upload->message()->render();
                    echo json_encode($json);
                    return;
                }

                $categoryEdit->cover = $image;
            }

            if (!$categoryEdit->save()) {
                $json["message"] = $categoryEdit->message()->render();
                echo json_encode($json);
                return;
            }

            $this->message->success("Categoria atualizada com sucesso...")->flash();
            echo json_encode(["redirect" => url("/admin/product/categories")]);
            return;
        }


        //delete
        if (!empty($data["action"]) && $data["action"] == "delete") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $categoryDelete = (new Category())->findById($data["category_id"]);

            if (!$categoryDelete) {
                $json["message"] = $this->message->error("A categoria não existe ou já foi excluída antes")->render();
                echo json_encode($json);
                return;
            }

            if ($categoryDelete->products()->count()) {
                $json["message"] = $this->message->warning("Não é possível remover pois existem produtos cadastrados")->render();
                echo json_encode($json);
                return;
            }

            if ($categoryDelete->cover && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$categoryDelete->cover}")) {
                unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$categoryDelete->cover}");
                (new Thumb())->flush($categoryDelete->cover);
            }

            $categoryDelete->destroy();
            $this->message->success("A categoria foi excluída com sucesso...")->flash();
            echo json_encode(["reload" => true]);

            return;
        }

        $categoryEdit = null;
        if (!empty($data["category_id"])) {
            $categoryId = filter_var($data["category_id"], FILTER_VALIDATE_INT);
            $categoryEdit = (new Category())->findById($categoryId);
        }

        $head = $this->seo->render(
            CONF_SITE_NAME . " | Categoria",
            CONF_SITE_DESC,
            url("/admin"),
            url("/admin/assets/images/image.jpg"),
            false
        );

        echo $this->view->render("widgets/product/category", [
            "app" => "product/categories",
            "head" => $head,
            "category" => $categoryEdit,
            "subSession" => (new Category())->find("type = 'product' AND session = 0")->fetch(true)
        ]);
    }


    /**
     * @param array|null $data
     * @throws \Exception
     */
    public function categoryPecas(?array $data): void
    {
        //create
        if (!empty($data["action"]) && $data["action"] == "create") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $categoryCreate = new Category();
            $categoryCreate->title = $data["title"];
            $categoryCreate->uri = str_slug($categoryCreate->title);
            $categoryCreate->description = $data["description"];
            $categoryCreate->type = "pecas";
            $categoryCreate->session = $data["session"];

            //upload cover
            if (!empty($_FILES["cover"])) {
                $files = $_FILES["cover"];
                $upload = new Upload();
                $image = $upload->image($files, $categoryCreate->title);

                if (!$image) {
                    $json["message"] = $upload->message()->render();
                    echo json_encode($json);
                    return;
                }

                $categoryCreate->cover = $image;
            }

            if (!$categoryCreate->save()) {
                $json["message"] = $categoryCreate->message()->render();
                echo json_encode($json);
                return;
            }

            $this->message->success("Categoria criada com sucesso...")->flash();
            $json["redirect"] = url("/admin/product/categories-pecas");

            echo json_encode($json);
            return;
        }

        //update
        if (!empty($data["action"]) && $data["action"] == "update") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $categoryEdit = (new Category())->findById($data["category_id"]);

            if (!$categoryEdit) {
                $this->message->error("Você tentou editar uma categoria que não existe ou foi removida")->flash();
                echo json_encode(["redirect" => url("/admin/product/categories-pecas")]);
                return;
            }

            $categoryEdit->title = $data["title"];
            $categoryEdit->uri = str_slug($categoryEdit->title);
            $categoryEdit->description = $data["description"];
            $categoryEdit->session = $data["session"];


            //upload cover
            if (!empty($_FILES["cover"])) {
                if ($categoryEdit->cover && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$categoryEdit->cover}")) {
                    unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$categoryEdit->cover}");
                    (new Thumb())->flush($categoryEdit->cover);
                }

                $files = $_FILES["cover"];
                $upload = new Upload();
                $image = $upload->image($files, $categoryEdit->title);

                if (!$image) {
                    $json["message"] = $upload->message()->render();
                    echo json_encode($json);
                    return;
                }

                $categoryEdit->cover = $image;
            }

            if (!$categoryEdit->save()) {
                $json["message"] = $categoryEdit->message()->render();
                echo json_encode($json);
                return;
            }

            $this->message->success("Categoria atualizada com sucesso...")->flash();
            echo json_encode(["redirect" => url("/admin/product/categories-pecas")]);
            return;
        }


        //delete
        if (!empty($data["action"]) && $data["action"] == "delete") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $categoryDelete = (new Category())->findById($data["category_id"]);

            if (!$categoryDelete) {
                $json["message"] = $this->message->error("A categoria não existe ou já foi excluída antes")->render();
                echo json_encode($json);
                return;
            }

            if ($categoryDelete->products()->count()) {
                $json["message"] = $this->message->warning("Não é possível remover pois existem produtos cadastrados")->render();
                echo json_encode($json);
                return;
            }

            if ($categoryDelete->cover && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$categoryDelete->cover}")) {
                unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$categoryDelete->cover}");
                (new Thumb())->flush($categoryDelete->cover);
            }

            $categoryDelete->destroy();
            $this->message->success("A categoria foi excluída com sucesso...")->flash();
            echo json_encode(["reload" => true]);

            return;
        }

        $categoryEdit = null;
        if (!empty($data["category_id"])) {
            $categoryId = filter_var($data["category_id"], FILTER_VALIDATE_INT);
            $categoryEdit = (new Category())->findById($categoryId);
        }

        $head = $this->seo->render(
            CONF_SITE_NAME . " | Categoria",
            CONF_SITE_DESC,
            url("/admin"),
            url("/admin/assets/images/image.jpg"),
            false
        );

        echo $this->view->render("widgets/product/category-pecas", [
            "app" => "product/categories-pecas",
            "head" => $head,
            "category" => $categoryEdit,
            "subSession" => (new Category())->find("type = 'pecas' AND session = 0")->fetch(true)
        ]);
    }



    /**
     * @param array|null $data
     */
    public function variations(?array $data): void
    {
        $variations = (new Variation())->find();
        $pager = new Pager(url("/admin/product/variations/"));
        $pager->pager($variations->count(), 9, (!empty($data["page"]) ? $data["page"] : 1));

        $head = $this->seo->render(
            CONF_SITE_NAME . " | Variações",
            CONF_SITE_DESC,
            url("/admin"),
            url("/admin/assets/images/image.jpg"),
            false
        );

        echo $this->view->render("widgets/product/variations", [
            "app" => "product/variations",
            "head" => $head,
            "variations" => $variations->order("title")->limit($pager->limit())->offset($pager->offset())->fetch(true),
            "paginator" => $pager->render()
        ]);
    }

    /**
     * @param array|null $data
     * @throws \Exception
     */
    public function variation(?array $data): void
    {


        //create
        if (!empty($data["action"]) && $data["action"] == "create") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $variationCreate = new Variation();
            $variationCreate->title = $data["title"];
            $variationCreate->type = "products";

            if (!$variationCreate->save()) {
                $json["message"] = $variationCreate->message()->render();
                echo json_encode($json);
                return;
            }
            $this->message->success("Variação criado com sucesso...")->flash();
            $json["redirect"] = url("/admin/product/variations");
            echo json_encode($json);
            return;
        }
        //update
        if (!empty($data["action"]) && $data["action"] == "update") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);

            $variationEdit = (new Variation())->findById($data["variation_id"]);
            if (!$variationEdit) {
                $this->message->error("Você tentou editar uma Variação que não existe ou foi removida")->flash();
                echo json_encode(["redirect" => url("/admin/product/variations")]);
                return;
            }
            $variationEdit->title = $data["title"];
            $variationEdit->updated_at = date(CONF_DATE_APP);

            if (!$variationEdit->save()) {
                $json["message"] = $variationEdit->message()->render();
                echo json_encode($json);
                return;
            }
            $this->message->success("Variação atualizada com sucesso...")->flash();
            echo json_encode(["redirect" => url("/admin/product/variations")]);
            return;
        }

        //delete
        if (!empty($data["action"]) && $data["action"] == "delete") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $variationDelete = (new Variation())->findById($data["variation_id"]);

            if (!$variationDelete) {
                $json["message"] = $this->message->error("A variação não existe ou já foi excluída ")->render();
                echo json_encode($json);
                return;
            }

//            if ($variationDelete->products()->count()) {
//                $json["message"] = $this->message->warning("Não é possível remover pois existem produtos cadastrados deste tipo")->render();
//                echo json_encode($json);
//                return;
//            }

            $variationDelete->destroy();
            $this->message->success("Variação excluída com sucesso...")->flash();
            echo json_encode(["reload" => true]);

            return;
        }

        $variationEdit = null;
        if (!empty($data["variation_id"])) {
            $typeId = filter_var($data["variation_id"], FILTER_VALIDATE_INT);
            $variationEdit = (new Variation())->findById($typeId);
        }

        $head = $this->seo->render(
            CONF_SITE_NAME . " | Variação de produtos",
            CONF_SITE_DESC,
            url("/admin"),
            url("/admin/assets/images/image.jpg"),
            false
        );

        echo $this->view->render("widgets/product/variation", [
            "app" => "product/variations",
            "head" => $head,
            "variation" => $variationEdit
        ]);
    }


    public function addVariations(?array $data) : void
    {

        if(!$data["gallery_link"]){
            $json["message"] = $this->message->error("Erro ao selecionar variação")->render();
            echo json_encode($json);
            return;
        }

        if (!empty($data["action"]) && $data["action"] == "delete") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $variationDelete = (new ProductVariations())->findById($data["id"]);
            if (!$variationDelete) {
                $this->message->error("Você tentou excluir uma Variação que não existe ou já foi removida")->flash();
                echo json_encode(["reload" => true]);
                return;
            }
            $variationDelete->destroy();

            $json["ajax"] = $this->view->render("views/fragments/table-variations.php",
                ["productVariation" =>
                    (new ProductVariations())
                        ->order("variation_id")
                        ->find("product_id = :product_id","product_id={$data["gallery_link"]}")
                        ->fetch(true)]);
            $json["ajaxTarget"] = ".j_variation";
            $json["message"] = $this->message->success("Variações deletada com sucesso")->render();
            echo json_encode($json);
            return;
        }

        if (!empty($data["action"]) && $data["action"] == "addItem") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $variationUpdate = (new ProductVariations())->findById($data["id"]);
            $variationUpdate->caracteristic = $data["caracteristic"];
            if (!$variationUpdate->save()) {
                $json["message"] = $this->message->error("Erro ao atualizar, tente novamente mais tarde")->render();
                echo json_encode($json);
                return;
            }
            $json["ok"] = "ok";
            echo json_encode($json);
            return;

        }

        if(!isset($data["variations"])){
            $ProductVariations = (new ProductVariations())->find("product_id = :product_id", "product_id={$data["gallery_link"]}");
            if ($ProductVariations->count()) {

                $ProductVariations->delete("product_id = :product_id", "product_id={$data["gallery_link"]}");
                $json["message"] = $this->message->info("Itens Deletados")->render();
                $json["ajax"] = $this->view->render("views/fragments/table-variations.php",
                    ["productVariation" =>
                        (new ProductVariations())
                            ->order("variation_id")
                            ->find("product_id = :product_id","product_id={$data["gallery_link"]}")
                            ->fetch(true)]);
                $json["ajaxTarget"] = ".j_variation";
                echo json_encode($json);
                return;
            }
            $json["message"] = $this->message->error("Selecione ao menos uma variação")->render();
            echo json_encode($json);
            return;
        }

        $variations = $data["variations"];
        foreach ($variations as $item) {

            $ProductVariations = (new ProductVariations())->find("product_id = :product_id AND variation_id = :variation_id",
                "product_id={$data["gallery_link"]}&variation_id={$item}");

            if (!$ProductVariations->count()) {
                $ProductVariations->product_id = $data["gallery_link"];
                $ProductVariations->variation_id = $item;
                $ProductVariations->save();
            }

        }

        $json["ajax"] = $this->view->render("views/fragments/table-variations.php",
            ["productVariation" =>
                (new ProductVariations())
                    ->order("variation_id")
                    ->find("product_id = :product_id","product_id={$data["gallery_link"]}")
                    ->fetch(true)]);        $json["ajaxTarget"] = ".j_variation";
        $json["message"] = $this->message->success("Variações adicionadas com sucesso")->render();
        echo json_encode($json);
        return;

    }

}