<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Check whether the site is offline or not.
*
*/
class App_settings_hook
{
  public function __construct()
  {
    log_message('debug', 'Accessing Settings hook!');
  }

  public function get_settings()
  {
    if (file_exists(APPPATH . 'config/config.php')) {
      include(APPPATH . 'config/config.php');

      $this->CI = &get_instance();
      $this->CI->load->model('Settings_model', 'Settings');
      $this->CI->load->model('Account_model', 'Account');
      $this->CI->load->model('Work_model', 'Work');
      $this->CI->load->model('Branches_model', 'Branches');
      $this->CI->load->model('User_model', 'User');

      //    Redirect to Login if User session is Empty
      if (strtolower($this->CI->router->fetch_class()) != 'download' && strtolower($this->CI->router->fetch_class()) != 'report_generate' && strtolower($this->CI->router->fetch_class()) != 'attendance' && strtolower($this->CI->router->fetch_class()) != 'backup' && strtolower($this->CI->router->fetch_class()) != 'login' && strtolower($this->CI->uri->segment(1)) != 'api' &&  $this->CI->session->userdata('user_id') == "") {
        redirect(base_url(), 'refresh');
      }

      // Select All (Approved/Non Approved Data in Mobile Default)
      $this->CI->config->set_item('select_data_entry_approval', 'all');
      $this->CI->config->set_item('page_template', '');

      $company_details = $this->CI->Settings->select_settings('*', array("settings_category" => "Company Details"))->result();
      foreach ($company_details as $key => $value) {
        $this->CI->config->set_item($value->settings_name, $value->value);
      }

      $boq_details = $this->CI->Settings->select_settings('*', array("settings_category" => "BOQ"))->result();
      foreach ($boq_details as $key => $value) {
        $this->CI->config->set_item($value->settings_name, $value->value);
      }

      $where = '';
      // $where = "settings_category='User' or settings_category='Labour' or settings_category='HR' or settings_category='Accounts' or settings_category='Tools'";
      $app_settings = $this->CI->Settings->select_settings('*', $where)->result();
      foreach ($app_settings as $key => $value) {
        if($value->settings_category=='Material' && $this->CI->session->userdata('branch_id') != 0){
          $this->CI->config->set_item(str_replace(" ", "_", $value->settings_category) . "_" . $value->settings_name, $value->value_2);
        }else{
          $this->CI->config->set_item(str_replace(" ", "_", $value->settings_category) . "_" . $value->settings_name, $value->value);
        }
      }
      if ($this->CI->config->item('Template_template_file_url_type') == 'local') {
        $this->CI->config->set_item('Template_template_file_url', base_url());
      }

      // Set Time Zone Globally
      date_default_timezone_set($this->CI->config->item('Server_timezone'));

      $this->CI->config->set_item('Measurement_Sides', array("LHS","RHS","Center","U","BHS","Round","None"));
      // Tax Types
      $tax_types = $this->CI->Settings->select_tax_types('*', $where)->result();
      $tax_percentages = array();
      foreach ($tax_types as $row) {
        $tax_percentages[] = $row->tax_percentage;
        if ($this->CI->config->item('Tax_tax_splitting') == 1) {
          $tax1_name = $this->CI->config->item('Tax_tax1_name');
          $tax2_name = $this->CI->config->item('Tax_tax2_name');
          $tax3_name = $this->CI->config->item('Tax_tax3_name');
          $tax_name = $row->tax_percentage . "%";
          $tax_name_split = '';
          if ($row->tax1_percent != 0) {
            $tax_name_split .= $tax1_name . '@' . $row->tax1_percent . '%, ';
          }
          if ($row->tax2_percent != 0) {
            $tax_name_split .= $tax2_name . '@' . $row->tax2_percent . '%, ';
          }
          if ($row->tax3_percent != 0) {
            $tax_name_split .= $tax3_name . '@' . $row->tax3_percent . '%, ';
          }
          if ($tax_name_split != '') {
            $tax_name_split = rtrim($tax_name_split, ', ');
            $tax_name .= " (" . $tax_name_split . ")";
          }
        } else {
          $tax_name = $row->tax_percentage . "%";
        }
        $row->tax_name = $tax_name;
      }
      $tax_percentages = array_unique($tax_percentages);
      $this->CI->config->set_item('Tax_tax_percent', $tax_types);
      $this->CI->config->set_item('Tax_tax_percent_old', $tax_percentages);

      $branch_id = $this->CI->session->userdata('branch_id');

      if ($branch_id == 0) {
        $this->CI->config->set_item("company_branches", $this->CI->Branches->select_branches('*', array('branch_active_status' => 1))->result());
        $default_branch_data['branch_name'] = 'No Branch';
        $default_branch_data['quotation_prefix'] = $this->CI->config->item('quotation_prefix');
        $default_branch_data['quotation_header'] = $this->CI->config->item('quotation_header');
        $default_branch_data['quotation_footer'] = $this->CI->config->item('quotation_footer');
        $default_branch_data['workorder_prefix'] = $this->CI->config->item('workorder_prefix');
        $default_branch_data['workorder_header'] = $this->CI->config->item('workorder_header');
        $default_branch_data['workorder_footer'] = $this->CI->config->item('workorder_footer');
        $default_branch_data['workorder_logo'] = $this->CI->config->item('workorder_logo');
        $default_branch_data['sales_estimation_logo'] = $this->CI->config->item('sales_estimation_logo');
        $this->CI->config->set_item("default_branch_data",$default_branch_data);
      }

      $this->CI->config->set_item('fin_year_id', 1);
      $fin_year = $this->CI->Settings->select_finyear('*', array("active_status" => 1));
      if($fin_year->num_rows()==1){
        $this->CI->config->set_item('fin_year_id', $fin_year->row()->finyear_id);
        $this->CI->config->set_item('fin_year', $fin_year->row()->fin_year);
      }

      $app_modules = $this->CI->Settings->select_settings_modules('*')->result();
      foreach ($app_modules as $key => $value) {
        $this->CI->config->set_item("app_module_" . $value->module_name, $value->active_status);
      }

      if ($this->CI->session->userdata('user_id') && $this->CI->session->userdata('user_id') != '' && $this->CI->session->userdata('user_id') != NULL) {
        $this->CI->config->set_item('user_role', $this->CI->session->userdata('user_role'));
        $this->CI->config->set_item('user_directory', $this->CI->session->userdata('user_role') . "/");

        if($this->CI->session->userdata('user_role')=='admin' || $this->CI->session->userdata('user_role')=='qs' || $this->CI->session->userdata('user_role')=='qs_manager' || $this->CI->session->userdata('user_role')=='project_manager' || $this->CI->session->userdata('user_role')=='hr_manager' || $this->CI->session->userdata('user_role')=='operation_manager' || $this->CI->session->userdata('user_role')=='procurement_engineer' || $this->CI->session->userdata('user_role')=='auditor' || $this->CI->session->userdata('user_role')=='accounts_manager' || $this->CI->session->userdata('user_role')=='purchase_manager' || $this->CI->session->userdata('user_role_id')==20 || ($this->CI->session->userdata('user_role')=='general_manager' && $this->CI->config->item('User_general_manager_data_access_view_all')==1)){
          $this->CI->config->set_item('user_data_access_view_all',1);
        }else{
          $this->CI->config->set_item('user_data_access_view_all',0);
        }
        if ($this->CI->session->userdata('user_role') == 'supervisor' || ($this->CI->session->userdata('user_role') == 'general_manager' && $this->CI->config->item('User_general_manager_tr_user_accounts_only') == "1")) {
          $this->CI->config->set_item('account_heads', $this->CI->Account->select_account_heads("", array("ah.acc_user_id" => $this->CI->session->userdata('user_id'), 'ah.acc_head_branch_id' => $branch_id))->result());
        } else {
          if ($this->CI->config->item('Accounts_admin_user_account_heads_selectable') == 1) {
            $this->CI->config->set_item('account_heads', $this->CI->Account->select_account_heads("", "(ah.account_type=32 or ah.account_type=36) and ah.acc_head_branch_id=$branch_id ")->result());
          } else {
            $this->CI->config->set_item('account_heads', $this->CI->Account->select_account_heads("", "(ah.account_type=32 or ah.account_type=36) and ah.acc_employee_id=0 and ah.acc_head_branch_id=$branch_id")->result());
          }
        }
        $this->CI->config->set_item('expense_heads', $this->CI->Account->select_account_heads("", "ah.account_type=11 and ah.acc_head_branch_id=$branch_id")->result());
        $this->CI->config->set_item('payment_modes', unserialize($this->CI->Settings->select_settings("value", array("settings_name" => 'payment_modes'))->row()->value));
      }
      // $this->CI->config->set_item('ta_vehicles',array(array('type'=>'Bus','fixed_rate'=>0,'rate'=>0),array('type'=>'Car','fixed_rate'=>1,'rate'=>4),array('type'=>'Auto Rikshaw','fixed_rate'=>0,'rate'=>0),array('type'=>'Train','fixed_rate'=>0,'rate'=>0),array('type'=>'Two Wheeler','fixed_rate'=>1,'rate'=>2),array('type'=>'Others','fixed_rate'=>0,'rate'=>0)));
      $this->CI->config->set_item('project_sections', $this->CI->Work->select_project_sections("")->result());

      // $currency_format = new NumberFormatter('en_IN', NumberFormatter::CURRENCY);
      $currency_format = new NumberFormatter($this->CI->config->item('Currency_currency_formatter'), NumberFormatter::DECIMAL);
      $currency_format->setTextAttribute(NumberFormatter::CURRENCY_CODE, $this->CI->config->item('Currency_currency_shortname'));
      $currency_format->setAttribute(NumberFormatter::FRACTION_DIGITS, $this->CI->config->item('Currency_amount_decimals_2'));
      $this->CI->config->set_item('currency_format',$currency_format);

      function CurrencyFormat($amount, $dec_count = 0)
      {
        $amount = number_format($amount, $dec_count);
        $amount = str_replace(',', '', $amount);
        $amount_prefix = '';
        if (strpos($amount, '-') !== false) {
          $amount = str_replace('-', '', $amount);
          $amount_prefix = '-';
        }
        if (strpos($amount, '+') !== false) {
          $amount = str_replace('+', '', $amount);
          $amount_prefix = '+';
        }

        $explrestunits = "";
        if($amount!=''){
          $amount = preg_replace('/,+/', '', $amount);
        }
        $words = explode(".", $amount);
        $des = "";
        for ($i = 0; $i < $dec_count; $i++) {
          $des .= "0";
        }

        if (count($words) <= 2) {
          $amount = $words[0];
        }
        if (count($words) >= 2) {
          $des = $words[1];
        }
        if ($dec_count > 0) {
          if (strlen($des) < $dec_count) {
            $des = "$des";
          } else {
            $des = substr($des, 0, $dec_count);
          }
        } else {
          $des = "";
        }

        if (strlen($amount) > 3) {
          $lastthree = substr($amount, strlen($amount) - 3, strlen($amount));
          $restunits = substr($amount, 0, strlen($amount) - 3); // extracts the last three digits
          $restunits = (strlen($restunits) % 2 == 1) ? "0" . $restunits : $restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
          $expunit = str_split($restunits, 2);
          for ($i = 0; $i < sizeof($expunit); $i++) {
            // creates each of the 2's group and adds a comma to the end
            if ($i == 0) {
              $explrestunits .= (int)$expunit[$i] . ","; // if is first value , convert into integer
            } else {
              $explrestunits .= $expunit[$i] . ",";
            }
          }
          $thecash = $explrestunits . $lastthree;
        } else {
          $thecash = $amount;
        }
        if ($des != "") {
          $formatted_value = "$thecash.$des";
        } else {
          $formatted_value = "$thecash";
        }
        if ($amount_prefix != "") {
          $formatted_value = $amount_prefix . $formatted_value;
        }
        return $formatted_value; // writes the final format where $currency is the currency symbol.

      }

      function getIndianCurrency(float $number)
      {
        $decimal = round($number - ($no = floor($number)), 2) * 100;
        $hundred = null;
        $digits_length = strlen($no);
        $i = 0;
        $str = array();
        $words = array(
          0 => '', 1 => 'one', 2 => 'two',
          3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six',
          7 => 'seven', 8 => 'eight', 9 => 'nine',
          10 => 'ten', 11 => 'eleven', 12 => 'twelve',
          13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen',
          16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen',
          19 => 'nineteen', 20 => 'twenty', 30 => 'thirty',
          40 => 'forty', 50 => 'fifty', 60 => 'sixty',
          70 => 'seventy', 80 => 'eighty', 90 => 'ninety'
        );
        $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
        while ($i < $digits_length) {
          $divider = ($i == 2) ? 10 : 100;
          $number = floor($no % $divider);
          $no = floor($no / $divider);
          $i += $divider == 10 ? 1 : 2;
          if ($number) {
            $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
            $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
            $str[] = ($number < 21) ? $words[$number] . ' ' . $digits[$counter] . $plural . ' ' . $hundred : $words[floor($number / 10) * 10] . ' ' . $words[$number % 10] . ' ' . $digits[$counter] . $plural . ' ' . $hundred;
          } else $str[] = null;
        }
        $Rupees = implode('', array_reverse($str));
        $paise = ($decimal > 0) ? "." . ($words[$decimal / 10] . " " . $words[$decimal % 10]) . ' Paise' : '';
        // return ($Rupees ? $Rupees . 'Rupees ' : '') . $paise;
        return ($Rupees ? $Rupees . 'Rupees ' : '');
      }
    }


    if ($this->CI->uri->segment(1)!='' && strtolower($this->CI->uri->segment(1)) != 'api') {
      if($this->CI->session->userdata('user_sub_role_id')){
        $role_where['ur.role_id'] = $this->CI->session->userdata('user_sub_role_id');
      }else{
        $role_where['ur.role_id'] = $this->CI->session->userdata('user_role_id');
      }
      $role_data	= $this->CI->User->select_user_roles("",$role_where);
      // Menu $ Settings
      $menu_group = $this->CI->Settings->select_modules("distinct(module_group)","","module_group")->result();
      foreach ($menu_group as $key0 => $value0) {
        $value0->menu_group_user_active_status = 0;
        $menu = $this->CI->Settings->select_modules("",array("module_group"=>$value0->module_group))->result();
        foreach ($menu as $key => $value) {
          $value->user_active_status = 0;
          $value->submenu = $this->CI->Settings->select_module_elements("",array("me.moduleno"=>$value->moduleno),false)->result();
          foreach ($value->submenu as $key2 => $value2) {
            if($role_data->num_rows()==1 && $role_data->row()->modulemanagement==1 && $role_data->row()->havesubrole==0){
              // Check User Element Exist & Its Values
              if($role_data->row()->modulebasedtype=='account'){ //For Account Based Module Management
                $user_element_where['user_id'] = $this->CI->session->userdata('user_id');
              }else{ //For Role Based Module Management
                if($this->CI->session->userdata('user_sub_role_id') && $this->CI->session->userdata('user_sub_role_id')!=''){
                  $user_element_where['user_id'] = $this->CI->session->userdata('user_sub_role_id');
                }else{
                  $user_element_where['user_id'] = $this->CI->session->userdata('user_role_id');
                }
              }
              $user_element_where['user_id_type'] = $role_data->row()->modulebasedtype;
              $user_element_where['ue.elementno'] = $value2->elementno;
              $user_element_data = $this->CI->Settings->select_user_module_elements("ue.*",$user_element_where,false);
              if($user_element_data->num_rows()==1 && $user_element_data->row()->activestatus==1){
                $value->user_active_status = $value2->user_active_status = 1;
                $value2->user_entry_status = $user_element_data->row()->entrystatus;
                $value2->user_edit_status = $user_element_data->row()->editstatus;
                $value2->user_view_status = $user_element_data->row()->viewstatus;
              }else{
                $value2->user_active_status = 0;
              }
            }elseif($role_data->num_rows()==1 && $role_data->row()->modulemanagement==0 && $role_data->row()->havesubrole==0){
              // For User Role Have modulemanagement Independent
              if($value2->admin_access==1){
                $value->user_active_status = $value2->user_active_status = 1;
                $value2->user_entry_status = 1;
                $value2->user_edit_status = 1;
                $value2->user_view_status = 1;
              }else{
                $value2->user_active_status = 0;
              }
            }else{
              $value2->user_active_status = 0;
            }
          }
          if($value->user_active_status==1){
            $value0->menu_group_user_active_status = 1;
          }
        }
        $value0->menu_list = $menu;
      }
      $this->CI->config->set_item('main_menu',$menu_group);
      // Select Module Elements
      $module_elements = $this->CI->Settings->select_module_elements("*,me.slno as elem_slno","",true)->result();
      $this->CI->config->set_item('module_elements',$module_elements);
    }
  }
}
