<?php
/**
 * Author: Askarali
 */
class MY_Controller extends CI_Controller{
      public $source_version = "3.5";
      public function __construct()
      {
        parent::__construct();

        //$this->output->enable_profiler(TRUE);

        //Update check disabled - database already updated to 3.5
        //if($this->uri->segment(1) == 'login' && $this->uri->segment(1) != 'setup'){
        //  $this->simple_update_check();
        //}
        
        // Check if we're coming from installation and handle database connection issues
        if($this->uri->segment(1) == 'login' && $this->input->get('from_install')) {
            // Force reload database configuration
            $this->load->database();
        }

        //Used after logout
        if(!empty($this->input->cookie("language"))){
         $this->session->set_userdata('language',$this->input->cookie("language"));
         
         $cookie = array(
            'name'   => 'language',
              'value'  => '',
              'expire' => '0',
              );
          $this->input->set_cookie($cookie);
        }
        //end
        
        $default_lang = ($this->session->has_userdata('language')) ? $this->session->userdata('language') : "English";
        $this->lang->load($default_lang, $default_lang);
      }
      /** Theme URL for static assets (no index.php) so CSS/JS are served directly and don't return 404 HTML */
      private function get_theme_link(){
        $base = rtrim(base_url(), '/');
        if (strpos($base, 'index.php') !== false) {
          $base = preg_replace('#/index\.php/??$#', '/', $base);
        }
        return $base . '/theme/';
      }
      public function load_info(){
        // Skip heavy operations for login page to improve speed
        if($this->uri->segment(1) == 'login' && !$this->session->userdata('logged_in')){
            $this->data = array('theme_link'    => $this->get_theme_link(),
                                'base_url'      => base_url(),
                                'SITE_TITLE'    => 'POS System',
                                'VERSION'       => '3.6',
                                'CURRENCY'      => '$',
                                'CURRENCY_PLACE'=> 'Left',
                                'CURRENCY_CODE' => 'USD',
                                'CUR_DATE'      => date("Y-m-d"),
                                'VIEW_DATE'     => 'd-m-Y',
                                'CUR_TIME'      => date("h:i:s a"),
                                'SYSTEM_IP'     => $_SERVER['REMOTE_ADDR'],
                                'SYSTEM_NAME'   => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
                                'CUR_USERNAME'  => '',
                                'CUR_USERID'    => '',
                                    );
            return;
        }
        
        /*if(strtotime(date("d-m-Y")) >= strtotime(date("05-04-2019"))){
            echo "License Expired! Contact Admin";exit();
          }*/

            //CHECK LANGUAGE IN SESSION ELSE FROM DB
            if(!$this->session->has_userdata('language') && $this->session->has_userdata('logged_in') ){
              $this->load->model('language_model');
              $this->language_model->set(get_current_store_language());
            }
            if($this->session->has_userdata('logged_in')){
              $this->lang->load($this->session->userdata('language'), $this->session->userdata('language'));
            }
            //End

            //If currency not set retrieve from DB
            $this->load_currency_data();
            //end

            

            // Check if database is ready and tables exist
            try {
                // PERFORMANCE: Skip file read check after first successful load (cache in session)
                $db_config_checked = $this->session->userdata('db_config_checked');
                if (!$db_config_checked) {
                    // First check if database configuration has placeholders (only once)
                    $dbConfigPath = APPPATH . 'config/database.php';
                    if (file_exists($dbConfigPath)) {
                        $dbConfigContent = file_get_contents($dbConfigPath);
                        if (strpos($dbConfigContent, '%HOSTNAME%') !== false || 
                            strpos($dbConfigContent, '%USERNAME%') !== false || 
                            strpos($dbConfigContent, '%PASSWORD%') !== false || 
                            strpos($dbConfigContent, '%DATABASE%') !== false) {
                            throw new Exception('Database configuration not properly set up');
                        }
                    }
                    $this->session->set_userdata('db_config_checked', true);
                }
                
                // First check if database connection is working
                if (!$this->db->conn_id) {
                    throw new Exception('Database connection not established');
                }
                
                // PERFORMANCE: Cache site settings in session (only refresh if not cached)
                $cached_site_settings = $this->session->userdata('cached_site_settings');
                if (!$cached_site_settings) {
                    $query =$this->db->select('site_name,version')->where('id',1)->get('db_sitesettings');
                    if($query->num_rows() > 0) {
                        $this->session->set_userdata('cached_site_settings', $query->row());
                        $site_row = $query->row();
                    } else {
                        $site_row = null;
                    }
                } else {
                    $site_row = $cached_site_settings;
                }
                
                if(!$site_row) {
                    // Database not ready, use defaults
                    $this->data = array('theme_link'    => $this->get_theme_link(),
                                        'base_url'      => base_url(),
                                        'SITE_TITLE'    => 'NCS Billing System',
                                        'VERSION'       => '3.6',
                                        'CURRENCY'      => '$',
                                        'CURRENCY_PLACE'=> 'Left',
                                        'CURRENCY_CODE' => 'USD',
                                        'CUR_DATE'      => date("Y-m-d"),
                                        'VIEW_DATE'     => 'd-m-Y',
                                        'CUR_TIME'      => date("h:i:s a"),
                                        'SYSTEM_IP'     => $_SERVER['REMOTE_ADDR'],
                                        'SYSTEM_NAME'   => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '', // Skip slow DNS lookup
                                        'CUR_USERNAME'  => '',
                                        'CUR_USERID'    => '',
                                        );
                    return;
                }

                // PERFORMANCE: Cache store settings in session
                $store_id = $this->session->userdata('logged_in') ? get_current_store_id() : 1;
                $cached_store_settings = $this->session->userdata('cached_store_settings');
                $cached_store_id = $this->session->userdata('cached_store_id');
                
                if (!$cached_store_settings || $cached_store_id != $store_id) {
                    $this->db->select('store_name,timezone,time_format,date_format,decimals,qty_decimals');
                    $this->db->where('id', $store_id);
                    $this->db->from('db_store');
                    $query1 = $this->db->get();
                    
                    if($query1->num_rows() > 0) {
                        $this->session->set_userdata('cached_store_settings', $query1->row());
                        $this->session->set_userdata('cached_store_id', $store_id);
                        $store_row = $query1->row();
                    } else {
                        $store_row = null;
                    }
                } else {
                    $store_row = $cached_store_settings;
                }
                
                if(!$store_row) {
                    // Store table not ready, use defaults
                    $site_name = $site_row ? $site_row->site_name : 'NCS Billing System';
                    $version = $site_row ? $site_row->version : '3.6';
                    $this->data = array('theme_link'    => $this->get_theme_link(),
                                        'base_url'      => base_url(),
                                        'SITE_TITLE'    => $site_name,
                                        'VERSION'       => $version,
                                        'CURRENCY'      => '$',
                                        'CURRENCY_PLACE'=> 'Left',
                                        'CURRENCY_CODE' => 'USD',
                                        'CUR_DATE'      => date("Y-m-d"),
                                        'VIEW_DATE'     => 'd-m-Y',
                                        'CUR_TIME'      => date("h:i:s a"),
                                        'SYSTEM_IP'     => $_SERVER['REMOTE_ADDR'],
                                        'SYSTEM_NAME'   => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '', // Skip slow DNS lookup
                                        'CUR_USERNAME'  => '',
                                        'CUR_USERID'    => '',
                                        );
                    return;
                }
            } catch (Exception $e) {
                // Database error, use defaults
                $this->data = array('theme_link'    => $this->get_theme_link(),
                                    'base_url'      => base_url(),
                                    'SITE_TITLE'    => 'NCS Billing System',
                                    'VERSION'       => '3.6',
                                    'CURRENCY'      => '$',
                                    'CURRENCY_PLACE'=> 'Left',
                                    'CURRENCY_CODE' => 'USD',
                                    'CUR_DATE'      => date("Y-m-d"),
                                    'VIEW_DATE'     => 'd-m-Y',
                                    'CUR_TIME'      => date("h:i:s a"),
                                    'SYSTEM_IP'     => $_SERVER['REMOTE_ADDR'],
                                    'SYSTEM_NAME'   => gethostbyaddr($_SERVER['REMOTE_ADDR']),
                                    'CUR_USERNAME'  => '',
                                    'CUR_USERID'    => '',
                                    );
                return;
            }

            date_default_timezone_set(trim($store_row->timezone));

            $time_format = ($store_row->time_format=='24') ? date("h:i:s") : date("h:i:s a");

            $date_view_format = trim($store_row->date_format);
            $this->session->set_userdata(array('view_date'  => $date_view_format));
            $this->session->set_userdata(array('view_time'  => $store_row->time_format));
            $this->session->set_userdata(array('decimals'  => $store_row->decimals));
            $this->session->set_userdata(array('qty_decimals'  => $store_row->qty_decimals));
            $this->session->set_userdata(array('store_name'  => $store_row->store_name));
            

            $this->data = array('theme_link'    => $this->get_theme_link(),
                                'base_url'      => base_url(),
                                'SITE_TITLE'    => $site_row->site_name,
                                'VERSION'       => $site_row->version,
                                'CURRENCY'      => $this->session->userdata('currency'),
                                'CURRENCY_PLACE'=> $this->session->userdata('currency_placement'),
                                'CURRENCY_CODE' => $this->session->userdata('currency_code'),
                                'CUR_DATE'      => date("Y-m-d"),
                                'VIEW_DATE'     => $date_view_format,
                                'CUR_TIME'      => $time_format,
                                'SYSTEM_IP'     => $_SERVER['REMOTE_ADDR'],
                                'SYSTEM_NAME'   => gethostbyaddr($_SERVER['REMOTE_ADDR']),
                                'CUR_USERNAME'  => $this->session->userdata('inv_username'),
                                'CUR_USERID'    => $this->session->userdata('inv_userid'),
                                'CUR_USERID'    => $this->session->userdata('inv_userid'),
                                    );
            

      }
      public function load_currency_data(){
        // PERFORMANCE: Check if currency already in session (cached)
        if($this->session->userdata('logged_in')){
          // Only query if currency not in session or store changed
          if(!$this->session->userdata('currency') || $this->session->userdata('currency_store_id') != get_current_store_id()){
            $q1=$this->db->query("SELECT a.currency_name,a.currency,a.currency_code,a.symbol,b.currency_placement FROM db_currency a,db_store b WHERE a.id=b.currency_id AND b.id=".get_current_store_id());
                if($q1->num_rows() > 0){
                  $currency = $q1->row()->currency;
                  $currency_placement = $q1->row()->currency_placement;
                  $currency_code = $q1->row()->currency_code;
                  $this->session->set_userdata(array(
                    'currency'  => $currency,
                    'currency_placement'  => $currency_placement,
                    'currency_code'  => $currency_code,
                    'currency_store_id' => get_current_store_id() // Cache store ID to detect changes
                  ));
                } else {
                  // Fallback to base currency if no currency found
                  $base_currency = get_base_currency();
                  $this->session->set_userdata(array(
                    'currency'  => $base_currency ? $base_currency->symbol : '$',
                    'currency_placement'  => 'Right',
                    'currency_code'  => $base_currency ? $base_currency->currency_code : 'USD',
                    'currency_store_id' => get_current_store_id()
                  ));
                }
          }
          // Currency already cached in session, skip query
        }
        else{
          $this->session->set_userdata(array('currency'  => '','currency_placement'  => '','currency_code'  => '')); 
        }
      }

