<?php
class ControllerCommonHome extends Controller {
    public function index() {

        $language = $this->language->load('common/home');
        $this->data = array_merge($this->data, $language);

        $this->load->type('tipocomum');

        $this->load->model('setting/efutura');

        $skyhub_invalid_credential =  $this->config->get('skyhub_invalid_credential');
        $skyhub_status =  $this->config->get('skyhub_status');
        if($skyhub_status == Type_Status::Tp_Desabilitado && $skyhub_invalid_credential){
            $this->data['show_skyhub_invalid_credentials_message'] = true;
            if (isset($this->data['warning_skyhub_credential'])) {
                $this->data['warning_skyhub_credential'] = sprintf(
                    $this->language->get('warning_skyhub_credential'),
                    $this->url->link('module/skyhub/settings', 'token=' . $this->session->data['token'] . '&type=' . Type_TitleModules::Tp_Marketplace . '#tab-info=0', 'SSL')
                );
            }
        } else {
            $this->data['show_skyhub_invalid_credentials_message'] = false;
        }

        $correios_invalid_credential =  $this->config->get('correios_invalid_credential');
        $correios_tracking_status =  $this->config->get('correios_tracking_status');
        if($correios_tracking_status == Type_Status::Tp_Desabilitado && $correios_invalid_credential){
            $this->data['show_correios_invalid_credentials_message'] = true;
            if (isset($this->data['warning_correios_credential'])) {
                $this->data['warning_correios_credential'] = sprintf(
                    $this->language->get('warning_correios_credential'),
                    $this->url->link('shipping/correios', 'token=' . $this->session->data['token'] . '&type=' . Type_TitleModules::Tp_Envio . '#tab-info=2', 'SSL')
                );
            }
        } else {
            $this->data['show_correios_invalid_credentials_message'] = false;
        }

        $this->data['showECommerceLinks'] = $this->config->get('config_sistema_ecommerce');
        $this->data['showMarketplaceLinks'] =  $this->config->get('config_sistema_marketplace');

        $this->data['production_link_warning'] = $this->config->get('config_sistema_ecommerce') && empty($this->config->get('config_linkproducao_ssl'));
        $this->data['link_manual_dominio'] = 'http://manual.futurasistemas.com.br/manual-do-sistema/como-configurar-dominio-de-complemento-no-cpanel/';

        $this->document->setTitle($this->language->get('heading_title'));

        $this->data['review_link'] = sprintf($this->language->get('text_review_link'), $this->url->link('catalog/review', 'token=' . $this->session->data['token'], 'SSL'));

        $this->data['configbar'] = $this->getChild('common/configbar');
        $this->data['last_sales_order'] = $this->getChild('common/home/last_sales_order');

        $this->data['store_rating_module_status'] = $this->config->get('store_rating_module_status');

        $this->data['link_product'] = $this->url->link('catalog/product', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['link_order'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['link_customer'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['link_customer_online'] = $this->url->link('report/customer_online', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['link_searchterms'] = $this->url->link('report/searchterms', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['link_most_viewed'] = $this->url->link('report/product_viewed', 'token=' . $this->session->data['token'], 'SSL');

        $this->document->addScript(array(
            'view/javascript/jquery/charts.js',
            'view/public/js/page-home.js'
        ));

        // Check install directory exists
        if (is_dir(dirname(DIR_APPLICATION) . '/install')) {
            $this->data['error_install'] = $this->language->get('error_install');
        } else {
            $this->data['error_install'] = '';
        }


        // Check image directory is writable
        $file = DIR_IMAGE . 'test';

        $handle = fopen($file, 'a+');

        fwrite($handle, '');

        fclose($handle);

        if (!file_exists($file)) {
            $this->data['error_image'] = sprintf($this->language->get('error_image'). DIR_IMAGE);
        } else {
            $this->data['error_image'] = '';

            unlink($file);
        }

        // Check image cache directory is writable
        $file = DIR_IMAGE . 'cache/test';

        $handle = fopen($file, 'a+');

        fwrite($handle, '');

        fclose($handle);

        if (!file_exists($file)) {
            $this->data['error_image_cache'] = sprintf($this->language->get('error_image_cache'). DIR_IMAGE . 'cache/');
        } else {
            $this->data['error_image_cache'] = '';

            unlink($file);
        }

        // Check cache directory is writable
        $file = DIR_CACHE . 'test';

        $handle = fopen($file, 'a+');

        fwrite($handle, '');

        fclose($handle);

        if (!file_exists($file)) {
            $this->data['error_cache'] = sprintf($this->language->get('error_image_cache'). DIR_CACHE);
        } else {
            $this->data['error_cache'] = '';

            unlink($file);
        }

        // Check download directory is writable
        $file = DIR_DOWNLOAD . 'test';

        $handle = fopen($file, 'a+');

        fwrite($handle, '');

        fclose($handle);

        if (!file_exists($file)) {
            $this->data['error_download'] = sprintf($this->language->get('error_download'). DIR_DOWNLOAD);
        } else {
            $this->data['error_download'] = '';

            unlink($file);
        }

        // Check logs directory is writable
        $file = DIR_LOGS . 'test';

        $handle = fopen($file, 'a+');

        fwrite($handle, '');

        fclose($handle);

        if (!file_exists($file)) {
            $this->data['error_logs'] = sprintf($this->language->get('error_logs'). DIR_LOGS);
        } else {
            $this->data['error_logs'] = '';

            unlink($file);
        }

        $this->data['breadcrumbs'] = array();

        $this->data['breadcrumbs'][] = array(
            'text'      => $this->language->get('text_home'),
            'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => false
        );

        $this->data['token'] = $this->session->data['token'];

        $this->load->model('catalog/product');
        $data = array(
            'filter_data_replicacao_ecommerce' => true
        );
        $this->data['total_product'] = $this->ftrgeralregistry->gerarCache('total_product', $this->model_catalog_product->getTotalProducts(), 86400);
        $this->data['total_product_year'] = sprintf($this->language->get('total_product_year'), $this->ftrgeralregistry->gerarCache('total_product_year', $this->model_catalog_product->getTotalProducts($data), 86400));

        $this->load->model('sale/order');

        $this->data['total_sale'] = $this->ftrgeralregistry->gerarCache('total_sale', $this->currency->format($this->model_sale_order->getTotalSales(), $this->config->get('config_currency')), 86400);
        $this->data['total_sale_year'] = sprintf($this->language->get('total_sale_year'), $this->ftrgeralregistry->gerarCache('total_sale_year', $this->currency->format($this->model_sale_order->getTotalSalesByYear(date('Y')), $this->config->get('config_currency')), 86400));

        // ticket medio
        $this->data['average_sale'] = $this->ftrgeralregistry->gerarCache('average_sale', $this->currency->format($this->model_sale_order->getAverageSalesLast12Months(), $this->config->get('config_currency')), 86400);


        $data = array(
            'filter_status_futuraserver' => true
        );
        $this->data['total_order'] = $this->ftrgeralregistry->gerarCache('total_order', $this->model_sale_order->getTotalOrders($data), 86400);

        $data = array(
            'filter_order_status_id' => (int)$this->config->get('config_complete_status_id'),
            'filter_date_added_between' => true,
            'filter_status_futuraserver' => true
        );
        $this->data['total_order_year'] = sprintf($this->language->get('total_order_year'), $this->ftrgeralregistry->gerarCache('total_order_year', $this->model_sale_order->getTotalOrders($data), 86400));

        $this->load->model('sale/customer');
        $data = array(
            'filter_approved' => Type_Status::Tp_Habilitado,
            'filter_date_added_between' => true
        );
        $this->data['total_customer'] = $this->ftrgeralregistry->gerarCache('total_customer', $this->model_sale_customer->getTotalCustomers(), 86400);
        $this->data['total_customer_year'] = sprintf($this->language->get('total_customer_year'), $this->ftrgeralregistry->gerarCache('total_customer_year', $this->model_sale_customer->getTotalCustomers($data), 86400));

        // clientes online
        $this->load->model('report/online');
        $this->data['total_customer_online'] = $this->customers_online(false);
        date_default_timezone_set('America/Sao_Paulo');
        $this->data['customers_online_last_refresh'] = date("H:i");

        $this->load->model('catalog/review');

        $this->data['total_review'] = $this->model_catalog_review->getTotalReviews();
        $this->data['total_review_approval'] = $this->model_catalog_review->getTotalReviewsAwaitingApproval();

        $this->load->model('catalog/store_rating');
        $this->data['total_store_rating'] = $this->model_catalog_store_rating->getTotalRatings();
        $this->data['total_store_rating_approval'] = $this->model_catalog_store_rating->getTotalRatingsAwaitingApproval();

        $this->load->model('sale/affiliate');

        $this->data['total_affiliate'] = $this->model_sale_affiliate->getTotalAffiliates();
        $this->data['total_affiliate_approval'] = $this->model_sale_affiliate->getTotalAffiliatesAwaitingApproval();

        $this->load->dmodel('catalog/searchterms');
        $this->data['search_terms'] = $this->dmodel_catalog_searchterms->getSearchTermsMostWanted(array('limit' => 10));

        $this->load->model('report/product');
        $this->data['most_viewed_products'] = $this->model_report_product->getProductsViewed(array('limit' => 10, 'start' => 0));

        $this->data['marketplace_status'] = array_filter(array(
            $this->config->get('skyhub_status'),
            $this->config->get('mercadolivre_status'),
            $this->config->get('shopee_status'),
        ));

        $this->data['app_status'] = (int)$this->model_sale_order->getOrderApp();

        $quick_config = $this->config->get('quick_config');

        $userName = $this->user->getUserName();
        $userID = $this->user->getId();

        if (isset($quick_config) && $userName != 'futura') {
            $this->data['exibe_quick_configure'] = (!isset($quick_config[$userID]) || (isset($quick_config[$userID]) && ($quick_config[$userID]['status'] == 1 && strtotime($quick_config[$userID]['date']) < strtotime(date('Y-m-d'))))) ? 1 : 0;
        } else {
            $this->data['exibe_quick_configure'] = 0;
        }

        if (!$this->user->hasPermission('access', Type_PermissaoFuncao::Tp_OrderStats)) {
          $this->data['order_stats_permission'] = false;
        } else {
          $this->data['order_stats_permission'] = true;
        }

        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->response->setOutput($this->render('common/home'));
    }

    public function chart() {

        $this->language->load('common/home');
        $this->load->model('sale/order');
        $this->load->type('tipocomum');
        $this->load->type('tipofuturaserver');

        $data = array();

        $data['order'] = array();
        $data['xaxis'] = array();
        $data['label_order']	  = $this->language->get('text_order');

        if (isset($this->request->get['range'])) {
            $range = $this->request->get['range'];
        } else {
            $range = Type_Period::Tp_Month;
        }

        switch ($range) {
            case Type_Period::Tp_Day:
                for ($i = 0; $i < 24; $i++) {
                    $data['order'][]    = $this->model_sale_order->getOrderTotalValueDateByHour($i);
                    $data['xaxis'][]    = date('H', mktime($i, 0, 0, date('n'), date('j'), date('Y')));
                }
                break;
            case Type_Period::Tp_Week:
                $date_start = strtotime('-' . date('w') . ' days');

                for ($i = 0; $i < 7; $i++) {
                    $date = date('Y-m-d', $date_start + ($i * 86400));
                    $data['order'][]    = $this->model_sale_order->getOrderTotalValueDateByWeek($date);
                    $data['xaxis'] =array(
                        0 => 'Domingo',
                        1 => 'Segunda-feira',
                        2 => 'Terça-feira',
                        3 => 'Quarta-feira',
                        4 => 'Quinta-feira',
                        5 => 'Sexta-feira',
                        6 => 'Sábado'
                    );
                }

                break;
            default:
            case Type_Period::Tp_Month:
                for ($i = 1; $i <= date('t'); $i++) {
                    $date = date('Y') . '-' . date('m') . '-' . $i;
                    $data['order'][]    = $this->model_sale_order->getOrderTotalValueDateByMonth($date);
                    $data['xaxis'][] = date('j', strtotime($date));
                }
                break;
            case Type_Period::Tp_Year:
                for ($i = 1; $i <= 12; $i++) {
                    $data['order'][]    = $this->model_sale_order->getOrderTotalValueDateByYear($i);
                    $data['xaxis'] =array(
                        0 => 'Janeiro',
                        1 => 'Fevereiro',
                        2 => 'Março',
                        3 => 'Abril',
                        4 => 'Maio',
                        5 => 'Junho',
                        6 => 'Julho',
                        7 => 'Agosto',
                        8 => 'Setembro',
                        9 => 'Outubro',
                        10 => 'Novembro',
                        11 => 'Dezembro'
                    );
                }
                break;
        }

        $this->response->setOutput(json_encode($data));
    }


    public function chartDevice(){

        $this->language->load('common/home');
        $this->load->type('tipocomum');
        $this->load->type('tipofuturaserver');
        $this->load->model('sale/order');

        $browser = new BrowserInfo();

        $data = array();

        $data['desktop'] = array();
        $data['tablet'] = array();
        $data['mobile'] = array();
        $data['xaxis'] = array();
        $data['label_desktop']  =  $this->language->get('text_desktop');
        $data['label_tablet']   =  $this->language->get('text_tablet');
        $data['label_mobile']   =  $this->language->get('text_mobile');

        if (isset($this->request->get['range'])) {
            $range = $this->request->get['range'];
        } else {
            $range = Type_Period::Tp_Month;
        }

        switch ($range) {
            case Type_Period::Tp_Day:
                for ($i = 0; $i < 24; $i++) {
                    $results = $this->model_sale_order->getOrderValueDeviceByHour($i);
                    if ($results) {
                        foreach ($results as $result) {
                            if($result['device']==$browser::IsDeskTop){
                                $data['desktop'][] = $result['total_device'];
                            }else{
                                $data['desktop'][] = 0 ;
                            }
                            if($result['device']==$browser::IsTablet){
                                $data['tablet'][] = $result['total_device'];
                            }else{
                                $data['tablet'][] = 0 ;
                            }
                            if($result['device']==$browser::IsMobile){
                                $data['mobile'][] = $result['total_device'];
                            }else{
                                $data['mobile'][] = 0 ;
                            }
                        }
                    }else{
                        $data['desktop'][] = 0 ;
                        $data['tablet'][]  = 0 ;
                        $data['mobile'][]  = 0 ;
                    }
                    $data['xaxis'][] = date('H', mktime($i, 0, 0, date('n'), date('j'), date('Y')));
                }
                break;
            case Type_Period::Tp_Week:
                $date_start = strtotime('-' . date('w') . ' days');

                for ($i = 0; $i < 7; $i++) {
                    $date = date('Y-m-d', $date_start + ($i * 86400));
                    $results = $this->model_sale_order->getOrderValueDeviceByWeek($date);
                    if ($results) {
                        foreach ($results as $result) {
                            if($result['device']==$browser::IsDeskTop){
                                $data['desktop'][] = $result['total_device'];
                            }else{
                                $data['desktop'][] = 0 ;
                            }
                            if($result['device']==$browser::IsTablet){
                                $data['tablet'][] = $result['total_device'];
                            }else{
                                $data['tablet'][] = 0 ;
                            }
                            if($result['device']==$browser::IsMobile){
                                $data['mobile'][] = $result['total_device'];
                            }else{
                                $data['mobile'][] = 0 ;
                            }
                        }
                    }else{
                        $data['desktop'][] = 0 ;
                        $data['tablet'][]  = 0 ;
                        $data['mobile'][]  = 0 ;
                    }
                    $data['xaxis'] =array(
                        0 => 'Domingo',
                        1 => 'Segunda-feira',
                        2 => 'Terça-feira',
                        3 => 'Quarta-feira',
                        4 => 'Quinta-feira',
                        5 => 'Sexta-feira',
                        6 => 'Sábado'
                    );
                }
                break;
            default:
            case Type_Period::Tp_Month:
                for ($i = 1; $i <= date('t'); $i++) {
                    $date = date('Y') . '-' . date('m') . '-' . $i;
                    $results = $this->model_sale_order->getOrderValueDeviceByMonth($date);
                    if ($results) {
                        foreach ($results as $result) {
                            if($result['device']==$browser::IsDeskTop){
                                $data['desktop'][] = $result['total_device'];
                            }else{
                                $data['desktop'][] = 0 ;
                            }
                            if($result['device']==$browser::IsTablet){
                                $data['tablet'][] = $result['total_device'];
                            }else{
                                $data['tablet'][] = 0 ;
                            }
                            if($result['device']==$browser::IsMobile){
                                $data['mobile'][] = $result['total_device'];
                            }else{
                                $data['mobile'][] = 0 ;
                            }
                        }
                    }else{
                        $data['desktop'][] = 0 ;
                        $data['tablet'][]  = 0 ;
                        $data['mobile'][]  = 0 ;
                    }
                    $data['xaxis'][] = date('j', strtotime($date));
                }
                break;
            case Type_Period::Tp_Year:
                for ($i = 1; $i <= 12; $i++) {
                    $results = $this->model_sale_order->getOrderValueDeviceByYear($i);
                    $index = $i -1;
                    if ($results) {
                        foreach ($results as $result) {
                            if($result['device']==$browser::IsDeskTop){
                                $data['desktop'][$index] += $result['total_device'];
                            }else{
                                $data['desktop'][$index] += 0 ;
                            }
                            if($result['device']==$browser::IsTablet){
                                $data['tablet'][$index] += $result['total_device'];
                            }else{
                                $data['tablet'][$index] += 0 ;
                            }
                            if($result['device']==$browser::IsMobile){
                                $data['mobile'][$index] += $result['total_device'];
                            }else{
                                $data['mobile'][$index] += 0 ;
                            }
                        }
                    }else{
                        $data['desktop'][$index] = 0 ;
                        $data['tablet'][$index]  = 0 ;
                        $data['mobile'][$index]  = 0 ;
                    }
                }

                $data['xaxis'] =array(
                  0 => 'Janeiro',
                  1 => 'Fevereiro',
                  2 => 'Março',
                  3 => 'Abril',
                  4 => 'Maio',
                  5 => 'Junho',
                  6 => 'Julho',
                  7 => 'Agosto',
                  8 => 'Setembro',
                  9 => 'Outubro',
                  10 => 'Novembro',
                  11 => 'Dezembro'
                );

                break;
        }

        $this->response->setOutput(json_encode($data));

    }

    public function chartMarketplace() {
        $this->language->load('common/home');
        $this->load->model('sale/order');
        $this->load->type('tipocomum');
        $this->load->type('tipofuturaserver');

        $data = array();
        $hasValue = array();

        if (isset($this->request->get['range'])) {
            $range = $this->request->get['range'];
        } else {
            $range = Type_Period::Tp_Month;
        }

        foreach (Type_MarketplaceInt::getEnumList() as $key => $value) {
            $data[$key]['label'] = $value;
        }

        switch ($range) {
            case Type_Period::Tp_Day:
                $results = $this->model_sale_order->getOrderValueMarketplaceByDay(date('Y-m-d'));

                foreach (Type_MarketplaceInt::getEnumList() as $key => $value) {
                    for ($hour = 0; $hour < 24; $hour++) {
                        if ($results) {
                            $result = array_filter($results, function ($reg) use ($hour, $key) {
                                return $reg['hora'] == $hour && $reg['marketplace'] == $key;
                            });
                        } else  {
                            $result = array();
                        }
                        if (!empty($result)) {
                            $data[$key]['data'][] = (float)current($result)['total_marketplace'];
                            if (!in_array($key, $hasValue)) {
                                $hasValue[] = $key;
                            }
                        } else {
                            $data[$key]['data'][] = 0;
                        }
                    }
                }

                for ($hour = 0; $hour < 24; $hour++) {
                    $data['xaxis'][] = date('H', mktime($hour, 0, 0, date('n'), date('j'), date('Y')));
                }

                break;
            case Type_Period::Tp_Week:
                $results = $this->model_sale_order->getOrderValueMarketplaceByWeek(date('Y-m-d'));

                foreach (Type_MarketplaceInt::getEnumList() as $key => $value) {
                    for ($dia = 0; $dia < 7; $dia++) {
                        if ($results) {
                            $result = array_filter($results, function ($reg) use ($dia, $key) {
                                return $reg['dia'] == $dia && $reg['marketplace'] == $key;
                            });
                        } else  {
                            $result = array();
                        }
                        if (!empty($result)) {
                            $data[$key]['data'][] = (float)current($result)['total_marketplace'];
                            if (!in_array($key, $hasValue)) {
                                $hasValue[] = $key;
                            }
                        } else {
                            $data[$key]['data'][] = 0;
                        }
                    }
                }


                $data['xaxis'] = array(0 => 'Domingo', 1 => 'Segunda-feira', 2 => 'Terça-feira', 3 => 'Quarta-feira', 4 => 'Quinta-feira', 5 => 'Sexta-feira', 6 => 'Sábado');

                break;
            default:
            case Type_Period::Tp_Month:

                $results = $this->model_sale_order->getOrderValueMarketplaceByMonth(date('Y-m-d'));

                foreach (Type_MarketplaceInt::getEnumList() as $key => $value) {
                    for ($dia = 1; $dia <= date('t'); $dia++) {
                        if ($results) {
                            $result = array_filter($results, function ($reg) use ($dia, $key) {
                                return $reg['dia'] == $dia && $reg['marketplace'] == $key;
                            });
                        } else  {
                            $result = array();
                        }
                        if (!empty($result)) {
                            $data[$key]['data'][] = (float)current($result)['total_marketplace'];
                            if (!in_array($key, $hasValue)) {
                                $hasValue[] = $key;
                            }
                        } else {
                            $data[$key]['data'][] = 0;
                        }
                    }
                }

                for ($dia = 1; $dia <= date('t'); $dia++) {
                    $data['xaxis'][] = date('j', strtotime(date('Y') . '-' . date('m') . '-' . $dia));
                }

                break;
            case Type_Period::Tp_Year:
                $results = $this->model_sale_order->getOrderValueMarketplaceByYear(date("Y"));

                foreach (Type_MarketplaceInt::getEnumList() as $key => $value) {
                    for ($mes = 1; $mes <= 12; $mes++) {
                        if ($results) {
                            $result = array_filter($results, function ($reg) use ($mes, $key) {
                                return $reg['mes'] == $mes && $reg['marketplace'] == $key;
                            });
                        } else {
                            $result = array();
                        }
                        if (!empty($result)) {
                            $data[$key]['data'][] = (float)current($result)['total_marketplace'];
                            if (!in_array($key, $hasValue)) {
                                $hasValue[] = $key;
                            }
                        } else {
                            $data[$key]['data'][] = 0;
                        }
                    }
                }

                $data['xaxis'] = array(0 => 'Janeiro', 1 => 'Fevereiro', 2 => 'Março', 3 => 'Abril', 4 => 'Maio', 5 => 'Junho',6 => 'Julho', 7 => 'Agosto', 8 => 'Setembro', 9 => 'Outubro', 10 => 'Novembro', 11 => 'Dezembro');

                break;
        }

        $dataJson = array();
        if ($hasValue) {
            $contador = 1;
            foreach ($data as $key => $value) {
                if (in_array($key, $hasValue, true)) {
                    $dataJson[$contador] = $data[$key];
                    $contador++;
                }
            }
        } else {
            $dataJson[1] = $data[1];
            $dataJson[1]['label'] = "Nenhuma venda de marketplace";
        }
        $dataJson['xaxis'] = $data['xaxis'];

        $this->response->setOutput(json_encode($dataJson));
    }

    public function chartSalesChannel() {
        $this->language->load('common/home');
        $this->load->model('sale/order');
        $this->load->type('tipocomum');
        $this->load->type('tipofuturaserver');

        $app_status = (int)$this->model_sale_order->getOrderApp();
        $marketplace_status = array_filter(array(
            $this->config->get('skyhub_status'),
            $this->config->get('mercadolivre_status'),
            $this->config->get('shopee_status')
        ));

        $data = array();
        $hasValue = array();

        if (isset($this->request->get['range'])) {
            $range = $this->request->get['range'];
        } else {
            $range = Type_Period::Tp_Month;
        }

        foreach (Type_OrigemSistema::getEnumList() as $key => $value) {
            $data[$key]['label'] = $value;
        }

        switch ($range) {
            case Type_Period::Tp_Day:
                $results = $this->model_sale_order->getOrderValueSalesChannelByDay(date('Y-m-d'));

                foreach (Type_OrigemSistema::getEnumList() as $key => $value) {
//                    if (($key == Type_OrigemSistema::Tp_App && !$app_status) || ($key == Type_OrigemSistema::Tp_Marketplace && empty($marketplace_status))){
//                        continue;
//                    }
                    for ($hour = 0; $hour < 24; $hour++) {
                        if ($results) {
                            $result = array_filter($results, function ($reg) use ($hour, $key) {
                                return $reg['hora'] == $hour && $reg['origem'] == $key;
                            });
                        } else  {
                            $result = array();
                        }
                        if (!empty($result)) {
                            $data[$key]['data'][] = (float)current($result)['total_origem'];
                            if (!in_array($key, $hasValue)) {
                                $hasValue[] = $key;
                            }
                        } else {
                            $data[$key]['data'][] = 0;
                        }
                    }
                }

                for ($hour = 0; $hour < 24; $hour++) {
                    $data['xaxis'][] = date('H', mktime($hour, 0, 0, date('n'), date('j'), date('Y')));
                }

                break;
            case Type_Period::Tp_Week:
                $results = $this->model_sale_order->getOrderValueSalesChannelByWeek(date('Y-m-d'));

                foreach (Type_OrigemSistema::getEnumList() as $key => $value) {
                    for ($dia = 0; $dia < 7; $dia++) {
                        if ($results) {
                            $result = array_filter($results, function ($reg) use ($dia, $key) {
                                return $reg['dia'] == $dia && $reg['origem'] == $key;
                            });
                        } else  {
                            $result = array();
                        }
                        if (!empty($result)) {
                            $data[$key]['data'][] = (float)current($result)['total_origem'];
                            if (!in_array($key, $hasValue)) {
                                $hasValue[] = $key;
                            }
                        } else {
                            $data[$key]['data'][] = 0;
                        }
                    }
                }


                $data['xaxis'] = array(0 => 'Domingo', 1 => 'Segunda-feira', 2 => 'Terça-feira', 3 => 'Quarta-feira', 4 => 'Quinta-feira', 5 => 'Sexta-feira', 6 => 'Sábado');

                break;
            default:
            case Type_Period::Tp_Month:

                $results = $this->model_sale_order->getOrderValueSalesChannelByMonth(date('Y-m-d'));

                foreach (Type_OrigemSistema::getEnumList() as $key => $value) {
                    for ($dia = 1; $dia <= date('t'); $dia++) {
                        if ($results) {
                            $result = array_filter($results, function ($reg) use ($dia, $key) {
                                return $reg['dia'] == $dia && $reg['origem'] == $key;
                            });
                        } else  {
                            $result = array();
                        }
                        if (!empty($result)) {
                            $data[$key]['data'][] = (float)current($result)['total_origem'];
                            if (!in_array($key, $hasValue)) {
                                $hasValue[] = $key;
                            }
                        } else {
                            $data[$key]['data'][] = 0;
                        }
                    }
                }

                for ($dia = 1; $dia <= date('t'); $dia++) {
                    $data['xaxis'][] = date('j', strtotime(date('Y') . '-' . date('m') . '-' . $dia));
                }

                break;
            case Type_Period::Tp_Year:
                $results = $this->model_sale_order->getOrderValueSalesChannelByYear(date("Y"));

                foreach (Type_OrigemSistema::getEnumList() as $key => $value) {
                    for ($mes = 1; $mes <= 12; $mes++) {
                        if ($results) {
                            $result = array_filter($results, function ($reg) use ($mes, $key) {
                                return $reg['mes'] == $mes && $reg['origem'] == $key;
                            });
                        } else {
                            $result = array();
                        }
                        if (!empty($result)) {
                            $data[$key]['data'][] = (float)current($result)['total_origem'];
                            if (!in_array($key, $hasValue)) {
                                $hasValue[] = $key;
                            }
                        } else {
                            $data[$key]['data'][] = 0;
                        }
                    }
                }

                $data['xaxis'] = array(0 => 'Janeiro', 1 => 'Fevereiro', 2 => 'Março', 3 => 'Abril', 4 => 'Maio', 5 => 'Junho',6 => 'Julho', 7 => 'Agosto', 8 => 'Setembro', 9 => 'Outubro', 10 => 'Novembro', 11 => 'Dezembro');

                break;
        }

        $dataJson = array();
        if ($hasValue) {
            $contador = 1;
            foreach ($data as $key => $value) {
                if (($key !== 'xaxis') and
                    ($key !== Type_OrigemSistema::Tp_Marketplace or $marketplace_status) and
                    ($key !== Type_OrigemSistema::Tp_App or $app_status)) {
                    $dataJson[$contador] = $data[$key];
                    $contador++;
                }
            }
        } else {
            $dataJson[1] = $data[1];
            $dataJson[1]['label'] = "Nenhuma venda encontrada";
        }

        $dataJson['xaxis'] = $data['xaxis'];
        $this->response->setOutput(json_encode($dataJson));
    }

    public function login() {
        $route = '';

        if (isset($this->request->get['route'])) {
            $part = explode('/', $this->request->get['route']);

            if (isset($part[0])) {
                $route .= $part[0];
            }

            if (isset($part[1])) {
                $route .= '/' . $part[1];
            }
        }

        $ignore = array(
            'common/login',
            'common/forgotten',
            'common/reset'
        );

        if (!$this->user->isLogged() && !in_array($route, $ignore)) {
            return $this->forward('common/login');
        }

        if (isset($this->request->get['route'])) {
            $ignore = array(
                'common/login',
                'common/logout',
                'common/forgotten',
                'common/reset',
                'error/not_found',
                'error/permission'
            );

            $config_ignore = array();

            if ($this->config->get('config_token_ignore')) {
                $config_ignore = unserialize($this->config->get('config_token_ignore'));
            }

            $ignore = array_merge($ignore, $config_ignore);

            if (!in_array($route, $ignore) && (!isset($this->request->get['token']) || !isset($this->session->data['token']) || ($this->request->get['token'] != $this->session->data['token']))) {
                return $this->forward('common/login');
            }
        } else {
            if (!isset($this->request->get['token']) || !isset($this->session->data['token']) || ($this->request->get['token'] != $this->session->data['token'])) {
                return $this->forward('common/login');
            }
        }
    }

    public function permission() {
        if (isset($this->request->get['route'])) {
            $route = '';

            $part = explode('/', $this->request->get['route']);

            if (isset($part[0])) {
                $route .= $part[0];
            }

            if (isset($part[1])) {
                $route .= '/' . $part[1];
            }

            if(defined('PREFIX_NAME') && in_array(PREFIX_NAME, $part)){
                $route .= '/' . $part[2].'/'.$part[3];
            }

            $ignore = array(
                'common/home',
                'common/login',
                'common/logout',
                'common/forgotten',
                'common/reset',
                'common/notification',
                'common/user',
                'common/nav',
                'user/trocasenha',
                'error/not_found',
                'error/permission',
                'extension/easyconfigure',
                'tool/error_log',
                'tool/error_log_mercadolivre',
                'common/adsbanner',
                'common/manual',
                'marketplace/Marketplacecalls',
                'marketplace/marketprice',
            );

            if (!in_array($route, $ignore) && !$this->user->hasPermission('access', $route)) {
                return $this->forward('error/permission');
            }
        }
    }

    public function customers_online($json=true){
        $this->load->dmodel('tool/online');
        $this->dmodel_tool_online->cleanonline();

        $this->load->model('report/online');
        $retorno = $this->model_report_online->getTotalCustomersOnline();
        date_default_timezone_set('America/Sao_Paulo');
        $hour = date("H:i");

        if ($json) {
            $this->response->setOutputJson(['total' => $retorno, 'hour' => $hour]);
        } else {
            return $retorno;
        }
    }

    public function Version(){

        $json = array();

        $this->language->load('common/home');
        $this->load->model('setting/efutura');

        $this->model_setting_efutura->updateVersion();

        $json['success'] = true;

        $this->response->setOutput(json_encode($json));

    }


    public function last_sales_order(){

        $this->load->model('sale/order');
        $this->load->type('tipofuturaserver');

        $language = $this->language->load('common/home');
        $this->data = array_merge($this->data, $language);

        $proccess_status = (isset($this->request->get['proccess_status'])) ? $this->request->get['proccess_status'] : '';
        $this->data['linkFilterProcessVenda'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&filter_order_process_status=' . $proccess_status, 'SSL');

        $this->data['contrlProcVenda'] = false;

        if($this->config->get('processo_venda_status') == Type_DsimDnao::Tp_Sim){
            foreach(Type_ContrlProcVenda::getEnumlist() as $key => $value){
                $contrlProcVenda[] = array(
                    'key'      => $key,
                    'value'    => $value,
                    'selected' => ftr_geral::isSelected($key, $proccess_status)
                );
            }
            $this->data['contrlProcVenda'] = $contrlProcVenda;
        }

        $this->data['orders'] = array();

        $data = array(
            'sort'  => 'o.date_added',
            'order' => 'DESC',
            'start' => 0,
            'limit' => 12,
            'filter_order_process_status' => $proccess_status
        );

        $results = $this->model_sale_order->getOrders($data);

        foreach ($results as $result) {

            $this->data['orders'][] = array(
                'order_id'   => $result['order_id'],
                'customer'   => $result['customer'],
                'status'     => $result['status'],
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                'total'      => $this->currency->format($result['total'], $result['currency_code'], $result['currency_value']),
                'href'       => $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $result['order_id'], 'SSL')
            );
        }

        $this->response->setOutput($this->render('common/last_sales_order'));

    }


}
