<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Dashboard extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('dashboard_model');
    }

    /* This is admin dashboard view */
    public function index()
    {
        close_setup_menu();
        $this->load->model('departments_model');
        $this->load->model('todo_model');
        $data['departments'] = $this->departments_model->get();

        $data['todos'] = $this->todo_model->get_todo_items(0);
        // Only show last 5 finished todo items
        $this->todo_model->setTodosLimit(5);
        $data['todos_finished'] = $this->todo_model->get_todo_items(1);
        $data['upcoming_events_next_week'] = $this->dashboard_model->get_upcoming_events_next_week();
        $data['upcoming_events'] = $this->dashboard_model->get_upcoming_events();
        $data['title'] = _l('dashboard_string');

        $this->load->model('contracts_model');
        $data['expiringContracts'] = $this->contracts_model->get_contracts_about_to_expire(get_staff_user_id());

        $this->load->model('currencies_model');
        $data['currencies'] = $this->currencies_model->get();
        $data['base_currency'] = $this->currencies_model->get_base_currency();
        $data['activity_log'] = $this->misc_model->get_activity_log();
        // Tickets charts
        $tickets_awaiting_reply_by_status = $this->dashboard_model->tickets_awaiting_reply_by_status();
        $tickets_awaiting_reply_by_department = $this->dashboard_model->tickets_awaiting_reply_by_department();

        $data['tickets_reply_by_status'] = json_encode($tickets_awaiting_reply_by_status);
        $data['tickets_awaiting_reply_by_department'] = json_encode($tickets_awaiting_reply_by_department);

        $data['tickets_reply_by_status_no_json'] = $tickets_awaiting_reply_by_status;
        $data['tickets_awaiting_reply_by_department_no_json'] = $tickets_awaiting_reply_by_department;

        $data['projects_status_stats'] = json_encode($this->dashboard_model->projects_status_stats());
        $data['leads_status_stats'] = json_encode($this->dashboard_model->leads_status_stats());
        $data['google_ids_calendars'] = $this->misc_model->get_google_calendar_ids();
        $data['bodyclass'] = 'dashboard invoices-total-manual';
        $this->load->model('announcements_model');
        $data['staff_announcements'] = $this->announcements_model->get();
        $data['total_undismissed_announcements'] = $this->announcements_model->get_total_undismissed_announcements();

        $this->load->model('projects_model');
        $data['projects_activity'] = $this->projects_model->get_activity('', hooks()->apply_filters('projects_activity_dashboard_limit', 20));
        add_calendar_assets();
        $this->load->model('utilities_model');
        $this->load->model('estimates_model');
        $data['estimate_statuses'] = $this->estimates_model->get_statuses();

        $this->load->model('proposals_model');
        $data['proposal_statuses'] = $this->proposals_model->get_statuses();

        $wps_currency = 'undefined';
        if (is_using_multiple_currencies()) {
            $wps_currency = $data['base_currency']->id;
        }
        $data['weekly_payment_stats'] = json_encode($this->dashboard_model->get_weekly_payments_statistics($wps_currency));

        $data['dashboard'] = true;

        $data['user_dashboard_visibility'] = get_staff_meta(get_staff_user_id(), 'dashboard_widgets_visibility');

        if (!$data['user_dashboard_visibility']) {
            $data['user_dashboard_visibility'] = [];
        } else {
            $data['user_dashboard_visibility'] = unserialize($data['user_dashboard_visibility']);
            foreach ($data['user_dashboard_visibility'] as $k => $w) {
                if (!$this->app_acl->component_loaded('project_management')) {
                    if ($w['id'] == 'projects_chart') {
                        unset($data['user_dashboard_visibility'][$k]);
                    }
                    if ($w['id'] == 'projects_activity') {
                        unset($data['user_dashboard_visibility'][$k]);
                    }


                }
                if (!$this->app_acl->component_loaded('finance')) {
                    if ($w['id'] == 'weekly_payments_chart') {
                        unset($data['user_dashboard_visibility'][$k]);
                    }
                    if ($w['id'] == 'finance_overview') {
                        unset($data['user_dashboard_visibility'][$k]);
                    }

                }

                if (!$this->app_acl->component_loaded('contracts')) {
                    if ($w['id'] == 'contracts_expiring') {
                        unset($data['user_dashboard_visibility'][$k]);
                    }

                }

                if (!$this->app_acl->component_loaded('agenda')) {
                    if ($w['id'] == 'today_appointments') {
                        unset($data['user_dashboard_visibility'][$k]);
                    }

                }


                if (!$this->app_acl->component_loaded('sales')) {
                    if ($w['id'] == 'commission') {
                        unset($data['user_dashboard_visibility'][$k]);
                    }

                }


                if (!$this->app_acl->component_loaded('utilities')) {
                    if ($w['id'] == 'todos') {
                        unset($data['user_dashboard_visibility'][$k]);
                    }

                }

                if (!$this->app_acl->component_loaded('sales')) {
                    if ($w['id'] == 'leads_chart') {
                        unset($data['user_dashboard_visibility'][$k]);
                    }

                }
            }
            //pre($data['user_dashboard_visibility']);
        }


        $data['user_dashboard_visibility'] = json_encode($data['user_dashboard_visibility']);


        $data = hooks()->apply_filters('before_dashboard_render', $data);
        $this->load->view('admin/dashboard/dashboard', $data);
    }

    public function inbound_lead_generation()
    {
        if (!has_permission('okr', '', 'view') && !has_permission('okr', '', 'view_own') && !is_admin()) {
            //access_denied('okr');
        }
        $this->load->language('dashboard');
        $data['title'] = _l('dashboard');
        $data['colors']['primary'] = '#1caf9a';
        $data['colors']['greyed'] = '#dee2e6 ';
        $data['colors']['secondary'] = '#17A2B8';


        $this->load->view('admin/dashboard/inbound_lead_generation', $data);
    }

    public function inbound_lead_generation_ajax()
    {
        if ($this->input->is_ajax_request()) {


            echo '{"draw":1,"iTotalRecords":"1",
                "iTotalDisplayRecords":"1",
                "aaData":[{"0":"Organic Search","1":"22"}]}';
        }
    }

    public function helpdesk()
    {
        if (!has_permission('okr', '', 'view') && !has_permission('okr', '', 'view_own') && !is_admin()) {
            //access_denied('okr');
        }
        $this->load->language('dashboard');
        $data['title'] = _l('dashboard');
        $data['colors']['primary'] = '#e2202e';
        $data['colors']['greyed'] = '#cccccc';
        $data['colors']['secondary'] = '#D6E9C6';


        $this->load->view('admin/dashboard/helpdesk', $data);
    }

    public function sales_conversion()
    {
        if (!has_permission('okr', '', 'view') && !has_permission('okr', '', 'view_own') && !is_admin()) {
            //access_denied('okr');
        }
        $this->load->language('dashboard');
        $data['title'] = _l('dashboard');
        $data['colors']['primary'] = '#1caf9a';
        $data['colors']['greyed'] = '#dee2e6 ';
        $data['colors']['secondary'] = '#17A2B8';


        $this->load->view('admin/dashboard/sales_conversion', $data);
    }

    public function tactical_finance()
    {
        if (!has_permission('okr', '', 'view') && !has_permission('okr', '', 'view_own') && !is_admin()) {
            //access_denied('okr');
        }
        $this->load->language('dashboard');
        $data['title'] = _l('dashboard');
        $data['colors']['primary'] = '#e2202e';
        $data['colors']['greyed'] = '#cccccc';
        $data['colors']['secondary'] = '#D6E9C6';

        $this->load->view('admin/dashboard/tactical_finance', $data);
    }

    public function cfo()
    {
        if (!has_permission('okr', '', 'view') && !has_permission('okr', '', 'view_own') && !is_admin()) {
            //access_denied('okr');
        }
        $this->load->language('dashboard');
        $data['title'] = _l('dashboard');
        $data['colors']['primary'] = '#1caf9a';
        $data['colors']['greyed'] = '#dee2e6 ';
        $data['colors']['secondary'] = '#17A2B8';


        $this->load->view('admin/dashboard/cfo', $data);
    }

    public function cmo()
    {
        if (!has_permission('okr', '', 'view') && !has_permission('okr', '', 'view_own') && !is_admin()) {
            //access_denied('okr');
        }
        $this->load->language('dashboard');
        $data['title'] = _l('dashboard');
        $data['colors']['primary'] = '#1caf9a';
        $data['colors']['greyed'] = '#dee2e6 ';
        $data['colors']['secondary'] = '#17A2B8';


        $this->load->view('admin/dashboard/cmo', $data);
    }

    public function ceo()
    {
        $this->load->language('dashboard');
        $data['title'] = _l('dashboard');
        $data['colors']['primary'] = '#1caf9a';
        $data['colors']['greyed'] = '#dee2e6 ';
        $data['colors']['secondary'] = '#17A2B8';


        $this->load->view('admin/dashboard/ceo', $data);
    }

    public function sales_cycle()
    {
        if (!has_permission('okr', '', 'view') && !has_permission('okr', '', 'view_own') && !is_admin()) {
            //access_denied('okr');
        }
        $this->load->language('dashboard');
        $data['title'] = _l('dashboard');
        $data['colors']['primary'] = '#e2202e';
        $data['colors']['greyed'] = '#cccccc';
        $data['colors']['secondary'] = '#D6E9C6';


        $this->load->view('admin/dashboard/sales_cycle', $data);
    }

    public function sales_kpi()
    {
        if (!has_permission('okr', '', 'view') && !has_permission('okr', '', 'view_own') && !is_admin()) {
            //access_denied('okr');
        }
        $this->load->language('dashboard');
        $data['title'] = _l('dashboard');
        $data['colors']['primary'] = '#e2202e';
        $data['colors']['greyed'] = '#cccccc';
        $data['colors']['secondary'] = '#D6E9C6';


        $this->load->view('admin/dashboard/sales_kpi', $data);
    }

    public function sales_opportunity()
    {
        if (!has_permission('okr', '', 'view') && !has_permission('okr', '', 'view_own') && !is_admin()) {
            //access_denied('okr');
        }
        $this->load->language('dashboard');
        $data['title'] = _l('dashboard');
        $data['colors']['primary'] = '#e2202e';
        $data['colors']['greyed'] = '#cccccc';
        $data['colors']['secondary'] = '#D6E9C6';


        $this->load->view('admin/dashboard/sales_opportunity', $data);
    }

    public function legal()
    {
        if (!has_permission('dashboard', '', 'view')) {
            //access_denied('okr');
        }
        close_setup_menu();

        if (!has_permission('contracts', '', 'view') && !has_permission('contracts', '', 'view_own')) {
            access_denied('contracts');
        }
        $this->load->model('contracts_model');
        $this->load->language('dashboard');
        $data['title'] = _l('dashboard');

        $data['expiring'] = $this->contracts_model->get_contracts_about_to_expire(get_staff_user_id());
        $data['count_active'] = count_active_contracts();
        $data['count_expired'] = count_expired_contracts();
        $data['count_recently_created'] = count_recently_created_contracts();
        $data['count_trash'] = count_trash_contracts();
        $data['chart_types'] = json_encode($this->contracts_model->get_contracts_types_chart_data());
        $data['chart_types_values'] = json_encode($this->contracts_model->get_contracts_types_values_chart_data());
        $data['contract_types'] = $this->contracts_model->get_contract_types();
        $data['years'] = $this->contracts_model->get_contracts_years();
        $this->load->model('currencies_model');
        $data['base_currency'] = $this->currencies_model->get_base_currency();

        $this->load->view('admin/dashboard/legal', $data);
    }


    /* Chart weekly payments statistics on home page / ajax */
    public function weekly_payments_statistics($currency)
    {
        if ($this->input->is_ajax_request()) {
            echo json_encode($this->dashboard_model->get_weekly_payments_statistics($currency));
            die();
        }
    }

    /**
     * @return mixed
     */
    public function onboarding()
    {
        if (!has_permission('dashboard', '', 'view')) {
            access_denied('dashboard');
        }
        close_setup_menu();

        $this->load->language('dashboard');
        $this->load->model('leads_model');
        $this->load->model('contracts_model');
        $this->load->model('departments_model');
        $this->load->model('custom_fields_model');

        $data['title'] = _l('Onboarding');

        if (get_option('invoice_company_name') && get_option('invoice_company_address') && get_option('invoice_company_city') && get_option('company_vat')) {
            $data['completion_company_data'] = true;
        } else {
            $data['completion_company_data'] = false;
        }

        if (get_option('company_logo')) {
            $data['upload_logo'] = true;
        } else {
            $data['upload_logo'] = false;
        }

        if (get_option('email_protocol') == 'smtp' && get_option('smtp_encryption') && get_option('smtp_host') && get_option('smtp_port') && get_option('smtp_email')) {
            $data['personalization_emails_system'] = true;
        } elseif (get_option('email_protocol') == 'crmconnect' && get_option('email_signature') && get_option('smtp_email_charset')) {
            $data['personalization_emails_system'] = true;
        } else {
            $data['personalization_emails_system'] = false;
        }

        if (get_option('invoice_company_name') && get_option('company_vat') && get_option('company_trade') && get_option('invoice_company_address') && get_option('invoice_company_city') && get_option('company_state')) {
            $data['billing_setup'] = true;
        } else {
            $data['billing_setup'] = false;
        }


        if (get_option('instance_id') && get_option('company_vat')) {
            $data['e_invoice_activation'] = true;
        } else {
            $data['e_invoice_activation'] = false;
        }

        $roles = $this->roles_model->get_all_roles();
        if ($roles) {
            $data['rights_and_permissions'] = true;
        } else {
            $data['rights_and_permissions'] = false;
        }

        $users = $this->roles_model->get_all_users();
        if ($users) {
            $data['add_users_to_the_platform'] = true;
        } else {
            $data['add_users_to_the_platform'] = false;
        }

        if (get_option('decimal_separator') && get_option('thousand_separator') && get_option('number_padding_prefixes') && get_option('show_tax_per_item') && get_option('default_tax')) {
            $data['financial_internal_rules'] = true;
        } else {
            $data['financial_internal_rules'] = false;
        }

        $pipelines = $this->leads_model->get_pipeline();
        if ($pipelines) {
            $data['establishes_sales_channels'] = true;
        } else {
            $data['establishes_sales_channels'] = false;
        }

        $forms = $this->leads_model->get_forms();
        if ($forms) {
            $data['lead_collection_forms'] = true;
        } else {
            $data['lead_collection_forms'] = false;
        }

        $forms = $this->contracts_model->get_contract_types_all();
        if ($forms) {
            $data['establishes_categories_documents'] = true;
        } else {
            $data['establishes_categories_documents'] = false;
        }

        $contracts = $this->contracts_model->get_all_contracts();
        if ($contracts) {
            $data['establish_templates'] = true;
        } else {
            $data['establish_templates'] = false;
        }

        if (get_option('enable_gdpr')) {
            $data['configure_gdpr'] = true;
        } else {
            $data['configure_gdpr'] = false;
        }

        $departments = $this->departments_model->get_departments();
        if ($departments) {
            $data['configure_the_support_departments'] = true;
        } else {
            $data['configure_the_support_departments'] = false;
        }

        if (get_option('services')) {
            $data['establishes_internal_rules'] = true;
        } else {
            $data['establishes_internal_rules'] = false;
        }

        $job_titles = $this->leads_model->get_job_titles();
        if ($job_titles) {
            $data['lead_segmentation'] = true;
        } else {
            $data['lead_segmentation'] = false;
        }


        if (get_option('leads_kanban_limit')) {
            $data['lead_settings'] = true;
        } else {
            $data['lead_settings'] = false;
        }

        $custom_fields = $this->custom_fields_model->get_all_custom_fields();
        if ($custom_fields) {
            $data['define_custom_fields'] = true;
        } else {
            $data['define_custom_fields'] = false;
        }

        $email = $this->leads_model->get_email_integration();
        if ($email->active) {
            $data['define_lead_email'] = true;
        } else {
            $data['define_lead_email'] = false;
        }

        //$define_custom_fields
        $this->load->view('admin/dashboard/onboarding', $data);
    }
}
