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: //home/artinside/sites.artinside.com.br/mainpro/source/App/Web.php
<?php

namespace Source\App;

use Anam\Phpcart\Cart;
use FlyingLuscas\ViaCEP\ViaCEP;
use NodejsPhpFallback\Uglify;
use Source\Core\Controller;
use Source\Core\Session;
use Source\Core\View;
use Source\Models\Activity;
use Source\Models\Address;
use Source\Models\Auth;
use Source\Models\Category;
use Source\Models\Company;
use Source\Models\Config;
use Source\Models\CourseDocuments;
use Source\Models\Ecommerce\Collection;
use Source\Models\Ecommerce\CreditCard;
use Source\Models\Ecommerce\OrderItens;
use Source\Models\Ecommerce\Orders;
use Source\Models\Ecommerce\Product;
use Source\Models\Ecommerce\ProductVariations;
use Source\Models\Enrolment;
use Source\Models\Files;
use Source\Models\Filters;
use Source\Models\Gallery;
use Source\Models\Newsletter;
use Source\Models\Post;
use Source\Models\Report\Access;
use Source\Models\Report\Online;
use Source\Models\User;
use Source\Support\Email;
use Source\Support\Frete;
use Source\Support\FreteFrenet;
use Source\Support\Pager;
use Source\Models\Envelopadores;
use Source\Models\Course;
use Source\Models\Locations;
use Source\Models\Client;
use Source\Support\RecaptchaV2;
use Source\Support\Upload;

/**
 * Web Controller
 * @package Source\App
 */
class Web extends Controller
{
    /** @var User */
    private $user;

    /**
     * Web constructor.
     */
    public function __construct($router)
    {
        parent::__construct(__DIR__ . "/../../themes/" . CONF_VIEW_THEME . "/");
        (new Access())->report();
        (new Online())->report();
        $this->view->addData("router", $router);
        $Config = (new Config())->findById(1);
        if ($Config->data()->maintenance == 1) {
            if (!Auth::user() or !Auth::userLevel(Auth::user(), 5)) {
                get_url(1) != "manutencao" ? redirect("manutencao") : null;
            } else {
                $this->view->addData("maintenance", true);
            }
        }
    }

    /**
     * SITE HOME
     */
    public function home(): void
    {
        $head = $this->seo->render(
            CONF_SITE_NAME . " - " . CONF_SITE_TITLE,
            CONF_SITE_DESC,
            url(),
            theme("/assets/images/share.jpg")
        );

//        echo $this->view->render("lp2", []);
        echo $this->view->render("home", [
            "head" => $head,
            "gallery" => (new Post())
                ->find("id = 1")
                ->fetch(),
        ]);
    }

    /**
     * SITE HOME
     */
    public function teachers(): void
    {
        redirect("https://secure.maa.com.br/inicio/sala_alunos/lectus/professor.asp");
    }

    /**
     * SITE HOME
     */
    public function whatsapp(): void
    {
        redirect("https://api.whatsapp.com/send?phone=5511993662413");
    }

    /**
     * SITE HOME
     */
    public function typ(): void
    {
        $head = $this->seo->render(
            CONF_SITE_NAME . " - " . CONF_SITE_TITLE,
            CONF_SITE_DESC,
            url(),
            theme("/assets/images/share.jpg")
        );
        echo $this->view->render("typ", [
            "head" => $head,
            "breadcrumb" => (object)[
                ["obrigado"]
            ]

        ]);
    }

    /**
     * SITE HOME
     */
    public function typ2(): void
    {
        $head = $this->seo->render(
            CONF_SITE_NAME . " - " . CONF_SITE_TITLE,
            CONF_SITE_DESC,
            url(),
            theme("/assets/images/share.jpg")
        );
        echo $this->view->render("typ2", [
            "head" => $head,
            "breadcrumb" => (object)[
                ["obrigado"]
            ]

        ]);
    }

    /**
     * SITE HOME
     */
    public function typ3($data): void
    {
        if (isset($data) and $data["course_id"] != "") {
            $ids = explode("-", $data["course_id"]);
            $enrolment_id = $ids[0];
            $client_id = $ids[1];

            $enrolment = (new Enrolment())->find(
                "id = {$enrolment_id} AND client_id = {$client_id}",
                "cid={$enrolment_id}&clid={$client_id}"
            );

            if ($enrolment->count() != 1) {
                redirect(url());
            }
        } else {
            redirect(url());
        }

        $head = $this->seo->render(
            CONF_SITE_NAME . " - " . CONF_SITE_TITLE,
            CONF_SITE_DESC,
            url(),
            theme("/assets/images/share.jpg")
        );
        echo $this->view->render("typ3", [
            "head" => $head,
            "enrolment" => $enrolment->fetch(),
            "breadcrumb" => (object)[
                ["obrigado"]
            ]

        ]);
    }

    /**
     *
     */
    public function maintenance(): void
    {
        echo $this->view->render("maintenance", []);
    }


    /**
     *
     */
    public function campaign(): void
    {
        echo $this->view->render("campaign", [
            "categories" => (new Category())
                ->find("type = 'product'")
                ->offset(0)
                ->limit(10)
                ->fetch(true)
        ]);
    }

    /**
     *
     */
    public function campaignResults(): void
    {
        echo $this->view->render("campaign-results", [
            "results" => (new Newsletter())
                ->find("origin = 'Desafio SH Decor Envelopador'")
                ->fetch(true)
        ]);
    }