      public function verify_store_and_user_status(){
            $store_rec = get_store_details();
            // No store found (e.g. user has no store assigned and no default store) - set first active store so pages don't break
            if (!$store_rec || !is_object($store_rec)) {
              $safe_id = get_safe_store_id_for_query();
              $this->session->set_userdata('store_id', $safe_id);
              return;
            }
            //STORE ACTIVE OR NOT
            if(!$store_rec->status){
              $this->session->set_flashdata('failed', 'Your Store Temporarily Inactive!');
              redirect('logout');exit;
            }
            //USER ACTIVE OR NOT
            $user_rec = get_user_details();
            if (!$user_rec || !is_object($user_rec)) {
              $this->session->set_flashdata('failed', 'Your account could not be verified.');
              redirect('logout');exit;
            }
            if(!$user_rec->status){
              $this->session->set_flashdata('failed', 'Your account is temporarily inactive!');
              redirect('logout');exit;
            }
      }
      public function load_global($validate_subs='VALIDATE'){
            //Check login or redirect to logout
            if($this->session->userdata('logged_in')!=1){ redirect(base_url().'logout','refresh');    }

            $this->verify_store_and_user_status();

            $this->load_info();
      }

      public function currency($value='',$with_comma=false){
        $value = trim($value);

        if(!empty($value) && is_numeric($value)){
          $value= ($with_comma) ? store_number_format($value) : store_number_format($value,false);
        }

      // Get currency symbol with fallback to base currency
        $currency_symbol = $this->session->userdata('currency');
        if (empty($currency_symbol)) {
          $base_currency = get_base_currency();
          $currency_symbol = $base_currency ? $base_currency->symbol : '$';
        }

        if($this->session->userdata('currency_placement')=='Left'){
          if(!empty($value)){
            return $currency_symbol." ".$value;
          }
          return $currency_symbol."".$value;
          
        }
        else{
          if(!empty($value)){
            return $value." ".$currency_symbol;    
          }
         return $value."".$currency_symbol; 
        }
      }

      

