<?php

class REF_Controller extends CI_Controller {
    public $user_data;
    public $controller; 
    public function __construct() {
        // To Check session already started or not
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        parent::__construct();
        
        $segments = $this->uri->segments;
        $this->controller = strtolower( $segments[1] );
        $scanAvailability = get_general_setting()->scan_availability;
        
        if( $this->controller == 'scan' && !defined('NO_RELOAD') ) :
            if($scanAvailability == 1) :
                redirect('kiosk/scan/'. $segments[2]);
            else :
                scan_unavailable_error();
            endif;
        endif;
        
        $this->user_data = get_user_data();
        $log_type = !empty( $this->user_data['log_type'] ) ? $this->user_data['log_type'] : $segments[3];
        
        define('IS_LOGGED', !empty($this->user_data) ? TRUE : FALSE );
        define('IS_KSK', $this->controller == 'kiosk' || $this->user_data['is_kiosk'] || (!IS_LOGGED && $this->controller != 'admin') || ( IS_LOGGED && $this->user_data['role'] != '3' ) ? TRUE : FALSE );
        define('IS_KSK_CMS', IS_KSK && strtolower( $segments[3] ) == 'kiosk' ? TRUE : FALSE ); // For CMS Mode KIOSK (Madapalli, Prasadam, Daily Report link from KIOSK Home page Menu )
        
        define('IS_KSK_ADMIN', IS_LOGGED && IS_KSK && $log_type == 'admin' ? TRUE : FALSE);
        define('IS_KSK_BILL', IS_LOGGED && IS_KSK && $log_type == 'bill' ? TRUE : FALSE);
        if( !defined('BASE_URL') ) define( 'BASE_URL', base_url() );

        if( IS_LOGGED ) :
            
            if( !isset( $_SERVER['HTTP_REFERER'] ) && !empty( $this->controller ) && $this->controller != 'admin' ) :
                // Direct Access
                //#die('<style>body{overflow: hidden; background: url(../../assets/images/bg.jpg);}</style><div style="width: 80%; margin: 20% auto; text-align: center; font-size: 30px; font-style: oblique; color: #999; text-shadow: 1px 1px 3px #999; letter-spacing: 3px; padding: 40px;"><marquee style="width: 500px; display: inline-flex; margin-right: 20px;">Direct Access is not allowed!</marquee><a href="'. base_url() . ( IS_KSK ? '' : 'home' ) .'">Go to Home!</a></div>');
            endif;    
            
            $this->config->set_item('css_url', base_url() . 'assets/css/');
            $this->config->set_item('js_url', base_url() . 'assets/js/');
            $this->config->set_item('images_url', base_url() . 'assets/images/');
            //if( $this->user_data['role'] == '3' ) :
                // Super Admin
                $all_permissions = check_permission();
                //echo "<pre> Data: "; print_r($all_permissions); die;
            //endif;
            
            $pstatus = $this->session->flashdata( REMOTE_ADDR . '_flag' );  
            if( !TO_PRINT && $pstatus != 'NO' && ( $segments[2] == 'add' || $segments[2] == 'edit' ) ) :
                $this->session->set_flashdata( REMOTE_ADDR . '_flag', 'N' );  
            endif; 
            
            /*
             * Server Down
             */
            if( $this->user_data['server_down'] == "1" ) :
            
                /*
                 *  Running on ALt. Server
                 */

                // Disable all actions, except "Insert"
                $post = $this->input->post();
                if( $segments[1] != 'general_settings' && ($segments[2] == 'edit' || $segments[2] == 'update' || $segments[2] == 'delete' || strtolower( $post['submit'] ) == 'update') ) :
                    // NOt Insert
                    server_down_error();
                endif;
                        
            else :
                
                if( $this->user_data['alt_count'] > 0 ) :
                    $pstatus = $this->session->flashdata( REMOTE_ADDR . '_flag' ); 
                    if( $this->user_data['role'] == '3' && !IS_KSK && empty( $pstatus ) ) :
                        // Intimate to super admin.
                        $this->session->set_flashdata( REMOTE_ADDR . '_flag', 'SERVER_DOWN' );

                    endif;
                endif;    
                
            endif;
                
            /* Data initialization for render function */
            $this->data = array();
            if (!empty($_SESSION['success'])) {
                $this->data['success'] = $_SESSION['success'];
                unset($_SESSION['success']);
            }
            else if (!empty($_SESSION['error'])) {
                $this->data['error'] = $_SESSION['error'];
                unset($_SESSION['error']);
            }

            $actions = $this->actions();
            $this->data['list_link']    = $actions['index'];
            $this->data['add_link']     = $actions['add'] . '/';
            $this->data['edit_link']    = $actions['edit'] . '/';
            $this->data['view_link']    = $actions['view'] . '/';
            $this->data['delete_link']  = $actions['delete'] . '/';
            $this->data['add_action']   = $actions['insert'] . '/';
            $this->data['edit_action']  = $actions['update'] . '/';
            $this->data['all_permissions'] = $all_permissions;

            $this->config->set_item('css_url', base_url() . 'assets/css/');
            $this->config->set_item('js_url', base_url() . 'assets/js/');
            $this->config->set_item('images_url', base_url() . 'assets/images/');
            $this->config->set_item('upload_url', base_url() . UPLOADS);
        //elseif( (!empty( $this->controller ) && $this->controller != 'admin' && empty( $_POST['act'] ) && strpos('print', $segments[2]) == -1) && !defined('NO_RELOAD') ):
        elseif( (!empty( $this->controller ) && $this->controller != 'admin' && $this->controller != 'kiosk' && empty( $_POST['act'] ) && $this->controller != 'billing_common' ) && !defined('NO_RELOAD') ):
            // Redirect to login
            redirect(base_url().( IS_KSK ? '' : 'admin' ));
        endif;
    }
    
