<?php

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

class App_Controller extends CI_Controller
{
    protected $current_db_version;

    public function __construct()
    {
        parent::__construct();




        $GLOBALS['EXT']->call_hook('pre_controller_constructor');


          if(!$this->input->is_ajax_request()){
              if(ENVIRONMENT == 'testing'){
                $this->output->enable_profiler(TRUE);
              }
              
          }


        /**
         * Fix for users who don't replace all files during update !!!
         */
        if (!class_exists('ForceUTF8\Encoding') && file_exists(APPPATH . 'vendor/autoload.php')) {
            require_once(APPPATH . 'vendor/autoload.php');
        }

        if (is_dir(FCPATH . 'install') && ENVIRONMENT != 'development') {
            //die('<h3>Delete the install folder</h3>');
        }

        if (CI_VERSION != '3.1.11') {
            echo '<h2>Additionally you will need to replace the <b>system</b> folder. We updated Codeigniter to 3.1.11.</h2>';
            echo '<p>From the newest downloaded files upload the <b>system</b> folder to your installation directory.';
            die;
        }

        if (!extension_loaded('mbstring') && (!function_exists('mb_strtoupper') || !function_exists('mb_strtolower'))) {
            die('<h1>"mbstring" PHP extension is not loaded. Enable this extension from cPanel or consult with your hosting provider to assist you enabling "mbstring" extension.</h4>');
        }

        $this->db->reconnect();



        $this->load->library('session');
        if (is_mobile()) {
            $this->session->set_userdata(['is_mobile' => true]);
        } else {
            $this->session->unset_userdata('is_mobile');
        }

        /**
         * Set system timezone based on selected timezone from options
         * @var string
         */
        $timezone = get_option('default_timezone');
        if ($timezone != '') {
            date_default_timezone_set($timezone);
        }


        /**
         * Clear last upgrade copy data
         * @var object
         */
        if ($lastUpdate = get_last_upgrade_copy_data()) {
            if ((time() - $lastUpdate->time) > _delete_temporary_files_older_then()) {
                @unlink($lastUpdate->path);
                update_option('last_upgrade_copy_data', '');
            }
        }


        if(DEFINED('PROCESS_CRM_INSTALLER')){
          $now = date('Y-m-d H:i:s');
          $date_to_maintenance = date('Y-m-d H:i:s', strtotime($now. ' +30 seconds'));
          file_put_contents(APPPATH.'.maintenance',$date_to_maintenance);

          $update = $this->app->upgrade_database_silent();
          if ($update['success'] == false) {
              //show_error($update['message']);
              installer_log('error',$update['message']);
          } else {
            //installer_log('info','ENROLL_EMAIL='.getenv('ENROLL_EMAIL'));
            //installer_log('info','CRM_ADMIN_PASS='.getenv('CRM_ADMIN_PASS'));
            //installer_log('info','active_package='.getenv('active_package'));

            $admin_user = getenv('ENROLL_EMAIL');
            $admin_pass = getenv('CRM_ADMIN_PASS');
            if($admin_user == '' OR !$admin_user){
              $admin_user = 'admin@crmconnect.ai';
            }
            if($admin_pass == '' OR !$admin_pass){
              $admin_user = 'admin@crmconnect.ai';
              $this->load->helper('string');
              $admin_pass = random_string('alnum', 12);
              installer_log('info','random pass = '.$admin_pass);
            }


            $user_id = $this->_create_user($admin_user,$admin_pass);
            $this->load->model('api/api_model');
            $api_uid = $this->api_model->add_user([
              'user' => $admin_user,
              'name' => (getenv('CONTACT_FN') ? getenv('CONTACT_FN') : 'Administrator').' '.getenv('CONTACT_LN'),
              'password' =>$admin_pass,
              'expiration_date'=>'2030-01-01'
            ]);
            $id_package = (int)getenv('active_package');

            $base_url = getenv('APP_BASE_URL');
            //if(endsWith($base_url,'/')){
              //$base_url =
            //}
            $base_url = rtrim($base_url, "/");

            $install_data = [
              'install_date'=>date('Y-m-d H:i:s'),
              'last_migration'=>date('Y-m-d H:i:s'),
              'base_url'=>$base_url,

              'api_token'=>$this->api_model->generated_token,
              'admin_user'=>$admin_user,
              'admin_pass'=>$admin_pass,
              'active_package'=>$id_package,

            ];
            add_option('CRM_INSTALLED',date('Y-m-d H:i:s'));
            $slug  = null;
           if($id_package == 1){
             $slug = 'startup_package';
           }else if($id_package == 2){
             $slug = 'essential_package';
           }else if($id_package == 3){
             $slug = 'pro_package';
           }
           $this->app_modules->initialize();
           $activated = $this->app_modules->activate($slug);

           /*if($slug != null){
           if(isset($this->app_modules)){
             unset($this->app_modules);
           }
           $this->load->library('app_modules');
           //$Amods = new app_modules();

           echo 'activating module...<br>';
             $activated = $this->app_modules->activate($slug);
           //$activated = $Amods->activate($slug);
           //$this->load->library('app_modules',null,'appmods');
           //$activated = $this->appmods->activate($slug);
           if(!$activated){
             echo $slug. ' not activated<br>';
           }else{

             echo $slug. ' activated<br>';
           }
           }*/

           $this->load->library('upgrader');
           $response = $this->upgrader->post_install_data($install_data);
             //die(1);
            redirect(base_url());
          }
          exit;
        }

        $this->load->model('authentication_model');
        $this->authentication_model->autologin();
        if ($this instanceof ClientsController) {
            load_client_language();
        } elseif ($this instanceof AdminController) {
            load_admin_language();
        } else {
            // When App_Controller is only extended or any other CORE controller that is not instance of ClientsController or AdminController
            // Will load the default sytem language, so we can get the locale and language from $GLOBALS;
            load_admin_language();
        }

        $vars             = [];
        $vars['locale']   = $GLOBALS['locale'];
        $vars['language'] = $GLOBALS['language'];

        $this->load->vars($vars);

        $this->current_db_version = $this->app->get_current_db_version();

        hooks()->do_action('app_init');
    }


    private function _create_user($admin_user,$admin_pass){
      $admin_pass = app_hash_password($admin_pass);
      $this->db->insert('staff',[
        //'staffid'=>1,
        'email'=>$admin_user,
        'firstname'=>getenv('CONTACT_FN'),
        'lastname'=>getenv('CONTACT_LN'),
        'password'=>$admin_pass,
        'datecreated'=>date('Y-m-d H:i:s'),
        'admin'=>1,
        'role'=>1,
        'active'=>1
      ]);
      $userid = $this->db->insert_id();
      return $userid;
    }

}