      public function store_wise_currency($store_id,$value=''){

        $q1=$this->db->query("SELECT a.currency_name,a.currency,a.currency_code,a.symbol,b.currency_placement FROM db_currency a,db_store b WHERE a.id=b.currency_id AND b.id=".$store_id);
              $currency = $q1->row()->currency;
              $currency_placement = $q1->row()->currency_placement;
              $currency_code = $q1->row()->currency_code;

        $value = trim($value);
        if(!empty($value) && is_numeric($value)){
          $value=number_format($value,2,'.','');
        }
        if($currency_placement=='Left'){
          if(!empty($value)){
            return $currency." ".$value;
          }
          return $currency."".$value;
          
        }
        else{
          if(!empty($value)){
            return $value." ".$currency;    
          }
         return $value."".$currency; 
        }
      }
      
      public function currency_code($value=''){
        if(!empty($this->session->userdata('currency_code'))){
          if($this->session->userdata('currency_placement')=='Left'){
            return $this->session->userdata('currency_code')." ".$value;
          }
          else{
           return $value." ".$this->session->userdata('currency'); 
          }
        }
        else{
          return $value;
        }
      }
      public function permissions($permissions=''){
          //If he the Admin (check both user id 1 and 2) - Super Admin and Admin
          if($this->session->userdata('inv_userid')==1 || $this->session->userdata('inv_userid')==2){
            return true;
          }

          $tot=$this->db->query('SELECT count(*) as tot FROM db_permissions where permissions="'.$permissions.'" and role_id='.$this->session->userdata('role_id'))->row()->tot;
          if($tot==1){
            return true;
          }
           return false;
        }
        