    public function render($data, $view_file = '') {
        $this->user_data = get_user_data();
        $header = $footer = array();
        $header = get_header_data();
        #$header['permission'] = $this->permission;
        $header['controller'] = $this->controller;
        $header['view_file'] = (!empty($view_file)) ? $view_file : 'home';
        $data['user_data'] = $header['user_data'] = $footer['user_data'] = $this->user_data;
        
        $is_kiosk = $data['is_kiosk'] || (!empty($this->user_data) && $this->user_data['role'] != '3') ? TRUE : FALSE;
        
        // To set custom header datas from controllers
        if (!empty($data['header'])) {
            foreach($data['header'] as $key => $value) {
                $header[$key] = $value;
            }
        }
        
        $head = array();
        $header['log_type'] = $footer['log_type'] = $data['log_type'];
        $data['permission'] = (!empty($this->permission)) ? $this->permission : array();
        $header['all_permissions'] = $this->data['all_permissions'];
        $head['page_title'] = $header['page_title'];
        // Some code happens here
        
        $is_ksk_head = $this->controller == 'billing_archanai' || (!IS_LOGGED && IS_KSK) ? TRUE : FALSE;
        
        // Load Views
        if(  $is_ksk_head ) :
            // Kiosk
            $header['settings'] = get_basic_setting();
            $this->load->view('billing/header', $header);
        
        else :
            // CMS
            $this->load->view('templates/head', $head);
            if( !IS_KSK_BILL && !IS_KSK_CMS ) :
                $this->load->view('templates/header', $header);
            endif;
        endif;
         
        $args = array_merge($header, $data, $footer);
        $this->load->view('templates/common', $args);
        $this->load->view($view_file, $data);
         
        if( $is_ksk_head ) :
            // Kiosk
            $this->load->view('billing/footer', $footer);
        else :
            // CMS
            $this->load->view('templates/footer', $footer);
        endif;
        
    }
    
    protected function actions($controller = '') {
        $action = array();
        $controller = (empty($controller)) ? $this->router->fetch_class() : $controller;
        $action['index']  = base_url() . $controller . '/index';
        $action['view']   = base_url() . $controller . '/view';
        $action['add']    = base_url() . $controller . '/add';
        $action['insert'] = base_url() . $controller . '/insert';
        $action['edit']   = base_url() . $controller . '/edit';
        $action['update'] = base_url() . $controller . '/update';
        $action['delete'] = base_url() . $controller . '/delete';
        $action['controller'] = $controller;
        
        return $action;
    }

    protected function auto_generation_code($id, $prefix='') {  
        $code = $prefix;
        return ($id > 999) ? $id : sprintf('%03d', $id);
    }
    
    protected function ajax_response($data) {
        echo json_encode($data, JSON_UNESCAPED_SLASHES);
        exit(0);
    }
}
?>