<?php

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

class AdminController extends App_Controller
{
    public function __construct()
    {
        parent::__construct();

        if ($this->app->is_db_upgrade_required($this->current_db_version)) {
            if ($this->input->post('upgrade_database')) {
                hooks()->do_action('pre_upgrade_database');

                $this->app->upgrade_database();
            } else {
                hooks()->do_action('pre_upgrade_database');

                $this->app->upgrade_database();
            }
            $update = $this->app->upgrade_database_silent();
        }

        hooks()->do_action('pre_admin_init');

        if (!is_staff_logged_in()) {
            if (strpos(current_full_url(), get_admin_uri() . '/authentication') === false) {
                redirect_after_login_to_current_url();
            }

            redirect(admin_url('authentication'));
        }

        if ($this->uri->segment(3) != 'notifications_check') {
            // In case staff have setup logged in as client - This is important don't change it
            foreach (['client_user_id', 'contact_user_id', 'client_logged_in', 'logged_in_as_client'] as $sk) {
                if ($this->session->has_userdata($sk)) {
                    $this->session->unset_userdata($sk);
                }
            }
        }

        // Update staff last activity
        $this->db->where('staffid', get_staff_user_id());
        $this->db->update('staff', ['last_activity' => date('Y-m-d H:i:s')]);

        $this->load->model('staff_model');


        // Do not check on ajax requests
        if (!$this->input->is_ajax_request()) {
            if (ENVIRONMENT == 'production' && is_admin()) {
                if ($this->config->item('encryption_key') === '') {
                    die('<h1>Encryption key not sent in application/config/app-config.php</h1>');
                } elseif (strlen($this->config->item('encryption_key')) != 32) {
                    die('<h1>Encryption key length should be 32 charachters</h1>');
                }
            }

            _maybe_system_setup_warnings();

            $this->init_quick_actions_links();
        }

        $currentUser = $this->staff_model->get(get_staff_user_id());


        // Deleted or inactive but have session
        if (!$currentUser || $currentUser->active == 0) {
            $this->authentication_model->logout();
            redirect(admin_url('authentication'));
        }

        if (is_assist_mode()) {
            $this->cards = $this->staff_model->get_card_assist(extract_id($this->uri->uri_string()));
        } else {
            $this->cards = null;
        }

        $GLOBALS['current_user'] = $currentUser;

        init_admin_assets();

        hooks()->do_action('admin_init');

        $vars = [
            'current_user' => $currentUser,
            'current_version' => $this->current_db_version,
            'task_statuses' => $this->tasks_model->get_statuses(),
        ];
        $this->db->where('staffid!=' . $currentUser->staffid);
        $this->db->where('active', 1);

        $this->db->where('name', 'chat_status');
        $this->db->where('value', 'online');

        $this->db->where(db_prefix() . 'staff.last_activity >= (NOW() - INTERVAL 30 minute)');

        $this->db->join(db_prefix() . 'chatsettings', 'user_id=staffid');
        $this->db->group_by('staffid');
        $this->db->group_by('chatsettings.id');
        $query = $this->db->get(db_prefix() . 'staff');
        if (!empty($query)) {
            $vars['onlineStaffs'] = $query->result_array();
            $onlineIds = array_column($vars['onlineStaffs'], 'staffid');
        } else {
            $vars['onlineStaffs'] = null;
            $onlineIds = null;
        }
        //echo '<pre>';var_dump($vars['onlineStaffs']); exit;
        $onlineIds = array_column($vars['onlineStaffs'], 'staffid');

        $this->db->where('active', 1);
        $this->db->where('name', 'chat_status');
        $this->db->where('staffid!=' . $currentUser->staffid);
        if (empty($onlineIds)) {
            $onlineIds = NULL;
        }
        $this->db->where_not_in('staffid', $onlineIds);
        $this->db->join(db_prefix() . 'chatsettings', 'user_id=staffid', 'LEFT');
        $vars['offlineStaffs'] = $this->db->get(db_prefix() . 'staff')->result_array();

        $this->db->where(db_prefix() . 'clients.active', 1);
        $this->db->where(db_prefix() . 'contacts.last_login BETWEEN (now() - interval 30 minute) AND NOW()');
//            $this->db->where_not_in('id',$onlineIds);
        $this->db->join(db_prefix() . 'clients', db_prefix() . 'clients.userid=' . db_prefix() . 'contacts.userid');
//            $this->db->join(db_prefix().'chatsettings','user_id=staffid');
        $vars['onlineClients'] = $this->db->get(db_prefix() . 'contacts')->result_array();


        $this->db->where(db_prefix() . 'clients.active', 1);
//            $this->db->where_not_in('id',$onlineIds);
//            $this->db->join(db_prefix().'chatsettings','user_id=staffid');
        $this->db->where('(' . db_prefix() . 'contacts.last_login <= (now() - interval 30 minute) OR `' . db_prefix() . 'contacts`.`last_login` IS NULL)', false, false);
        $this->db->join(db_prefix() . 'clients', db_prefix() . 'clients.userid=' . db_prefix() . 'contacts.userid');
        $vars['offlineClients'] = $this->db->get(db_prefix() . 'contacts')->result_array();

        //$this->db->where('active',1);
//            $this->db->where_not_in('id',$onlineIds);
//            $this->db->join(db_prefix().'chatsettings','user_id=staffid');
        $vars['onlineVendors'] = []; //$this->db->get(db_prefix().'vendor')->result_array();

        //$this->db->where('active',1);
//            $this->db->where_not_in('id',$onlineIds);
//            $this->db->join(db_prefix().'chatsettings','user_id=staffid');
        $vars['offlineVendors'] = []; //$this->db->get(db_prefix().'vendor')->result_array();

        $this->db->limit(10);
        $this->db->order_by('id', 'DESC');
        $vars['sideOkrs'] = $this->db->get(db_prefix() . 'okrs')->result_array();

        //$this->db->where('date > "'.date('Y-m-d 00:00:00').'" AND date < "'.date('Y-m-d 23:59:59').'"');
        //$vars['sideEvents'] = $this->db->get(db_prefix().'hpyevents')->result_array();


        //$this->app_menu->overwrite_menu_items();

        if (!$this->input->is_ajax_request()) {
            $vars['sidebar_menu'] = $this->app_menu->get_sidebar_menu_items();
            $vars['setup_menu'] = $this->app_menu->get_setup_menu_items();
        }

        /**
         * Autoloaded view variables
         * @var array
         */
        $vars = hooks()->apply_filters('admin_area_auto_loaded_vars', $vars);
        $this->load->vars($vars);
    }

    private function init_quick_actions_links()
    {

    }
}