        public function permission_check($value=''){
          if(!$this->permissions($value)){
             show_error("Access Denied", 403, $heading = "You Don't Have Enough Permission!!");
          }
          return true;
        }
        public function permission_check_with_msg($value=''){
          if(!$this->permissions($value)){
             echo "You Don't Have Enough Permission for this Operation!";
            exit();
          }
          return true;
        }
        public function show_access_denied_page()
        {
          show_error("Access Denied", 403, $heading = "You Don't Have Enough Permission!!");
        }
            //end
        public function get_current_version_of_db(){
          return $this->db->select('version')->from('db_sitesettings')->get()->row()->version;
        }
        
        public function belong_to($table,$rec_id){
          if(!is_it_belong_to_store($table,$rec_id)){
            show_error("Data may not avaialable!!", 403, $heading = "Something Went Wrong!!");
          }
        }

       public function update_db()
        { 
          //Before Login purpose only
          $this->load->model('updates_model');
          $this->updates_model->index();
        }

        public function simple_update_check()
        {
          try {
            // Quick version check and update (optimized)
            $result = $this->db->select('version')->from('db_sitesettings')->get();
            
            if($result->num_rows() > 0) {
              $current_version = $result->row()->version;
              
              if($current_version != '3.5') {
                // Update to current version
                $this->db->query("UPDATE `db_sitesettings` SET `version` = '3.5' WHERE `id` = '1'");
                
                // Show update message and redirect
                echo '<!DOCTYPE html>
                <html>
                <head>
                  <title>Updating System...</title>
                  <style>
                    body { font-family: Arial, sans-serif; text-align: center; padding: 50px; background: #f5f5f5; }
                    .update-box { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); max-width: 400px; margin: 0 auto; }
                    .spinner { border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 40px; height: 40px; animation: spin 2s linear infinite; margin: 20px auto; }
                    @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
                  </style>
                </head>
                <body>
                  <div class="update-box">
                    <h3>System Update</h3>
                    <div class="spinner"></div>
                    <p>Updating to version 3.5...</p>
                    <p><small>Please wait while we update your system.</small></p>
                  </div>
                  <script>
                    setTimeout(function() {
                      window.location.href = "' . base_url('login') . '";
                    }, 2000);
                  </script>
                </body>
                </html>';
                exit();
              }
            }
          } catch (Exception $e) {
            // If update fails, just continue to login
            // This prevents 500 errors
            error_log("Update check failed: " . $e->getMessage());
          }
        }

}