File: /home/artinside/www/lhh/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\Type;
use Source\Models\Ecommerce\Variations;
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();
if (!empty($data["search"]) && str_search($data["search"]) != "all") {
$search = str_search($data["search"]);
$products = (new Product())->find("MATCH(title, title) AGAINST(:s)", "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 variants(?array $data): void
{
if(isset($data) AND $data["action"] == "with-variants"){
if($data["variant"][0] != ""){
$json["html"] = $this->view->render("views/fragments/variants",["variants" => $data["variant"], "total" => $data["actual"]]);
echo json_encode($json);
return;
}
return;
}
if(isset($data) AND $data["action"] == "no-variants"){
$json["html"] = $this->view->render("views/fragments/no-variants",[]);
echo json_encode($json);
return;
return;
}
}
/**
* @param array|null $data
* @throws \Exception
*/
public function product(?array $data): void
{
//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();
if ($data["weight"] == 0 OR $data["height"] == 0 OR $data["width"] == 0 OR $data["price"] == 0) {
$json["message"] = $this->message->error("Peso, altura, comprimento, largura e preço não podem ser iguais a 0")->render();
echo json_encode($json);
return;
}
$productCreate = new Product();
$productCreate->category = $data["category"];
$productCreate->title = $data["title"];
$productCreate->uri = str_slug($productCreate->title);
$productCreate->subtitle = $data["subtitle"];
$productCreate->sku = $data["sku"];
$productCreate->content = str_replace(["{title}"], [$productCreate->title], $content);
$productCreate->video = $data["video"];
$productCreate->status = $data["status"];
$productCreate->post_at = date_fmt_back($data["post_at"]);
$productCreate->post_at = date_fmt_back($data["post_at"]);
$productCreate->variations = $data["variations"] == "" ? "no-variations" : $data["variations"];
// $productCreate->collection = $data["collection"];
$productCreate->gallery_link = $gLink;
//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 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(is_array($data["width"])){
$productCreate->type = 1;
$dataArray = explode(",", $data["firstVariation"]);
for($i = 0; $i < count($dataArray); $i++){
$variationCreate = new ProductVariations();
$variationCreate->product_id = $gLink;
(int)$variationCreate->width = $data["width"][$i];
(int)$variationCreate->height = $data["height"][$i];
(float)$variationCreate->weight = $data["weight"][$i];
(int)$variationCreate->depth = $data["depth"][$i];
$variationCreate->price = $data["price"][$i];
$variationCreate->promotional_price = $data["promotional_price"][$i];
(float)$variationCreate->stock = $data["stock"][$i];
$variationCreate->first_variation_item = trim($dataArray[$i]);
if (!$variationCreate->save()) {
$json["message"] = $variationCreate->message()->render();
echo json_encode($json);
return;
}
}
}else{
$productCreate->type = 0;
$variationCreate = new ProductVariations();
$variationCreate->product_id = $gLink;
$variationCreate->width = ((int)$data["width"]);
$variationCreate->height = ((int)$data["height"]);
$variationCreate->weight = ((float)$data["weight"]);
$variationCreate->depth = ((int)$data["depth"]);
$variationCreate->price = $data["price"];
$variationCreate->promotional_price = $data["promotional_price"];
$variationCreate->stock = ((float)$data["stock"]);
$variationCreate->first_variation_item = "no-variations";
if (!$variationCreate->save()) {
$json["message"] = $variationCreate->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/product/{$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"]);
//Verifica se algum item foi deletado
$array1 = array_map("trim", explode(",", $productEdit->variations)); //VEM DO BANCO
$array2 = array_map("trim", explode(",", $data["firstVariation"])); // VEM DA PÁGINA
$resultDeleteVariation = array_diff($array1, $array2);
// if ($data["weight"] == 0 OR $data["height"] == 0 OR $data["width"] == 0 OR $data["price"] == 0) {
// $json["message"] = $this->message->error("Peso, altura, comprimento, largura e preço não podem ser iguais a 0")->render();
// echo json_encode($json);
// return;
// }
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/home")]);
return;
}
$productEdit->category = $data["category"];
$productEdit->title = $data["title"];
$productEdit->uri = str_slug($productEdit->title);
$productEdit->subtitle = $data["subtitle"];
$productEdit->sku = $data["sku"];
$productEdit->content = str_replace(["{title}"], [$productEdit->title], $content);
$productEdit->video = $data["video"];
$productEdit->status = $data["status"];
$productEdit->post_at = date_fmt_back($data["post_at"]);
$productEdit->variations = $data["variations"] == "" ? "no-variations" : $data["variations"];
// $productEdit->collection = $data["collection"];
// $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 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(is_array($data["width"])){
$productEdit->type = 1;
//VERIFICAR SE O NOVO ITEM COM VARIANTES ERA UM ITEM SIMPLES
$verifyEditSingle = (new ProductVariations())->find("product_id = :gl AND first_variation_item = 'no-variations'", "gl={$productEdit->gallery_link}")->fetch();
if($verifyEditSingle){
//SE POSITIVO, DELETAR O ITEM SIMPLES PARA ABRIR ESPAÇO A UM ITEM VARIÁVEL
$verifyEditSingle->destroy();
//ignora o teste de deletar itens do array
$resultDeleteVariation = [];
}
$dataArray = explode(",", $data["firstVariation"]);
$dataArray = array_filter($dataArray);
for($i = 0; $i < count($dataArray); $i++){
if($data["variationId"][$i] == "0"){
$variationEdit = (new ProductVariations());
$variationEdit->product_id = $productEdit->gallery_link;
}else{
$variationEdit = (new ProductVariations())->find("id = :id", "id={$data["variationId"][$i]}")->fetch();
}
(int)$variationEdit->width = $data["width"][$i];
(int)$variationEdit->height = $data["height"][$i];
(float)$variationEdit->weight = $data["weight"][$i];
(int)$variationEdit->depth = $data["depth"][$i];
$variationEdit->price = $data["price"][$i];
$variationEdit->promotional_price = $data["promotional_price"][$i];
(float)$variationEdit->stock = $data["stock"][$i];
$variationEdit->first_variation_item = trim($dataArray[$i]);
if (!$variationEdit->save()) {
$json["message"] = $variationEdit->message()->render();
echo json_encode($json);
return;
}
}
//VERIFICA SE ALGUM ITEM VARIAVEL FOI DELETADO
if(count($resultDeleteVariation) >= 1){
foreach ($resultDeleteVariation as $result){
$verifyEditSingle = (new ProductVariations())->find("product_id = :gl AND first_variation_item = :fv", "gl={$productEdit->gallery_link}&fv={$result}")->fetch();
$verifyEditSingle->destroy();
}
}
}else{
$productEdit->type = 0;
//VERIFICAR SE O ITEM SEM VARIANTES ERA UM ITEM VARIAVEL
$verifyEditSingle = (new ProductVariations())->find("product_id = :gl AND first_variation_item != 'no-variations'", "gl={$productEdit->gallery_link}")->fetch(true);
if($verifyEditSingle){
//SE POSITIVO, DELETAR O ITEM SIMPLES PARA ABRIR ESPAÇO A UM ITEM VARIÁVEL
foreach ($verifyEditSingle as $verify){
$verify->destroy();
}
$variationEdit = new ProductVariations();
$variationEdit->product_id = $productEdit->gallery_link;
}else{
$variationEdit = (new ProductVariations())->find("product_id = :gl", "gl={$productEdit->gallery_link}")->fetch();
if (!$variationEdit) {
$this->message->error("Você tentou atualizar um Produto que não existe ou foi removido")->flash();
echo json_encode(["redirect" => url("/admin/product/home")]);
return;
}
}
$variationEdit->width = ((int)$data["width"]);
$variationEdit->height = ((int)$data["height"]);
$variationEdit->weight = ((float)$data["weight"]);
$variationEdit->depth = ((int)$data["depth"]);
$variationEdit->price = $data["price"];
$variationEdit->promotional_price = $data["promotional_price"];
$variationEdit->stock = ((float)$data["stock"]);
$variationEdit->first_variation_item = "no-variations";
if (!$variationEdit->save()) {
$json["message"] = $variationEdit->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/home")]);
return;
}
//delete
if (!empty($data["action"]) && $data["action"] == "delete") {
$data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
$productDelete = (new Product())->findById($data["product_id"]);
$variationDelete = (new ProductVariations())->find("product_id = :gl", "gl={$productDelete->gallery_link}")->fetch(true);
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 (!$variationDelete) {
$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);
}
(new Gallery())->galDelete($productDelete->gallery_link);
foreach ($variationDelete as $vd) {
$vd->destroy();
}
$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);
}
//MONTA ARRAY DE VARIATIONS
$array = "";
foreach ((new Variations())->find("variation_type_id = 1")->fetch(true) as $variation) {
$array .= $variation->title;
$array .= ",";
}
$array = substr($array, 0, -1);
$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/product", [
"app" => "product/product",
"head" => $head,
"product" => $productEdit,
"productVariations" => (new ProductVariations())->find("product_id = :gl", "gl={$productEdit->gallery_link}")->fetch(),
"productVariationsEdit" => (new ProductVariations())->find("product_id = :gl", "gl={$productEdit->gallery_link}")->fetch(true),
"variations" => $array,
"categories" => (new Category())->find("type = :type", "type=product")->order("title")->fetch(true),
// "types" => (new Type())->find()->order("title")->fetch(true),
// "collections" => (new Collection())->find()->order("title")->fetch(true),
"gallery" => (new Gallery())->find("gallery_link IN (SELECT gallery_link FROM products WHERE id = :id)", "id={$productEdit->id}")->fetch(true)
]);
}
/**
* @param array|null $data
*/
public function categories(?array $data): void
{
$categories = (new Category())->find("type = :type", "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
* @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";
//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"];
//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
]);
}
/**
* @param array|null $data
*/
public function types(?array $data): void
{
$types = (new Type())->find()->find();
$pager = new Pager(url("/admin/product/types/"));
$pager->pager($types->count(), 9, (!empty($data["page"]) ? $data["page"] : 1));
$head = $this->seo->render(
CONF_SITE_NAME . " | Tipos",
CONF_SITE_DESC,
url("/admin"),
url("/admin/assets/images/image.jpg"),
false
);
echo $this->view->render("widgets/product/types", [
"app" => "product/types",
"head" => $head,
"types" => $types->order("title")->limit($pager->limit())->offset($pager->offset())->fetch(true),
"paginator" => $pager->render()
]);
}
/**
* @param array|null $data
* @throws \Exception
*/
public function type(?array $data): void
{
//create
if (!empty($data["action"]) && $data["action"] == "create") {
$data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
$categoryCreate = new Type();
$categoryCreate->title = $data["title"];
$categoryCreate->uri = str_slug($categoryCreate->title);
$categoryCreate->description = $data["description"];
//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("Tipo criado com sucesso...")->flash();
$json["redirect"] = url("/admin/product/types");
echo json_encode($json);
return;
}
//update
if (!empty($data["action"]) && $data["action"] == "update") {
$data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
$categoryEdit = (new Type())->findById($data["type_id"]);
if (!$categoryEdit) {
$this->message->error("Você tentou editar um tipo de produto que não existe ou foi removido")->flash();
echo json_encode(["redirect" => url("/admin/product/types")]);
return;
}
$categoryEdit->title = $data["title"];
$categoryEdit->uri = str_slug($categoryEdit->title);
$categoryEdit->description = $data["description"];
$categoryEdit->updated_at = date(CONF_DATE_APP);
//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("Tipo de produto atualizado com sucesso...")->flash();
echo json_encode(["redirect" => url("/admin/product/types")]);
return;
}
//delete
if (!empty($data["action"]) && $data["action"] == "delete") {
$data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
$categoryDelete = (new Type())->findById($data["type_id"]);
if (!$categoryDelete) {
$json["message"] = $this->message->error("O Tipo de produto não existe ou já foi excluído 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 deste tipo")->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("Item excluído com sucesso...")->flash();
echo json_encode(["reload" => true]);
return;
}
$categoryEdit = null;
if (!empty($data["type_id"])) {
$typeId = filter_var($data["type_id"], FILTER_VALIDATE_INT);
$categoryEdit = (new Type())->findById($typeId);
}
$head = $this->seo->render(
CONF_SITE_NAME . " | Tipo de produtos",
CONF_SITE_DESC,
url("/admin"),
url("/admin/assets/images/image.jpg"),
false
);
echo $this->view->render("widgets/product/type", [
"app" => "product/types",
"head" => $head,
"type" => $categoryEdit
]);
}
/**
* @param array|null $data
*/
public function collections(?array $data): void
{
$collections = (new Collection())->find()->find();
$pager = new Pager(url("/admin/product/collections/"));
$pager->pager($collections->count(), 9, (!empty($data["page"]) ? $data["page"] : 1));
$head = $this->seo->render(
CONF_SITE_NAME . " | Coleções",
CONF_SITE_DESC,
url("/admin"),
url("/admin/assets/images/image.jpg"),
false
);
echo $this->view->render("widgets/product/collections", [
"app" => "product/collections",
"head" => $head,
"collections" => $collections->order("title")->limit($pager->limit())->offset($pager->offset())->fetch(true),
"paginator" => $pager->render()
]);
}
/**
* @param array|null $data
* @throws \Exception
*/
public function collection(?array $data): void
{
//create
if (!empty($data["action"]) && $data["action"] == "create") {
$data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
$categoryCreate = new Collection();
$categoryCreate->title = $data["title"];
$categoryCreate->uri = str_slug($categoryCreate->title);
$categoryCreate->description = $data["description"];
//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("Tipo criado com sucesso...")->flash();
$json["redirect"] = url("/admin/product/collections");
echo json_encode($json);
return;
}
//update
if (!empty($data["action"]) && $data["action"] == "update") {
$data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
$categoryEdit = (new Collection())->findById($data["collection_id"]);
if (!$categoryEdit) {
$this->message->error("Você tentou editar um tipo de produto que não existe ou foi removido")->flash();
echo json_encode(["redirect" => url("/admin/product/collections")]);
return;
}
$categoryEdit->title = $data["title"];
$categoryEdit->uri = str_slug($categoryEdit->title);
$categoryEdit->description = $data["description"];
$categoryEdit->updated_at = date(CONF_DATE_APP);
//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("Tipo de produto atualizado com sucesso...")->flash();
echo json_encode(["redirect" => url("/admin/product/collections")]);
return;
}
//delete
if (!empty($data["action"]) && $data["action"] == "delete") {
$data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
$categoryDelete = (new Collection())->findById($data["collection_id"]);
if (!$categoryDelete) {
$json["message"] = $this->message->error("O Tipo de produto não existe ou já foi excluído 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 deste tipo")->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("Item excluído com sucesso...")->flash();
echo json_encode(["reload" => true]);
return;
}
$categoryEdit = null;
if (!empty($data["collection_id"])) {
$collectionId = filter_var($data["collection_id"], FILTER_VALIDATE_INT);
$categoryEdit = (new Collection())->findById($collectionId);
}
$head = $this->seo->render(
CONF_SITE_NAME . " | Tipo de produtos",
CONF_SITE_DESC,
url("/admin"),
url("/admin/assets/images/image.jpg"),
false
);
echo $this->view->render("widgets/product/collection", [
"app" => "product/collections",
"head" => $head,
"collection" => $categoryEdit
]);
}
}