    public function ctaCampaign(array $data): void
    {
        if (isset($data["action"]) and $data["action"] == "desafio") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
//            if (request_limit("desafio", 5, 60*3)) {
//                $json['message'] = $this->message->error("Você já efetuou 5 tentativas de cadastro, esse é o limite. Por favor, aguarde 3 minutos para tentar novamente!")->render();
//                echo json_encode($json);
//                return;
//            }

            if (in_array("", $data)) {
                $json['message'] = $this->message->warning("Você deve preencher todos os campos")->render();
                echo json_encode($json);
                return;
            }

            if (!is_email($data['email'])) {
                $json['message'] = $this->message->info("Formato de email inválido")->render();
                echo json_encode($json);
                return;
            }
            $insta = str_replace(["@", " ", "  ", "   "], "", $data["insta"]);
            $newsletter = (new Newsletter())->find(
                "(email = :email OR extraField1 = :insta) AND origin = :origin",
                "email={$data["email"]}&insta={$insta}&origin={$data["origin"]}"
            );

            if ($newsletter->count()) {
                $json['message'] = $this->message->info("Você já está cadastrado em nosso Desafio")->render();
                echo json_encode($json);
                return;
            }
            $newsCreate = new Newsletter();

            $newsCreate->email = $data["email"];
            $newsCreate->name = $data["name"];
            $newsCreate->origin = $data["origin"];
            $newsCreate->extraField1 = $insta;
            $newsCreate->save();

            $json['message'] = $this->message->success("Inscrição Efetuada com sucesso {$newsletter->name}")->render();
            $json['callback'] = true;
            echo json_encode($json);
            return;
        }
    }


    /**
     *LANDINGS
     */
    public function lp1(): void
    {
        echo $this->view->render("lp1", [


        ]);
    }

    /**
     *LANDINGS
     */
    public function lp2(): void
    {
        echo $this->view->render("lp2", []);
    }

    /**
     *LANDINGS
     */
    public function lp3(): void
    {
        echo $this->view->render("lp3", []);
    }

    /**
     *LANDINGS
     */
    public function lp4(): void
    {
        echo $this->view->render("lp4", []);
    }

    /**
     * SITE ABOUT
     */
    public function about(): void
    {
        $company = (new Company())->findById(1);

        $head = $this->seo->render(
            "Sobre o " . CONF_SITE_NAME . " - " . CONF_SITE_DESC,
            CONF_SITE_DESC,
            url("/sobre"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("about", [
            "head" => $head,
            "company" => $company,
            "pageTitle" => (object)[
                "title" => "Sobre o " . CONF_SITE_NAME,
                "subtitle" => "Quem Somos",
                "image" => url("images/slide-bg.jpg"),

            ],
            "breadcrumb" => (object)[
                ["O " . CONF_SITE_NAME, "#"]
            ]
        ]);
    }
    /**
     * SITE OUVIDORIA
     */
    public function ouvidoria(): void
    {
        $company = (new Company())->findById(1);

        $head = $this->seo->render(
            "Ouvidoria " . CONF_SITE_NAME . " - " . CONF_SITE_DESC,
            CONF_SITE_DESC,
            url("/ouvidoria"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("ouvidoria", [
            "head" => $head,
            "company" => $company,
            "pageTitle" => (object)[
                "title" => "Ouvidoria " . CONF_SITE_NAME,
                "subtitle" => "Canal aberto com o Paliar",
                "image" => url("images/slide-bg.jpg"),

            ]
        ]);
    }


    /**
     * SITE Professores
     */
    public function team(): void
    {
        $company = (new Company())->findById(1);

        $head = $this->seo->render(
            "Equipe " . CONF_SITE_NAME . " - " . CONF_SITE_DESC,
            CONF_SITE_DESC,
            url("/professores"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("team", [
            "head" => $head,
            "company" => $company,
            "pageTitle" => (object)[
                "title" => "Nossos Professores ",
                "subtitle" => "Conheça nossos professores",
                "image" => url("images/slide-bg.jpg"),

            ],
            "breadcrumb" => (object)[
                ["Nossos Professores ", "#"]
            ]
        ]);
    }

    /**
     * SITE ABOUT
     */
    public function consulting(): void
    {
        $head = $this->seo->render(
            "Consultoria " . CONF_SITE_NAME . " - " . CONF_SITE_DESC,
            CONF_SITE_DESC,
            url("/consultoria"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("consulting", [
            "head" => $head,
            "pageTitle" => (object)[
                "title" => "Consultoria",
                "subtitle" => "Serviços Prestados",
                "image" => url("images/slide-bg.jpg"),

            ],
            "breadcrumb" => (object)[
                ["Consultoria", "#"]
            ]
        ]);
    }

    /**
     * SITE ABOUT
     */
    public function central(): void
    {
        $head = $this->seo->render(
            "Central de Eventos " . CONF_SITE_NAME . " - " . CONF_SITE_DESC,
            CONF_SITE_DESC,
            url("/central-de-eventos"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("central", [
            "head" => $head,
            "pageTitle" => (object)[
                "title" => "Central de Eventos",
                "subtitle" => "Serviços Prestados",
                "image" => url("images/slide-bg.jpg"),

            ],
            "breadcrumb" => (object)[
                ["Central de Eventos", "#"]
            ]
        ]);
    }

    /**
     * SITE ABOUT
     */
    public function faq(): void
    {
        $head = $this->seo->render(
            "Dúvidas Frequentes (FAQ) - " . CONF_SITE_NAME . " - " . CONF_SITE_DESC,
            CONF_SITE_DESC,
            url("/duvidas-frequentes"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("faq", [
            "head" => $head,
            "pageTitle" => (object)[
                "title" => "Dúvidas Frequentes",
                "subtitle" => "FAQ",
                "image" => url("images/slide-bg.jpg"),

            ],
            "breadcrumb" => (object)[
                ["Dúvidas Frequentes", "#"]
            ]
        ]);
    }

    /**
     * SITE ABOUT
     */
    public function purpose(): void
    {
        $head = $this->seo->render(
            CONF_SITE_NAME . " - Nosso Propósito",
            CONF_SITE_DESC,
            url("/sobre"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("purpose", [
            "head" => $head,
//            "company" => $company,
            "pageTitle" => (object)[
                "title" => "Nosso Propósito",
                "subtitle" => "Conheça um pouco mais do Paliar",
                "image" => url("images/slide-bg.jpg"),

            ],
            "breadcrumb" => (object)[
                ["Nosso Propósito", "#"]
            ]
        ]);
    }


    /**
     *CONTACT PAGE SITE
     */
    public function contact(): void
    {
        $head = $this->seo->render(
            "Contato " . CONF_SITE_NAME . " - " . CONF_SITE_DESC,
            CONF_SITE_DESC,
            url("/contato"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("contact", [
            "head" => $head,
            "pageTitle" => (object)[
                "title" => "Fale Conosco",
                "subtitle" => "Nos envie suas dúvidas e sugestões",
                "image" => url("images/slide-bg.jpg"),

            ],
            "breadcrumb" => (object)[
                ["Fale Conosco", "#"]
            ]
        ]);
    }

    /**
     *Form de Contato do site
     */
    public function contactForm(array $data): void
    {
        if (isset($data)) {
//            if (request_limit("weblogin", 10, 60 * 3)) {
//                $json['message'] = $this->message->error(
//                    "Você já efetuou 10 tentativas, esse é o limite. Por favor, aguarde 3 minutos para tentar novamente!"
//                )->render();
//                echo json_encode($json);
//                return;
//            }

            if (empty($data['email']) || empty($data['name']) || empty($data['message']) || empty($data['phone'])  || empty($data['subject']) ) {
                $json['message'] = $this->message->warning("Campos com * são de preenchimento obrigatório")->render();
                echo json_encode($json);
                return;
            }

            $redirect = url("/confirma");
            if ($data["action"] == "contato") {

                $contact = new Newsletter();
                $contact->name = $data["name"];
                $contact->email = $data["email"];
                $contact->phone = $data["phone"];
                $contact->subject = $data["subject"];
                $contact->message = $data["message"];
//                $contact->landing = $data["landing"];
                $mensagem = $data["message"];
                $redirect = "";
                $contact->save();
            }

            if ($data["action"] == "course") {
                $contact = new Newsletter();
                $contact->name = $data["name"];
                $contact->email = $data["email"];
                $contact->phone = $data["phone"];
                $contact->subject = $data["subject"];
                $contact->message = $data["product"];
//                $contact->landing = $data["landing"];
                $mensagem = $data["subject"];

                $contact->save();
            }

            if ($data["action"] == "landing") {
                $contact = new Newsletter();
                $contact->name = $data["name"];
                $contact->email = $data["email"];
                $contact->phone = $data["phone"];
                $contact->subject = $data["message"];
                $contact->message = $data["message"];
                $contact->landing = $data["landing"];
                $data["redirect"] == "" ? $redirect = url("/confirma") : $redirect = $data["redirect"];

                $mensagem = $contact->message;

                $contact->save();
            }

            $view = new View(__DIR__ . "/../../shared/views/email");
            $message = $view->render("contact", [
                "contact" => $contact,
                "message" => $mensagem
            ]);

            (new Email())->bootstrap(
                "Email do site " . CONF_SITE_NAME . " [{$contact->subject}]",
                $message,
                "contato@paliar.com.br",
                "Site Paliar"
            )->send($contact->email, $contact->name);

            $json['message'] = $this->message->success("Mensagem enviada com sucesso")->render();
            $json['reset'] = true;
            $json['redirect'] = $redirect;
            echo json_encode($json);
            return;
        }

        $json['message'] = $this->message->error("Erro ao enviar, favor entrar em contato com nosso suporte")->render();
        echo json_encode($json);
        return;
    }


    /**
     * SITE PRODUCT SINGLE
     */
    public function product(array $data): void
    {
        $product = (new Product())->findByUri($data["uri"]);
        if (!$product) {
            redirect("/404");
        }
        $productVariation = "";
        $product->views += 1;
        $product->save();
        if ($product->variations != "no-variations" and $product->variations != "") {
            $productVariation = (new ProductVariations())->find(
                "product_id = :gl",
                "gl={$product->gallery_link}"
            )->order("price ASC")->fetch(true);
            $productVariationFirst = (new ProductVariations())->find(
                "product_id = :gl AND stock > 0",
                "gl={$product->gallery_link}"
            )->order("price ASC")->fetch();
        }


        $head = $this->seo->render(
            "{$product->title} - " . CONF_SITE_NAME,
            $product->title,
            url("/produto/{$product->uri}"),
            ($product->cover ? image($product->cover, 1200, 628) : theme("/assets/images/share.jpg"))
        );

        echo $this->view->render("product", [
            "head" => $head,
            "product" => $product,
            "productVariation" => $productVariation,
            "productVariationFirst" => $productVariationFirst,
            "pageTitle" => (object)[],
            "category" => ($product->category()),
            "gallery" => (new Gallery())
                ->find("gallery_link = :g", "g={$product->gallery_link}")
                ->fetch(true),
            "breadcrumb" => (object)[
                [$product->category()->title, url("produto/em/{$product->category()->uri}")],
                [$product->title, ""]
            ],

            "related" => (new Product())
                ->fullSelect(
                    "SELECT p.*, p.title, c.title AS category_title, MIN(pv.price) AS price, pv.promotional_price AS promotional_price, pv.first_variation_item, SUM(pv.stock) as stock
                                                                FROM product_variations pv 
                                                                INNER JOIN products p ON p.gallery_link = pv.product_id 
                                                                INNER JOIN categories c ON c.id = p.category
                                                                WHERE p.category = :c AND p.id != :i 
                                                                GROUP BY pv.product_id 
                                                                HAVING sum(pv.stock) != 0 AND p.status = 'post'",
                    "c={$product->category()->id}&i={$product->id}"
                )
                ->order("p.post_at DESC")
                ->limit(6)
                ->fetch(true)
        ]);
    }

    /**
     * SITE PRODUCT VARIANTS CREATE
     */
    public function productVariants(array $data): void
    {
        $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);


        if (isset($data["action"]) and $data["action"] == "create") {
            $product = (new ProductVariations())->findById($data["id"]);
            if ($product) {
                if ($product->promotional_price > 0) {
//                        $price = '<del class="mr-1">R$ '. preco_real($product->price * ($product->product()->type == 1 ? 6.25 : 1)).'</del><ins>R$ '.preco_real($product->promotional_price * ($product->product()->type == 1 ? 6.25 : 1)).'</ins>';
                    $price = '<del class="mr-1">R$ ' . preco_real($product->price) . '</del><ins>R$ ' . preco_real(
                            $product->promotional_price
                        ) . '</ins>';
                } else {
//                        $price = '<ins>R$ '. preco_real($product->price * ($product->product()->type == 1 ? 6.25 : 1)).'</ins>';
                    $price = '<ins>R$ ' . preco_real($product->price) . '</ins>';
                }
                $json["price"] = $price;
                $json["view"] = $this->view->render(
                    "views/size-select",
                    [
                        "pv" => $product->stock,
                        "size" => $product->first_variation_item,
                        "price" => $product->promotional_price != 0 ? $product->promotional_price : $product->price
                    ]
                );
                echo json_encode($json);
                return;
            }
            $json['message'] = $this->message->error("Erro na requisição, favor tentar mais tarde")->render();
            echo json_encode($json);
            return;
        }

        if (isset($data["action"]) and $data["action"] == "change") {
            $product = (new ProductVariations())->findById($data["id"]);
            if ($product) {
                if ($data["size"] == 1.23 and $data["multiplier"] == 25) {
                    $realPrice = $product->price * CONF_FULL_SIZE_DISCOUNT;
                    $realPromoPrice = $product->promotional_price * CONF_FULL_SIZE_DISCOUNT;
                } else {
                    $realPrice = $product->price;
                    $realPromoPrice = $product->promotional_price;
                }
                if ($product->promotional_price > 0) {
//                        $price = '<del class="mr-1">R$ '. preco_real($product->price * ($product->product()->type == 1 ? 6.25 : 1)).'</del><ins>R$ '.preco_real($product->promotional_price * ($product->product()->type == 1 ? 6.25 : 1)).'</ins>';
                    $price = '<del class="mr-1">R$ ' . preco_real($realPrice) . '</del><ins>R$ ' . preco_real(
                            $realPromoPrice
                        ) . '</ins>';
                } else {
//                        $price = '<ins>R$ '. preco_real($product->price * ($product->product()->type == 1 ? 6.25 : 1)).'</ins>';
                    $price = '<ins>R$ ' . preco_real($realPrice) . '</ins>';
                }
                $json["price"] = $price;
                echo json_encode($json);
                return;
            }
            $json['message'] = $this->message->error("Erro na requisição, favor tentar mais tarde")->render();
            echo json_encode($json);
            return;
        }
        $json['message'] = $this->message->error("Erro na requisição, favor tentar mais tarde")->render();
        echo json_encode($json);
        return;
    }


    /**
     * @param array|null $data
     */
    public function documentSent(?array $data): void
    {
        if (isset($data) and $data["action"] == "create") {
            if (!isset($_FILES) or empty($_FILES)) {
                $json["message"] = $this->message->info("Selecionar um arquivo")->flash();
                $json["reload"] = true;
                echo json_encode($json);
                return;
            }
            if (!empty($_FILES["file"])) {
                if ($_FILES["file"]["size"] / 1000 > 10500) {
                    $json["message"] = $this->message->warning(
                        "Tamanho máximo permitido 10MB favor enviar um arquivo menor"
                    )->flash();
                    $json["reload"] = true;
                    echo json_encode($json);
                    return;
                }

                $verify = (new Files())->find(
                    "enrolment_id = :eid AND document_id = :did",
                    "eid={$data['enrolment_id']}&did={$data['document_id']}"
                );
                $doc = $_FILES["file"];
                $upload = new Upload();
                $title = "arquivo-" . $data["document_id"] . "-" . $data["enrolment_id"];
                $send = $upload->file($doc, $title);

                if (!$send) {
                    $json["message"] = $upload->message()->render();
                    echo json_encode($json);
                    return;
                }
                if ($verify->count() != 0) {
                    $id = $verify->fetch()->id;
                    $files = (new Files())->findById($id);

                    if ($files->file && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$files->file}")) {
                        unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$files->file}");
                    }
                } else {
                    $files = new Files();
                }


                $files->document_id = $data["document_id"];
                $files->enrolment_id = $data["enrolment_id"];

                $files->file = $send;

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

            $json["message"] = $this->message->success("Arquivos Enviado com sucesso")->flash();
            $json["reload"] = true;

            echo json_encode($json);
            return;
        }

        if (isset($data) and $data["action"] == "delete") {
            $files = (new Files())->findById($data["id"]);
            if (!$files) {
                $json["message"] = $this->message->error("Você tentou deletar um arquivo que não existe")->flash();
                $json["reload"] = true;

                echo json_encode($json);
                return;
            }
            if ($files->file && file_exists(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$files->file}")) {
                unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$files->file}");
            }
            $files->destroy();

            $json["message"] = $this->message->success("Arquivo deletado com sucesso")->flash();
            $json["reload"] = true;

            echo json_encode($json);
            return;
        }
    }


    public function filters(?array $data): void
    {
        if (isset($data) and $data["filter_id"] != "") {
            $session = new Session();

            if ($session->has($data["filter_id"])) {
                $session->unset($data["filter_id"]);
            } else {
                $session->set($data["filter_id"], $data["title"]);
            }


            $query = $this->queryFilter();
            if(strlen($query) > 8){
                $query .= " AND";
            }
            $courses = (new Course())->find("{$query} status != 0");




            $json["sidebar"] = $this->view->render("views/sidebar", [
                "modalidade" => (new Filters())->findByType("modalidade")->fetch(true),
                "area" => (new Filters())->findByType("area")->fetch(true),
                "jornada" => (new Filters())->findByType("jornada")->fetch(true),
                "formato" => (new Filters())->findByType("formato")->fetch(true),
                "session" => $session
            ]);

            $json["courses"] = $this->view->render("views/courses", [
                "courses" => $courses->order("ordenation ASC, title DESC")->fetch(true),
            ]);


            echo json_encode($json);
            return;
        }
    }

    public function queryFilter(): string
    {
        $session = new Session();

        $filterModalidade = (new Filters())->find("type = :type", "type=modalidade")->fetch(true);
        $filterJornada = (new Filters())->find("type = :type", "type=jornada")->fetch(true);
        $filterFormato = (new Filters())->find("type = :type", "type=formato")->fetch(true);
        $filterArea = (new Filters())->find("type = :type", "type=area")->fetch(true);

        //CONTROLE DE MODALIDADE
        $queryM = "(";
        $m = 0;
        $x = 1;
        foreach ($filterModalidade as $filter) {
            if ($session->has($filter->filter_id)) {
                if ($m >= $x) {
                    $x++;
                    $queryM .= " OR ";
                }
                $queryM .= "filter_modalidade LIKE '%$filter->title%'";
                $m++;
            }
        }

        if (strlen($queryM) > 8) {
            $queryM .= ")";
        } else {
            $queryM = "";
        }

        //CONTROLE DE JORNADA
        if (strlen($queryM) > 8) {
            $queryJ = " AND (";
        } else {
            $queryJ = "(";
        }
        $m = 0;
        $x = 1;
        foreach ($filterJornada as $filter) {
            if ($session->has($filter->filter_id)) {
                if ($m >= $x) {
                    $x++;
                    $queryJ .= " OR ";
                }
                $queryJ .= "filter_jornada LIKE '%$filter->title%'";
                $m++;
            }
        }

        if (strlen($queryJ) > 8) {
            $queryJ .= ")";
        } else {
            $queryJ = "";
        }
        //CONTROLE DE FORMATO
        if (strlen($queryM) > 8 or strlen($queryJ) > 8) {
            $queryF = " AND (";
        } else {
            $queryF = "(";
        }
        $m = 0;
        $x = 1;
        foreach ($filterFormato as $filter) {
            if ($session->has($filter->filter_id)) {
                if ($m >= $x) {
                    $x++;
                    $queryF .= " OR ";
                }
                $queryF .= "filter_formato LIKE '%$filter->title%'";
                $m++;
            }
        }
        if (strlen($queryF) > 8) {
            $queryF .= ")";
        } else {
            $queryF = "";
        }

        //CONTROLE DE AREA
        if (strlen($queryM) > 8 or strlen($queryJ) > 8 or strlen($queryF) > 8) {
            $queryA = " AND (";
        } else {
            $queryA = "(";
        }
        $m = 0;
        $x = 1;
        foreach ($filterArea as $filter) {
            if ($session->has($filter->filter_id)) {
                if ($m >= $x) {
                    $x++;
                    $queryA .= " OR ";
                }
                $queryA .= "filter_area LIKE '%$filter->title%'";
                $m++;
            }
        }
        if (strlen($queryA) > 8) {
            $queryA .= ")";
        } else {
            $queryA = "";
        }
        $query = $queryM . $queryJ . $queryF . $queryA;

        return $query;
    }

    /**
     * SITE CURSOS
     * @param array|null $data
     */
    public function courses(?array $data): void
    {
        $head = $this->seo->render(
            "Cursos - " . CONF_SITE_NAME,
            "Confira os melhores cursos de cuidados paliativos, pós graduação, especialização e aperfeiçoamento em cuidados paliativos",
            url("/cursos"),
            theme("/assets/images/share.jpg")
        );
        $query = $this->queryFilter();

        if(strlen($query) > 8){
            $query .= " AND";
        }

        $courses = (new Course())->find("{$query} status != 0");

//        $pager = new Pager(url("/cursos/p/"));
//        $pager->pager($courses->count(), 12, ($data['page'] ?? 1));

        echo $this->view->render("course", [
            "head" => $head,
//            "courses" => $courses->limit($pager->limit())->offset($pager->offset())->order("ordenation ASC, title DESC")->fetch(true),
            "courses" => $courses->order("ordenation ASC, title DESC")->fetch(true),
            "area" => (new Filters())->findByType("area")->fetch(true),
            "modalidade" => (new Filters())->findByType("modalidade")->fetch(true),
            "jornada" => (new Filters())->findByType("jornada")->fetch(true),
            "formato" => (new Filters())->findByType("formato")->fetch(true),
            "pageTitle" => (object)[
                "title" => "Nossos Cursos",
                "subtitle" => "Cursos " . CONF_SITE_NAME,
                "image" => url("images/slide-bg.jpg"),

            ],
            "breadcrumb" => (object)[
                ["Cursos", "#"]
            ],
//            "paginator" => $pager->render("pagination pagination-rounded"),
            "session" => new Session()
        ]);
    }

    /**
     * SITE COURSE
     * @param array $data
     */
    public function singleCourses(array $data): void
    {
        $course = (new Course())->findByUri($data['uri']);
        if (!$course) {
            redirect("/404");
        }

        $user = Auth::user();
        if (!$user || $user->level < 5) {
            $course->views += 1;
            $course->save();
        }

        $head = $this->seo->render(
            "{$course->title} - " . CONF_SITE_NAME,
            $course->subtitle,
            url("/cursos/{$course->uri}"),
            ($course->cover ? image($course->cover, 1200, 628) : theme("/assets/images/share.jpg"))
        );

        echo $this->view->render("singlecourse", [
            "head" => $head,
            "course" => $course,
            "pageTitle" => (object)[
                "title" => $course->title,
                "subtitle" => $course->subtitle,
                "image" => url("images/slide-bg.jpg"),
                "modalidade" => $course->filter_modalidade,
                "formato" => $course->filter_formato,

            ],
            "breadcrumb" => (object)[
                [$course->title, "#"]
            ],
            "relatedA" => (new Course())
                ->find("status != 0 AND id != :i", "i={$course->id}")
                ->order("id DESC")
                ->limit(3)->offset(0)
                ->fetch(true),
            "locations" => (new Locations())
                ->find("course_id = :i", "i={$course->id}")
                ->order("local DESC")
                ->fetch(true),
        ]);
    }


    /**
     * SITE ENROLMENT
     * @param array $data
     */
    public function enrolment(array $data): void
    {
        $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
        $course = (new Course())->find("id = :id", "id={$data['id']}")->fetch();
        if (!$course or $course->enrolment != 1) {
            $this->message->error("Curso não encontrado ou com matrículas encerradas!")->flash();
            redirect("/404");
        }

        $head = $this->seo->render(
            "Matrícula em:  {$course->title} - " . CONF_SITE_NAME,
            $course->subtitle,
            url("/cursos/{$course->uri}"),
            ($course->cover ? image($course->cover, 1200, 628) : theme("/assets/images/share.jpg"))
        );

        echo $this->view->render("enrolment", [
            "head" => $head,
            "course" => $course,
            "pageTitle" => (object)[
                "title" => "Matrícula Paliar",
                "subtitle" => $course->title,
            ],
            "breadcrumb" => (object)[
                ["Matrícula", "#"]
            ],
            "locations" => (new Locations())
                ->find("course_id = :i", "i={$course->id}")
                ->order("local DESC")
                ->fetch(true),
        ]);
    }

    public function registry(array $data): void
    {
        $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);

        if (
            empty($data["address"]) or
            empty($data["city"]) or
            empty($data["state"]) or
            empty($data["document"]) or
            empty($data["document2"]) or
            empty($data["zipcode"]) or
            empty($data["neighborhood"])
        ) {
            $json['message'] = $this->message->warning("Campos com * São de preenchimento obrigatório")->render();
            echo json_encode($json);
            return;
        }
        if (isset($data["action"]) and $data["action"] == "create") {
            $editClient = null;
            if (!empty($data["client_id"])) {
                $clientId = filter_var($data["client_id"], FILTER_VALIDATE_INT);
                $editClient = (new Client())->findById($clientId);
                $editClient->name = $data["name"];
                $editClient->document2 = str_replace([".", "-"], "", $data["document2"]);
                $editClient->document = str_replace([".", "-"], "", $data["document"]);
                $editClient->email = strtolower($data["email"]);
                $editClient->phone = $data["phone"];
                $editClient->address = $data["address"];
                $editClient->zipcode = $data["zipcode"];
                $editClient->complement = $data["complement"];
                $editClient->city = $data["city"];
                $editClient->state = $data["state"];
                $editClient->neighborhood = $data["neighborhood"];
                if (!$editClient->save()) {
                    $json["message"] = $editClient->message()->render();
                    echo json_encode($json);
                    return;
                }
                $verifyEnrolment = (new Enrolment())->find(
                    "client_id = :client_id AND course_id = :course_id",
                    "client_id={$clientId}&course_id={$data["course_id"]}"
                );
                if ($verifyEnrolment->count() != 0) {
                    $json['message'] = $this->message->info(
                        "Você já está cadastrado neste curso, aguarde contato de nossa equipe ou nos ligue para tirar dúvidas"
                    )->render();
                    echo json_encode($json);
                    return;
                }
                $createEnrolment = new Enrolment();
                $createEnrolment->course_id = ((int)$data["course_id"]);
                $createEnrolment->client_id = ((int)$clientId);
                $createEnrolment->price = $data["price"];
                $createEnrolment->payment_type = $data["payment_type"];
                $createEnrolment->document_complete = 0;

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

                //envia email
                $view = new View(__DIR__ . "/../../shared/views/email");
                $message = $view->render("contact-client", [
                    "name" => $data["name"],
                    "course" => $data['course_name'],
                    "enrolment" => $enrolmentId
                ]);

                (new Email())->bootstrap(
                    "Matrícula " . CONF_SITE_NAME . " [{$data['course_name']}]",
                    $message,
                    $data["email"],
                    $data["name"]
                )->send($data["email"], "Matrículas Paliar");

                $json['message'] = $this->message->success("Matrícula Realizada com Sucesso")->flash();
                $json["redirect"] = url("/cursos/documentos/{$enrolmentId}-{$clientId}");
                echo json_encode($json);
                return;
            } else {
                $verificaEmailCpf = (new Client())->find(
                    "email = :email AND (document IS NOT NULL OR document != '')",
                    "email={$data['email']}"
                );
                $verificaEmail = (new Client())->find(
                    "email = :email AND (document IS NULL OR document = '')",
                    "email={$data['email']}"
                );

                $cId = '';
                if ($verificaEmailCpf->count() != 0) {
                    $json['message'] = $this->message->info(
                        "Email já cadastrado em outro CPF, cadastre outro email."
                    )->render();
                    echo json_encode($json);
                    return;
                } elseif ($verificaEmail->count() != 0) {
                    $client = $verificaEmail->fetch();
                    $createClient = (new Client())->findById($client->id);
                    $cId = $client->id;
                } else {
                    $createClient = new Client();
                }

                $createClient->name = $data["name"];
                $createClient->document2 = str_replace([".", "-"], "", $data["document2"]);
                $createClient->document = str_replace([".", "-"], "", $data["document"]);
                $createClient->email = strtolower($data["email"]);
                $createClient->phone = $data["phone"];
                $createClient->address = $data["address"];
                $createClient->zipcode = $data["zipcode"];
                $createClient->complement = $data["complement"];
                $createClient->city = $data["city"];
                $createClient->state = $data["state"];
                $createClient->neighborhood = $data["neighborhood"];

                if (!$createClient->save()) {
                    $json["message"] = $createClient->message()->render();
                    echo json_encode($json);
                    return;
                }
                $clientId = $cId != '' ? $cId : $createClient->saveId();
                $createEnrolment = new Enrolment();
                $createEnrolment->course_id = ((int)$data["course_id"]);
                $createEnrolment->client_id = ((int)$clientId);
                $createEnrolment->price = $data["price"];
                $createEnrolment->payment_type = $data["payment_type"];
                $createEnrolment->document_complete = 0;
                if (!$createEnrolment->save()) {
                    $json["message"] = $createEnrolment->message()->render();
                    echo json_encode($json);
                    return;
                }
                $enrolmentId = $createEnrolment->saveId();

                //envia email
                $view = new View(__DIR__ . "/../../shared/views/email");
                $message = $view->render("contact-client", [
                    "name" => $data["name"],
                    "course" => $data['course_name'],
                    "enrolment" => $enrolmentId
                ]);

                (new Email())->bootstrap(
                    "Matrícula - " . CONF_SITE_NAME . " [{$data['course_name']}]",
                    $message,
                    $data["email"],
                    $data["name"]
                )->send($data["email"], "Matrículas Paliar");

                $json['message'] = $this->message->success("Matrícula Realizada com Sucesso")->flash();
                $json["redirect"] = url("/cursos/documentos/{$enrolmentId}-{$clientId}");
                echo json_encode($json);
                return;
            }
            if (isset($data["client_id"]) and $data["client_id"] != "") {
                $editClient = (new Client())->find("id = :id", "id={$data['client_id']}");
                var_dump($editClient->fetch());
                return;
            }
        }
        $course = (new Course())->find("id = :id", "id={$data['id']}")->fetch();
        if (!$course or $course->enrolment != 1) {
            $this->message->error("Curso não encontrado ou com matrículas encerradas!")->flash();
            redirect("/404");
        }
    }


    /**
     * SITE ENROLMENT
     * @param array $data
     */
    public function enrolmentDocuments(array $data): void
    {
        $ids = filter_var_array(explode("-", $data["ids"]), FILTER_SANITIZE_STRIPPED);
        $enrolmentId = $ids[0];
        $clientId = $ids[1];

        $verifyEnrolment = (new Enrolment())->find(
            "id = :id AND client_id = :cid AND status != 5 AND status != 6",
            "id={$enrolmentId}&cid={$clientId}"
        )->fetch();

        if ($verifyEnrolment) {
            $course = (new Course())->find("id = :id", "id={$verifyEnrolment->course_id}")->fetch();

            if (!$course) {
                $this->message->error("Curso não encontrado ou com matrículas encerradas!")->flash();
                redirect("/404");
            }

            $enrolment = (new Enrolment())->findById($enrolmentId);

            $percentual = $this->verifyPercentual($enrolment->course_id, $enrolment->id);
            if ($percentual >= 100 and $enrolment->document_complete != 1) {
                $enrolment->document_complete = 1;
                $enrolment->save();
            }

            if (!$enrolment) {
                redirect("admin/error/404");
            }
            $origin = 'enrolment';
            $activity = (new Activity())->find(
                "item_id = :itemid AND origin = :origin",
                "itemid={$enrolmentId}&origin={$origin}"
            );


            $head = $this->seo->render(
                "Matrícula em:  {$course->title} - " . CONF_SITE_NAME,
                $course->subtitle,
                url("/cursos/{$course->uri}"),
                ($course->cover ? image($course->cover, 1200, 628) : theme("/assets/images/share.jpg"))
            );

            echo $this->view->render("enrolment-documents", [
                "head" => $head,
                "course" => $course,
                "activity" => $activity->order("id DESC")->fetch(true),
                "documents" => (new CourseDocuments())->find("course_id = :cid", "cid={$enrolment->course_id}")->fetch(
                    true
                ),
                "percentual" => $percentual,
                "enrolment" => $verifyEnrolment,
                "pageTitle" => (object)[
                    "title" => "Matrícula Paliar",
                    "subtitle" => $course->title,
                ],
                "breadcrumb" => (object)[
                    ["Matrícula", "#"]
                ],
                "locations" => (new Locations())
                    ->find("course_id = :i", "i={$course->id}")
                    ->order("local DESC")
                    ->fetch(true),
            ]);
        } else {
            $this->message->error("Problema com seus dados informe o suporte!")->flash();
            redirect("/404");
        }
    }

    public function verifyPercentual(int $courseId, int $enrolmentId)
    {
        $countDocuments = (new CourseDocuments())->find("course_id = {$courseId}");
        $countFiles = (new Files())->find("enrolment_id = {$enrolmentId}");

        if ($countDocuments->count() == 0 and $countDocuments->count() == 0) {
            return 0;
        } else {
            $percentual = ($countFiles->count() / $countDocuments->count()) * 100;
            return $percentual;
        }
    }

    public function preRegistry(array $data): void
    {
        $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);


        if (isset($data["action"]) and $data["action"] == "create") {
            $editClient = null;

            //RECAPTCHA
            if (empty($data['g-recaptcha-response']) || $data["g-recaptcha-response"] == null) {
                $json['message'] = $this->message->error("Botão não sou um robo não selecionado")->render();
                echo json_encode($json);
                return;
            }

            //VERIFICA RECAPTCHA
            $recaptcha = new RecaptchaV2();
            if ($recaptcha->isValid($data["g-recaptcha-response"]) == false) {
                $json['message'] = $this->message->error("Recaptcha não autorizado")->render();
                echo json_encode($json);
                return;
            }

            $verificaEmail = (new Client())->find("email = :email", "email={$data['email']}");
            if ($verificaEmail->count() != 0) {
                $editClient = $verificaEmail->fetch();
                $editClient->name = $data["name"];
                $editClient->email = $data["email"];
                $editClient->phone = $data["phone"];
                $clientId = $editClient->id;
                if (!$editClient->save()) {
                    $json["message"] = $editClient->message()->render();
                    echo json_encode($json);
                    return;
                }
            } else {
                $createClient = new Client();
                $createClient->name = $data["name"];
                $createClient->email = strtolower($data["email"]);
                $createClient->phone = $data["phone"];

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

            $verifyEnrolment = (new Enrolment())->find("client_id = {$clientId} AND course_id = {$data["course_id"]}");
            if ($verifyEnrolment->count() != 0) {
                $json['message'] = $this->message->info(
                    "Seu email já consta neste curso, nossa equipe entrará em contato."
                )->flash();
                $json['reload'] = true;
                echo json_encode($json);
                return;
            }

            $createEnrolment = new Enrolment();
            $createEnrolment->course_id = ((int)$data["course_id"]);
            $createEnrolment->client_id = ((int)$clientId);
            $createEnrolment->status = 5;
            if (!$createEnrolment->save()) {
                $json["message"] = $createEnrolment->message()->render();
                echo json_encode($json);
                return;
            }
//                $enrolmentId = $createEnrolment->saveId();
//
//                //envia email
//                $view = new View(__DIR__ . "/../../shared/views/email");
//                $message = $view->render("contact-client", [
//                    "name" => $data["name"], "course" => $data['course_name'], "enrolment" => $enrolmentId
//                ]);
//
//                (new Email())->bootstrap(
//                    "Matrícula " . CONF_SITE_NAME . " [{$data['course_name']}]",
//                    $message,
//                    $data["email"], $data["name"]
//                )->send($data["email"], "Matrículas Paliar");

            $json['message'] = $this->message->success(
                "Cadastro Realizado com Sucesso, nossa equipe entrará em contato em breve"
            )->flash();
            $json["redirect"] = url("/confirma");
            echo json_encode($json);
            return;


            if (isset($data["client_id"]) and $data["client_id"] != "") {
                $editClient = (new Client())->find("id = :id", "id={$data['client_id']}");
                var_dump($editClient->fetch());
                return;
//

            }
        }
        $course = (new Course())->find("id = :id", "id={$data['id']}")->fetch();
        if (!$course or $course->enrolment != 1) {
            $this->message->error("Curso não encontrado ou com matrículas encerradas!")->flash();
            redirect("/404");
        }
    }


    public function verifyClient($data)
    {
        sleep(1);

        $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
        if (isset($data["document"]) and $data["document"] != "") {
            if (is_cpf($data["document"])) {
                $document = str_replace([".", "-"], "", $data["document"]);
                $client = (new Client())->find("document = :cpf", "cpf={$document}");
                if ($client->count() != 0) {
                    $res = $client->fetch();
                    $json['result'] = "client";
                    $json['client'] = [
                        "id" => $res->id,
                        "name" => $res->name,
                        "email" => $res->email,
                        "phone" => $res->phone,
                        "address" => $res->address,
                        "state" => $res->state,
                        "neighborhood" => $res->neighborhood,
                        "document2" => $res->document2,
                        "zipcode" => $res->zipcode,
                        "city" => $res->city
                    ];

                    echo json_encode($json);
//                    var_dump($res);
                    return;
                } else {
                    $json['result'] = "no-client";
                    echo json_encode($json);
                    return;
                }
            } else {
                $json['result'] = "mensagem";
                $json['message'] = $this->message->warning("CPF Inválido")->render();
                echo json_encode($json);
                return;
            }
        } else {
            $json['result'] = "mensagem";
            $json['message'] = $this->message->error("Erro na requisição")->render();
            echo json_encode($json);
            return;
        }
    }

    /**
     * SITE BLOG
     * @param array|null $data
     */
    public function blog(?array $data): void
    {
        $head = $this->seo->render(
            "Blog - " . CONF_SITE_NAME,
            "Confira em nosso blog dicas e sacadas de como controlar melhorar suas contas. Vamos tomar um café?",
            url("/blog"),
            theme("/assets/images/share.jpg")
        );

        $blog = (new Post())->findPost();
        $pager = new Pager(url("/blog/p/"));
        $pager->pager($blog->count(), 12, ($data['page'] ?? 1));

        echo $this->view->render("blog", [
            "head" => $head,
            "blog" => $blog->order("post_at DESC")->limit($pager->limit())->offset($pager->offset())->fetch(true),
            "pageTitle" => (object)[
                "title" => "Últimas Novidades",
                "subtitle" => "Acompanhe as Novidades " . CONF_SITE_NAME,
                "image" => url("images/slide-bg.jpg"),

            ],
            "breadcrumb" => (object)[
                ["Blog", "#"]
            ],
            "paginator" => $pager->render()
        ]);
    }


    /**
     * SITE BLOG SEARCH
     * @param array $data
     */
    public function blogSearch(array $data): void
    {
        if (!empty($data['s'])) {
            $search = str_search($data['s']);
            echo json_encode(["redirect" => url("/blog/buscar/{$search}/1")]);
            return;
        }

        $search = str_search($data['search']);
        $page = (filter_var($data['page'], FILTER_VALIDATE_INT) >= 1 ? $data['page'] : 1);

        if ($search == "all") {
            redirect("/blog");
        }

        $head = $this->seo->render(
            "Pesquisa por {$search} - " . CONF_SITE_NAME,
            "Confira os resultados de sua pesquisa para {$search}",
            url("/blog/buscar/{$search}/{$page}"),
            theme("/assets/images/share.jpg")
        );

        $blogSearch = (new Post())->findPost("MATCH(title, subtitle) AGAINST(:s)", "s={$search}");

        if (!$blogSearch->count()) {
            echo $this->view->render("blog", [
                "head" => $head,
                "title" => "PESQUISA POR:",
                "search" => $search
            ]);
            return;
        }

        $pager = new Pager(url("/blog/buscar/{$search}/"));
        $pager->pager($blogSearch->count(), 9, $page);

        echo $this->view->render("blog", [
            "head" => $head,
            "title" => "PESQUISA POR:",
            "search" => $search,
            "blog" => $blogSearch->limit($pager->limit())->offset($pager->offset())->fetch(true),
            "paginator" => $pager->render()
        ]);
    }

    /**
     * SITE BLOG POST
     * @param array $data
     */
    public function blogPost(array $data): void
    {
        $post = (new Post())->findByUri($data['uri']);
        if (!$post) {
            redirect("/404");
        }

        $user = Auth::user();
        if (!$user || $user->level < 5) {
            $post->views += 1;
            $post->save();
        }

        $head = $this->seo->render(
            "{$post->title} - " . CONF_SITE_NAME,
            $post->subtitle,
            url("/blog/{$post->uri}"),
            ($post->cover ? image($post->cover, 1200, 628) : theme("/assets/images/share.jpg"))
        );

        echo $this->view->render("blog-post", [
            "head" => $head,
            "post" => $post,
            "category" => (new Category())->find("id >= :id", "id={$post->category}")->fetch(),
            "author" => (new User())->find("id >= :id", "id={$post->author}")->fetch(),
            "pageTitle" => (object)[
                "title" => $post->title,
                "subtitle" => "",
                "image" => url("images/slide-bg.jpg"),

            ],
            "breadcrumb" => (object)[
                [$post->category()->title, "#"],
                [$post->title, "#"]
            ],
            "relatedA" => (new Post())
                ->findPost("category = :c AND id != :i", "c={$post->category}&i={$post->id}")
                ->order("post_at DESC")
                ->limit(2)->offset(0)
                ->fetch(true),
            "relatedB" => (new Post())
                ->findPost("category = :c AND id != :i", "c={$post->category}&i={$post->id}")
                ->order("post_at DESC")
                ->limit(2)->offset(2)
                ->fetch(true),
            "gallery" => (new Gallery())
                ->find("gallery_link = :g", "g={$post->gallery_link}")
                ->fetch(true),
        ]);
    }

    /**
     * SITE LOGIN
     * @param null|array $data
     */
    public function login(?array $data): void
    {
//            if (!csrf_verify_alt($data)) {
//                $json['message'] = $this->message->error("Erro ao enviar, favor use o formulário")->render();
//                echo json_encode($json);
//                return;
//            }

        if (request_limit("weblogin", 5, 60 * 3)) {
            $json['message'] = $this->message->error(
                "Você já efetuou 5 tentativas, esse é o limite. Por favor, aguarde 3 minutos para tentar novamente!"
            )->render();
            echo json_encode($json);
            return;
        }

        if (empty($data['email']) || empty($data['password'])) {
            $json['message'] = $this->message->warning("Informe seu email e senha para entrar")->render();
            echo json_encode($json);
            return;
        }

        $save = (!empty($data['save']) ? true : false);
        $auth = new Auth();
        $login = $auth->login($data['email'], $data['password'], $save);

        if ($login) {
            $this->message->success("Seja bem-vindo(a) de volta " . Auth::user()->first_name . "!")->flash();
            $json['redirect'] = $data['destino'] ? url($data['destino']) : url("/restrito");
        } else {
            $json['message'] = $auth->message()->before("Ooops! ")->render();
        }

        echo json_encode($json);
        return;
    }

    /**
     * SITE PASSWORD FORGET
     * @param null|array $data
     */
    public function forget(?array $data)
    {
        if (Auth::user()) {
            redirect("/");
        }

        if (!empty($data['csrf'])) {
            if (!csrf_verify($data)) {
                $json['message'] = $this->message->error("Erro ao enviar, favor use o formulário")->render();
                echo json_encode($json);
                return;
            }

            if (empty($data["email"])) {
                $json['message'] = $this->message->info("Informe seu e-mail para continuar")->render();
                echo json_encode($json);
                return;
            }

            if (request_repeat("webforget", $data["email"])) {
                $json['message'] = $this->message->error("Ooops! Você já tentou este e-mail antes")->render();
                echo json_encode($json);
                return;
            }

            $auth = new Auth();
            if ($auth->forget($data["email"])) {
                $json["message"] = $this->message->success("Acesse seu e-mail para recuperar a senha")->render();
            } else {
                $json["message"] = $auth->message()->before("Ooops! ")->render();
            }

            echo json_encode($json);
            return;
        }

        $head = $this->seo->render(
            "Recuperar Senha - " . CONF_SITE_NAME,
            CONF_SITE_DESC,
            url("/recuperar"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("auth-forget", [
            "head" => $head,
            "pageTitle" => (object)[
                "title" => "Recuperar Senha",
                "subtitle" => "Qual seu email cadastrado?",
            ],
            "breadcrumb" => (object)[
                ["Recuperar Senha", "#"]
            ]
        ]);
    }

    /**
     * SITE FORGET RESET
     * @param array $data
     */
    public function reset(array $data): void
    {
        if (Auth::user()) {
            redirect("/app");
        }

        if (!empty($data['csrf'])) {
            if (!csrf_verify($data)) {
                $json['message'] = $this->message->error("Erro ao enviar, favor use o formulário")->render();
                echo json_encode($json);
                return;
            }

            if (empty($data["password"]) || empty($data["password_re"])) {
                $json["message"] = $this->message->info("Informe e repita a senha para continuar")->render();
                echo json_encode($json);
                return;
            }

            list($email, $code) = explode("|", $data["code"]);
            $auth = new Auth();

            if ($auth->reset($email, $code, $data["password"], $data["password_re"])) {
                $this->message->success("Senha alterada com sucesso. Vamos controlar?")->flash();
                $json["reload"] = true;
            } else {
                $json["message"] = $auth->message()->before("Ooops! ")->render();
            }

            echo json_encode($json);
            return;
        }

        $head = $this->seo->render(
            "Crie sua nova senha no " . CONF_SITE_NAME,
            CONF_SITE_DESC,
            url("/recuperar"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("auth-reset", [
            "head" => $head,
            "code" => $data["code"],
            "pageTitle" => (object)[
                "title" => "Nova Senha",
                "subtitle" => "Cadastre uma nova senha",
            ],
            "breadcrumb" => (object)[
                ["Nova Senha", "#"]
            ]
        ]);
    }

    /**
     * SITE REGISTER
     * @param null|array $data
     */
    public function register(?array $data): void
    {
        if (Auth::user()) {
            redirect("/");
        }

        if (!empty($data['csrf'])) {
            if (!csrf_verify($data)) {
                $json['message'] = $this->message->error("Erro ao enviar, favor use o formulário")->render();
                echo json_encode($json);
                return;
            }

            if ($data["password"] != $data["verify_password"]) {
                $json['message'] = $this->message->warning("Senhas devem ser iguais")->render();
                echo json_encode($json);
                return;
            }

            $auth = new Auth();
            $user = new User();
            $user->bootstrap(
                $data["first_name"],
                $data["last_name"],
                $data["email"],
                $data["password"],
                $data["document"],
                $data["phone"],
                $data["datebirth"],
                $data["type"],
                $data["document2"],
                $data["celular"]
            );

            if ($auth->register($user)) {
                $login = $auth->login($data['email'], $data['password'], false);

                if ($login) {
                    $this->message->success("Seja bem-vindo " . Auth::user()->first_name . "!")->flash();
                    $json['redirect'] = url($data["destino"]);
                } else {
                    $json['message'] = $auth->message()->before("Ooops! ")->render();
                }
                echo json_encode($json);
                return;
            } else {
                $json['message'] = $auth->message()->before("Ooops! ")->render();
            }

            echo json_encode($json);
            return;
        }

        $head = $this->seo->render(
            "Criar Conta - " . CONF_SITE_NAME,
            CONF_SITE_DESC,
            url("/cadastrar"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("auth-register", [
            "head" => $head,
            "pageTitle" => (object)[
                "title" => "Cadastrar",
                "subtitle" => "Faça seu cadastro",
            ],
            "breadcrumb" => (object)[
                ["Cadastro", "#"]
            ]
        ]);
    }

    /**
     * SITE RESTRICTED
     * @param null|array $data
     */
    public function restricted(?array $data): void
    {
        if (!Auth::user()) {
            redirect("/");
        }
        $variableData = null;
        $variableData2 = null;
        $page = filter_var($data["page"], FILTER_SANITIZE_STRIPPED);
        if ($page == "") {
            $render = "views/restricted/home";
            $title = "Bem Vinda(o) " . user()->fullName();
            $breadcrumb = (object)[["Minha Conta", "#"]];
            $selected = "restrito/";
            $variableData = new Orders();
            $uid = \user()->data()->id;
            $variableData = $variableData->find("user_id = :uid", "uid={$uid}")->order("id DESC")->limit(3)->fetch(
                true
            );
            $variableData2 = new Orders();
            $variableData2 = $variableData2->find(
                "partner_id = :pid AND partner_payment = 0 AND status = 'paid'",
                "pid={$uid}"
            )->fetch(true);
        }
        if ($page == "perfil") {
            $render = "views/restricted/profile";
            $title = "Seu Perfil";
            $breadcrumb = (object)[["Minha Conta", url("restrito")], ["Perfil", "#"]];
            $selected = "restrito/perfil";
        }
        if ($page == "login") {
            $render = "views/restricted/login";
            $title = "Dados de Login";
            $breadcrumb = (object)[["Minha Conta", url("restrito")], ["Segurança", "#"]];
            $selected = "restrito/login";
        }
        if ($page == "enderecos") {
            $render = "views/restricted/adress";
            $title = "Meus Endereços";
            $breadcrumb = (object)[["Minha Conta", url("restrito")], ["Endereços", "#"]];
            $selected = "restrito/enderecos";
            $variableData = new Address();
            $uid = \user()->data()->id;
            $variableData = $variableData->find("user_id = :uid", "uid={$uid}")->fetch(true);
        }
        if ($page == "pedidos") {
            $render = "views/restricted/invoices";
            $title = "Meus Pedidos";
            $breadcrumb = (object)[["Minha Conta", url("restrito")], ["Pedidos", "#"]];
            $variableData = new Orders();
            $uid = \user()->data()->id;
            $variableData = $variableData->find("user_id = :uid", "uid={$uid}")->fetch(true);
            $selected = "restrito/pedidos";
        }
        if ($page == "cartoes") {
            $render = "views/restricted/billing";
            $title = "Cartões";
            $breadcrumb = (object)[["Minha Conta", url("restrito")], ["Cartões", "#"]];
            $selected = "restrito/cartoes";
            $variableData = new CreditCard();
            $uid = \user()->data()->id;
            $variableData = $variableData->find("user_id = :uid", "uid={$uid}")->fetch(true);
        }


        $head = $this->seo->render(
            "Meu Perfil - " . CONF_SITE_NAME,
            CONF_SITE_DESC,
            url("/restrito"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("user-area", [
            "head" => $head,
            "selected" => $selected,
            "render" => $render,
            "variableData" => $variableData,
            "variableData2" => $variableData2,
            "pageTitle" => (object)[
                "title" => $title,
                "subtitle" => user()->fullName(),
            ],
            "breadcrumb" => $breadcrumb
        ]);
    }

    /**
     * @param array $data
     */
    public function order(array $data): void
    {
        if (!Auth::user()) {
            redirect("/");
        }
        $order_id = filter_var($data["order_id"], FILTER_SANITIZE_STRIPPED);
        $order = (new Orders())->findById($order_id);
        $itens = (new OrderItens())->find("order_id = :order_id", "order_id={$order->id}")->fetch(true);

        $head = $this->seo->render(
            "Pedido - [#" . order_id($order->id) . "] | " . CONF_SITE_NAME,
            CONF_SITE_DESC,
            url("/restrito/"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("order", [
            "head" => $head,
            "selected" => "restrito/pedidos",
            "itens" => $itens,
            "order" => $order,
            "pageTitle" => (object)[
                "title" => "Pedido",
                "subtitle" => user()->fullName(),
            ],
            "breadcrumb" => (object)[["Minha Conta", url("restrito")], ["Pedidos", "#"]]
        ]);
    }

    public function userType(?array $data): void
    {
        if (!empty($data)) {
            if (is_cpf($data['document'])) {
                $json["result"] = 1;
                $json["html"] = $this->view->render("views/fragments/cpf", []);

                echo json_encode($json);
                return;
            }

            if (is_cnpj($data['document'])) {
                $json["result"] = 2;
                $json["html"] = $this->view->render("views/fragments/cnpj", []);

                echo json_encode($json);
                return;
            }
            $json["result"] = 3;
            $json["message"] = $this->message->warning("Documento Inválido, digitar CPF ou CNPJ")->render();
            echo json_encode($json);
            return;
        }
    }


    /**
     * @param array $data
     */
    public function profile(array $data): void
    {
        if (!empty($data['csrf'])) {
            if (!csrf_verify($data)) {
                $json['message'] = $this->message->error("Erro ao enviar, favor use o formulário")->render();
                echo json_encode($json);
                return;
            }
            if (isset($data) and $data["action"] == "profile") {
                $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
                $userUpdate = (new User())->findById($data["id"]);
                if (!$userUpdate) {
                    $this->message->error("Você tentou gerenciar um usuário que não existe")->flash();
                    echo json_encode(["redirect" => url("/")]);
                    return;
                }
                $userUpdate->first_name = $data["first_name"];
                $userUpdate->last_name = $data["last_name"];
                $userUpdate->email = $userUpdate->email;
                $userUpdate->password = (!empty($data["password"]) ? $data["password"] : $userUpdate->password);
                //$userUpdate->genre = $data["genre"];
                $userUpdate->datebirth = date_fmt_back($data["datebirth"]);
                $userUpdate->document = preg_replace("/[^0-9]/", "", $data["document"]);
                $userUpdate->about = $data["about"];
                $userUpdate->document2 = $data["document2"];
                $userUpdate->type = $data["type"];
                $userUpdate->phone = $data["phone"];
                $userUpdate->celular = $data["celular"];
                //upload photo
                if (!empty($_FILES["photo"])) {
                    if ($userUpdate->photo && file_exists(
                            __DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$userUpdate->photo}"
                        )) {
                        unlink(__DIR__ . "/../../../" . CONF_UPLOAD_DIR . "/{$userUpdate->photo}");
                        (new Thumb())->flush($userUpdate->photo);
                    }
                    $files = $_FILES["photo"];
                    $upload = new Upload();
                    $image = $upload->image($files, $userUpdate->fullName(), 600);
                    if (!$image) {
                        $json["message"] = $upload->message()->render();
                        echo json_encode($json);
                        return;
                    }
                    $userUpdate->photo = $image;
                }
                if (!$userUpdate->save()) {
                    $json["message"] = $userUpdate->message()->render();
                    echo json_encode($json);
                    return;
                }
                $this->message->success("Usuário atualizado com sucesso...")->flash();
                echo json_encode(["redirect" => url("restrito/perfil")]);
                return;
            }

            if (isset($data) and $data["action"] == "login") {
                $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
                $userUpdate = (new User())->findById($data["id"]);
                if (!$userUpdate) {
                    $this->message->error("Você tentou gerenciar um usuário que não existe")->flash();
                    echo json_encode(["redirect" => url("/")]);
                    return;
                }
                if (!isset($data["password"]) or $data["password"] == "" or !isset($data["re_password"]) or $data["re_password"] == "") {
                    $json['message'] = $this->message->error(
                        "Você Precisa digitar uma senha e confirmar a mesma"
                    )->render();
                    echo json_encode($json);
                    return;
                }
                if ($data["re_password"] != $data["password"]) {
                    $json['message'] = $this->message->error("As senha digitadas não são iguais")->render();
                    echo json_encode($json);
                    return;
                }
                $userUpdate->first_name = $userUpdate->first_name;
                $userUpdate->last_name = $userUpdate->last_name;
                $userUpdate->email = $userUpdate->email;
                $userUpdate->password = $data["password"];
                $userUpdate->datebirth = $userUpdate->datebirth;
                $userUpdate->document = $userUpdate->document;
                $userUpdate->phone = $userUpdate->phone;
                //upload photo

                if (!$userUpdate->save()) {
                    $json["message"] = $userUpdate->message()->render();
                    echo json_encode($json);
                    return;
                }
                $this->message->success("Usuário atualizado com sucesso...")->flash();
                echo json_encode(["redirect" => url("restrito")]);
                return;
            }
        }
        return;
    }

    /**
     * @param $data
     */
    public function address($data): void
    {
        if (isset($data) and $data["action"] == "search") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $zipcode = new ViaCEP();
            $json["callback"] = (object)$zipcode->findByZipCode($data['zipcode'])->toArray();

            echo json_encode($json);
            return;
        }
        if (isset($data) and $data["action"] == "complete") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $complete = (new Address())->findById($data['id']);
            $json["zipcode"] = $complete->zipcode;
            $json["street"] = $complete->street;
            $json["number"] = $complete->number;
            $json["complement"] = $complete->complement;
            $json["neighborhood"] = $complete->neighborhood;
            $json["city"] = $complete->city;
            $json["state"] = $complete->state;
            $json["type"] = $complete->type;

            echo json_encode($json);
            return;
        }
        if (isset($data) and $data["action"] == "add") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            if (!csrf_verify($data)) {
                $json['message'] = $this->message->error("Erro ao enviar, favor use o formulário")->render();
                echo json_encode($json);
                return;
            }
            $addressCreate = new Address();
            $addressCreate->user_id = $data["user_id"];
            $addressCreate->zipcode = $data["zipcode"];
            $addressCreate->street = $data["street"];
            $addressCreate->number = $data["number"];
            $addressCreate->complement = $data["complement"] ? $data["complement"] : "";
            $addressCreate->neighborhood = $data["neighborhood"];
            $addressCreate->city = $data["city"];
            $addressCreate->state = $data["state"];
            $addressCreate->type = $data["type"];
            $addressCreate->ibge = $data["ibge"] ? $data["ibge"] : "vazio";
            if (!$addressCreate->save()) {
                $json["message"] = $addressCreate->message()->render();
                echo json_encode($json);
                return;
            }
            if (isset($data["destino"])) {
                $json['message'] = $this->message->success("Endereço Cadastrado com Sucesso")->flash();
                echo json_encode(["redirect" => url($data["destino"])]);
                $session = new Session();
                $session->set(
                    "cep",
                    [
                        "cep" => $data["zipcode"],
                        "endereco" => $addressCreate->data()->street,
                        "numero" => $addressCreate->data()->number,
                        "bairro" => $addressCreate->neighborhood,
                        "complemento" => $addressCreate->complement,
                        "cidade" => $addressCreate->city,
                        "estado" => $addressCreate->state
                    ]
                );
                return;
            }
            $json['message'] = $this->message->success("Endereço Cadastrado com Sucesso")->flash();
            echo json_encode(["redirect" => url("restrito/enderecos")]);
            return;
        }

        if (isset($data) and $data["action"] == "update") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);

            if (!csrf_verify_alt($data)) {
                $json['message'] = $this->message->error("Erro ao enviar, favor use o formulário")->render();
                echo json_encode($json);
                return;
            }
            $addressUpdate = (new Address())->findById($data["id"]);
            if (!$addressUpdate) {
                $this->message->error("Você tentou atualizar um endereço que não existe ou foi removido")->flash();
                echo json_encode(["redirect" => url("/restrito")]);
                return;
            }
            $addressUpdate->user_id = $data["user_id"];
            $addressUpdate->zipcode = $data["zipcode"];
            $addressUpdate->street = $data["street"];
            $addressUpdate->number = $data["number"];
            $addressUpdate->complement = $data["complement"] ? $data["complement"] : "";
            $addressUpdate->neighborhood = $data["neighborhood"];
            $addressUpdate->city = $data["city"];
            $addressUpdate->state = $data["state"];
            $addressUpdate->type = $data["type"];
            $addressUpdate->ibge = $data["ibge"] ? $data["ibge"] : "";
            if (!$addressUpdate->save()) {
                $json["message"] = $addressUpdate->message()->render();
                echo json_encode($json);
                return;
            }
            $json['message'] = $this->message->success("Endereço Atualizado com Sucesso")->flash();
            echo json_encode(["redirect" => url("restrito/enderecos")]);
            return;
        }
        if (isset($data) and $data["action"] == "delete") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            $addressDelete = (new Address())->findById($data["id"]);
            if (!$addressDelete) {
                $this->message->error("Você tentou excluir um endereço que não existe ou já foi removido")->flash();
                echo json_encode(["reload" => true]);
                return;
            }
            $addressDelete->destroy();
            $json['message'] = $this->message->success("Endereço Deletado com Sucesso")->flash();
            echo json_encode(["redirect" => url("restrito/enderecos")]);
            return;
        }
    }


    /**
     * @param array $data
     */
    public function cart(array $data): void
    {
        $head = $this->seo->render(
            "Carrinho de produtos - " . CONF_SITE_NAME,
            CONF_SITE_DESC,
            url("/produtos/carrinho"),
            theme("/assets/images/share.jpg")
        );
        echo $this->view->render("cart", [
            "active" => "carrinho",
            "head" => $head,
            "pageTitle" => (object)[
                "title" => "Carrinho",
                "subtitle" => "Carrinho de Produtos",
            ],
            "breadcrumb" => (object)[
                ["Carrinho", "#"]
            ]
        ]);
    }

    /**
     * @param array|null $data
     */
    public function checkOut(?array $data): void
    {
        $frete = new Session();
        $cart = new Cart(CARRINHO);
        $variableData = null;
        $frenetResult = null;
        $cCard = null;
        if ($cart->count() < 1) {
            redirect("/carrinho");
        }
        $page = filter_var($data["page"], FILTER_SANITIZE_STRIPPED);

        if ($page == "entrar") {
            $frete->unset("cep");

            if (Auth::user() and $cart->count() >= 1) {
                redirect("/fechar/endereco");
            }
            $active = "fechar/entrar";
            $render = "views/checkout-login";
            $title = "Login";
            $subtitle = "Efetue o Login";
            $breadcrumb = (object)[["Fechar Pedido", "#"]];
        }
        if ($page == "endereco") {
            if (!Auth::user()) {
                redirect("/fechar/entrar");
            }
            if ($cart->count() < 1) {
                redirect("/carrinho");
            }
            $frete->unset("frete");
            if (verifyAddress()) {
                $frenet = new FreteFrenet(CONF_SITE_ADDR_ZIPCODE, verifyAddress(), $cart->getTotal());
                $frenetResult = $frenet->getServices();
            }

            $active = "fechar/endereco";
            $render = "views/checkout-address";
            $title = "Finalize o Pedido";
            $subtitle = "Confira seus dados";
            $variableData = new Address();
            $uid = \user()->data()->id;
            $variableData = $variableData->find("user_id = :uid", "uid={$uid}")->fetch(true);
            $breadcrumb = (object)[["Fechar Pedido", url("fechar")], ["Endereço", "#"]];
        }

        // INCLUI PAGINA DE PAGAR
        if ($page == "pagar") {
            if (!Auth::user()) {
                redirect("/fechar/entrar");
            }
            if ($cart->count() < 1) {
                redirect("/carrinho");
            }
            if (!$frete->has("frete")) {
                redirect("/fechar/endereco");
            }
            $active = "fechar/pagar";
            $render = "views/checkout-payment";
            $title = "Pagamento";
            $subtitle = "Confira os dados do Pedido";

            $variableData = $frete;
            $breadcrumb = (object)[["Fechar pedido", url("fechar")], ["Pagar", "#"]];

            $card = new CreditCard();
            $uid = \user()->data()->id;
            $cCard = $card->find("user_id = :uid", "uid={$uid}")->fetch(true);
        }


        //CONTROLA VIA POST O CONTROLE DE FRETE
        if ($data['action'] == "frete") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);

            if (!isset($data["type"])) {
                $json['message'] = $this->message->error("Frete não selecionado")->flash();
                $json['redirect'] = url("fechar/endereco");
                echo json_encode($json);
                return;
            }
            if ($frete->has("frete")) {
                $frete->unset("frete");
            }

            if ($data["type"] == "Retirada") {
                $frete->set("frete", ["type" => $data["type"], "price" => 0.00]);
                $json['redirect'] = url("fechar/pagar");

                echo json_encode($json);
                return;
            }
            if ($data["type"] != "Retirada") {
                $frenet = new FreteFrenet(CONF_SITE_ADDR_ZIPCODE, verifyAddress(), $cart->getTotal());
                $frenetResult = $frenet->getServices();
                $freteVal = searchArrayFrenet($data["type"], $frenetResult);

                if ($freteVal == "erro") {
                    $json['message'] = $this->message->error(
                        "Indentificamos uma falha na segurança ao calcular frete. Contate o Suporte"
                    )->flash();
                    $json['redirect'] = url("carrinho");
                    echo json_encode($json);
                    return;
                }

                $frete->set("frete", ["type" => $data["type"], "price" => $freteVal]);
                $json['redirect'] = url("fechar/pagar");
                echo json_encode($json);
                return;
            }

            $json['message'] = $this->message->error(
                "Não conseguimos calcular seu pedido, favor entrar em contato com nossa equipe"
            )->flash();
            $json['redirect'] = url("carrinho");
            echo json_encode($json);
            return;
        }


        if ($page == "deslogar") {
            Auth::logout();
            redirect("/fechar/entrar");
        }

        $head = $this->seo->render(
            "Finalizar Compras - " . CONF_SITE_NAME,
            CONF_SITE_DESC,
            url("/checkout"),
            theme("/assets/images/share.jpg")
        );


        echo $this->view->render("checkout", [
            "active" => $active,
            "head" => $head,
            "frenet" => $frenetResult,
            "variableData" => $variableData,
            "cCard" => $cCard,
            "render" => $render,
            "pageTitle" => (object)[
                "title" => $title,
                "subtitle" => $subtitle,
            ],
            "breadcrumb" => $breadcrumb
        ]);
    }


    /**
     * FINALIZAÇÃO DO PEDIDO
     */
    public function receipt(array $data): void
    {
        $order = (new Orders())->findByIntegrationOrder($data["order_id"]);
        if (\user()->data()->id != $order->user_id) {
            redirect("/");
        }


        $sesion = new Session();
        $sesion->unset("frete");
        $cart = new Cart(CARRINHO);
        $cart->clear();
        $head = $this->seo->render(
            "Pedido Concluído - " . CONF_SITE_NAME,
            CONF_SITE_DESC,
            url("/finalizar/$order->id"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("checkout-end", [
            "head" => $head,
            "order" => $order,
            "active" => "finalizar",
            "pageTitle" => (object)[
                "title" => "Obrigado por comprar conosco",
                "subtitle" => "Pedido [#" . order_id($order->id) . "]",
            ],
            "breadcrumb" => (object)[
                ["Obrigado", "#"]
            ]
        ]);
    }

    /**
     * SITE OPT-IN CONFIRM
     */
    public function confirm(): void
    {
        $head = $this->seo->render(
            "Confirme Seu Cadastro - " . CONF_SITE_NAME,
            CONF_SITE_DESC,
            url("/confirma"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("optin", [
            "head" => $head,
            "data" => (object)[
                "title" => "Falta pouco! Confirme seu cadastro.",
                "desc" => "Enviamos um link de confirmação para seu e-mail. Acesse e siga as instruções para concluir seu cadastro e comece a controlar com o CaféControl",
                "image" => theme("/assets/images/optin-confirm.jpg")
            ]
        ]);
    }

    /**
     * SITE OPT-IN SUCCESS
     * @param array $data
     */
    public function success(array $data): void
    {
        $email = base64_decode($data["email"]);
        $user = (new User())->findByEmail($email);

        if ($user && $user->status != "confirmed") {
            $user->status = "confirmed";
            $user->save();
        }

        $head = $this->seo->render(
            "Bem-vindo(a) ao " . CONF_SITE_NAME,
            CONF_SITE_DESC,
            url("/obrigado"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("optin", [
            "head" => $head,
            "data" => (object)[
                "title" => "Tudo pronto. Você já pode controlar :)",
                "desc" => "Bem-vindo(a) ao seu controle de contas, vamos tomar um café?",
                "image" => theme("/assets/images/optin-success.jpg"),
                "link" => url("/entrar"),
                "linkTitle" => "Fazer Login"
            ],
            "track" => (object)[
                "fb" => "Lead",
                "aw" => "AW-953362805/yAFTCKuakIwBEPXSzMYD"
            ]
        ]);
    }

    /**
     * SITE TERMS
     */
    public function terms(): void
    {
        $head = $this->seo->render(
            CONF_SITE_NAME . " - Termos de uso",
            CONF_SITE_DESC,
            url("/termos"),
            theme("/assets/images/share.jpg")
        );

        echo $this->view->render("terms", [
            "head" => $head,
            "pageTitle" => (object)[
                "title" => "Termos e condições",
                "subtitle" => "Confira nossos termos e condições"
            ],
            "breadcrumb" => (object)[
                ["Termos e Condições", "#"]
            ]
        ]);
    }

    /**
     * SITE TERMS
     */
    public function newsletter(array $data): void
    {
        if (isset($data["action"]) and $data["action"] == "newsletter") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            if (request_limit("newsletter", 5, 60 * 3)) {
                $json['message'] = $this->message->error(
                    "Você já efetuou 5 tentativas de cadastro, esse é o limite. Por favor, aguarde 3 minutos para tentar novamente!"
                )->render();
                echo json_encode($json);
                return;
            }

            if (in_array("", $data)) {
                $json['message'] = $this->message->warning("Você deve preencher seu email")->render();
                echo json_encode($json);
                return;
            }

            if (!is_email($data['email'])) {
                $json['message'] = $this->message->info("Formato de email inválido")->render();
                echo json_encode($json);
                return;
            }

            $newsletter = (new Newsletter())->find("email = :email", "email={$data["email"]}")->fetch(true);

            if ($newsletter) {
                $json['message'] = $this->message->info("Seu email já está em nossa newsletter")->render();
                echo json_encode($json);
                return;
            }
            $newsCreate = new Newsletter();

            $newsCreate->email = $data["email"];
            $newsCreate->landing = $data["landing"];
            $newsCreate->field2 = $data["field2"] != "" ? $data["field2"] : null;
            $newsCreate->save();

            $json['message'] = $this->message->success("Inscrição Efetuada com sucesso {$newsletter->email}")->render();
            echo json_encode($json);
            return;
        }
    }


    /**
     *
     */
    public function envelopadores(array $data): void
    {
        if (isset($data["action"]) and $data["action"] == "findCep") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
//            if (request_limit("weblogin", 5, 60 * 3)) {
//                $json['message'] = $this->message->error("Você já efetuou 5 tentativas, esse é o limite. Por favor, aguarde 3 minutos para tentar novamente!")->render();
//                echo json_encode($json);
//                return;
//            }

            if (strlen($data["cep"]) < 9) {
                $json['message'] = $this->message->error("Cep Inválido ou inexistente")->render();
                echo json_encode($json);
                return;
            }

            if ($data["cep"] == "") {
                $json['message'] = $this->message->info("Digite um cep Válido")->render();
                echo json_encode($json);
                return;
            }


            $viaCep = new ViaCEP();
            $address = $viaCep->findByZipCode($data["cep"]);

            if ($address->ibge != "") {
                $envelopadores = (new Envelopadores())->find("region LIKE '%{$address->ibge}%'")->fetch(true);
                $json['message'] = $this->message->success("Obrigado, aguarde")->render();
                $json['callback'] = true;
                $json["html"] = $this->view->render("views/fragments/envelopadores", ["envelopadores" => $envelopadores]
                );

                echo json_encode($json);
                return;
                return;
            } else {
                $json['message'] = $this->message->error("Cep Inválido ou inexistente")->render();
                echo json_encode($json);
                return;
            }
        }


        echo $this->view->render("envelopadores", [
//            "active" => $active,
//            "head" => $head,
//            "frenet" => $frenetResult,
//            "variableData" => $variableData,
//            "cCard" => $cCard,
//            "render" => $render,
            "pageTitle" => (object)[
                "title" => "Envelopadores",
                "subtitle" => "Um Profissional próximo de você",
            ],
            "breadcrumb" => ["Envelopadores", "#"]
        ]);
    }

    /**
     * SITE COUPONS
     */
    public function coupons(array $data): void
    {
        if (isset($data["action"]) and $data["action"] == "insere") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);
            if (request_limit("coupon", 5, 60 * 3)) {
                $json['message'] = $this->message->error(
                    "Você já efetuou 5 tentativas, esse é o limite. Por favor, aguarde 3 minutos para tentar novamente!"
                )->render();
                echo json_encode($json);
                return;
            }

            if (in_array("", $data)) {
                $json['message'] = $this->message->warning("Você deve preencher um cupom")->render();
                echo json_encode($json);
                return;
            }
            $coupon = coupon_validate($data["coupon"]);

            if (!$coupon) {
                $json['message'] = $this->message->warning("Cupom inválido, vencido ou esgotado")->render();
                echo json_encode($json);
                unset($_SESSION[CONF_SITE_NAME . "-coupon"]);
                return;
            }

            $session = new Session();
            $session->set(CONF_SITE_NAME . "-coupon", $coupon);
            $json['message'] = $this->message->success("Cupom aplicado com sucesso")->flash();
            $json["reload"] = true;
            echo json_encode($json);
            return;
        }
        if (isset($data["action"]) and $data["action"] == "remove") {
            $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);

            unset($_SESSION[CONF_SITE_NAME . "-coupon"]);

            $json['message'] = $this->message->success("Cupom removido com sucesso")->flash();
            $json["reload"] = true;
            echo json_encode($json);
            return;

            return;
        }
    }


    /**
     *
     */
    public function logout(): void
    {
        $this->message->info("Você saiu com sucesso " . Auth::user()->first_name . ". Volte logo :)")->flash();

        Auth::logout();
        redirect("/");
    }


    /**
     * SITE NAV ERROR
     * @param array $data
     */
    public function error(array $data): void
    {
        $error = new \stdClass();

        switch ($data['errcode']) {
            case "problemas":
                $error->code = "OPS";
                $error->title = "Estamos enfrentando problemas!";
                $error->message = "Parece que nosso serviço não está diponível no momento. Já estamos vendo isso mas caso precise, envie um e-mail :)";
                $error->linkTitle = "ENVIAR E-MAIL";
                $error->link = "mailto:" . CONF_MAIL_SUPPORT;
                break;

            case "manutencao":
                $error->code = "OPS";
                $error->title = "Desculpe. Estamos em manutenção!";
                $error->message = "Voltamos logo! Por hora estamos trabalhando para melhorar nosso conteúdo para você controlar melhor as suas contas :P";
                $error->linkTitle = null;
                $error->link = null;
                break;

            default:
                $error->code = $data['errcode'];
                $error->title = "Ooops. Conteúdo indisponível :/";
                $error->message = "Sentimos muito, mas o conteúdo que você tentou acessar não existe, está indisponível no momento ou foi removido :/";
                $error->linkTitle = "Continue navegando!";
                $error->link = url_back();
                break;
        }

        $head = $this->seo->render(
            "{$error->code} | {$error->title}",
            $error->message,
            url("/ops/{$error->code}"),
            theme("/assets/images/share.jpg"),
            false
        );

        //redireciona erro para pagina principal
        redirect(url());
        echo $this->view->render("error", [
            "head" => $head,
            "error" => $error,
            "pageTitle" => (object)[
                "title" => "",
                "subtitle" => "Erro na requisição!",
                "bg" => theme("/assets/recipes/images/recipe-single.jpg"),
            ],
            "breadcrumb" => (object)[
                ["Erro", "#"]
            ]

        ]);
    }
}