<?php

/* 
 * Author       : Jai K
 * Purpose      : Access Ajax req. from any of the modules
 * Created On   : 2016-08-25 13:14
 */

class Billing_Common extends REF_Controller {
    
    
    function __construct() {
        parent::__construct();
        
        $this->load->model('billing/common_model');
        
    }
    
    function import(){
        echo json_encode( $this->common_model->import() );
    }
    
    function get_rgb_color( $clr = '' ){
        
        if( $clr[0] != '#' ) :
            
            // RGBA
            preg_match('/^(rgba|rgb)\((.*?)\)/', $clr, $mtch);
            $e = explode(',', $mtch[2]);
            $clr = 'A='.( !empty( $e[3] ) ? $e[3] : '255').', R='.$e[0].', G='. $e[1]. ', B='. $e[2];
            
            
        else :
            // HEx to RGB
            
            if( strlen( $clr ) < 6 ) :
                // Short form
                $str = '#';
                for( $i = 1; $i <= 3; $i++ ) :
                    $str .= $clr[$i].''.$clr[$i];
                endfor;
                $clr = $str;
                
            endif;
            
            list($r, $g, $b) = sscanf($clr, "#%02x%02x%02x");
            $clr = "A=255, R=$r, G=$g, B=$b";
        endif;
        
        return $clr;
    }
    
    
    function exe($case, $str){
        
        switch( $case ) :
            
            case 'config' :
                
                
                /*
                 * Exe Install Limits
                 */
                $install_limit = $this->common_model->get_exe_install($str);
                
                if( $install_limit == "1" ) :
                    
                    /*
                     * Get Configuration's
                     */
                    $bsc_sett = get_basic_setting();
                    $desg_sett = get_design_setting();

                    $config = array(
                        "temple_name"   => $bsc_sett->temple_name,
                        "logo_url"      => BASE_URL . ( !empty( $desg_sett->logo ) ? 'uploads/settings/logo/'. $desg_sett->logo : 'assets/images/logo.png'), /** Important: Image Size Must be smaller **/
                        "theme_color"   => !empty( $desg_sett->login_page_color ) ? $desg_sett->login_page_color : '#f33', //!empty( $desg_sett->archanai_title_color ) ? $this->get_rgb_color( $desg_sett->archanai_title_color ) : '', // "A=255, R=49, G=75, B=79" 

                        "ip_addr"       => REMOTE_ADDR,
                        "enable_exe"    => TO_PRINT ? '1' : '0',
                        "contact_person"=> $bsc_sett->contact_name,
                        "contact_no"    => $bsc_sett->contact_no,
                        "install_limit" => $install_limit,
                    );
                    
                    $alt_server = get_alt_server(false);
                    foreach( $alt_server as $k => $alt ) :
                        $config[$alt['slug']] = $alt['value'];
                    endforeach;
                    
                else :
                    $config = array(
                        "enable_exe"    => '0',
                        "install_limit" => $install_limit,
                    );
                
                endif;
                
                
                echo json_encode($config);
                
            break;    
            
            case 'rm_print':
                /*
                 *  Remove printed files
                 */
                
                $str = urldecode( $str );
                $url = FCPATH . '/tmp/print/';  
                $e = explode("`", $str);
                foreach( $e as $k => $file_name ) :
                    if( file_exists( $url . $file_name ) ) :
                            unlink( $url . $file_name );
                    endif;
                endforeach;
            break;
        
            
            case 'print_flag' :
                /*
                 * Set Printer Status
                 */
                
                $found = FALSE;
                $path = TMP_PRINT_DIR . 'flag.txt';
                //$_SESSION[$e[0] . '_flag'] = $e[1] . '`' . $e[2];

                preg_match("/^(.*?)__(.*)/i", $str, $mths); // $str = "192.168.1.109|192.189.8.90__1__0__9434_ioere"; 

                $e = explode("%7C", $mths[1]); // ip addresses (|)


                if( !file_exists($path) ) :
                    $str = '';
                    foreach( $e as $k => $ip_addr ) :
                        $str .= $ip_addr ."__". $mths[2] . "\n";
                    endforeach;

                    file_put_contents($path, $str);
                else :
                    $lines = file($path);

                    $content = '';
                    $found_ips = array();
                    $ip_addrs = str_replace("%7C", "|", $mths[1]);
                    foreach( $lines as $k => $line ) :
                        preg_match_all('/^'.$ip_addrs.'(.*?)/' , $line, $mtchs);

                        if( $mtchs[0] ) :
                            $found = TRUE;
                            $found_ips[] = $mtchs[0][0];
                            $line = $mtchs[0][0] . "__" . $mths[2];
                            
                        endif;

                        $content .= trim($line)."\n";
                    endforeach;
                    
                    if( !$found || empty($found_ips[count($e)-1]) ) :
                        $str = '';
                        $e = array_diff($e, $found_ips);
                        foreach( $e as $k => $ip_addr ) :
                            $str .= $ip_addr . "__" . $mths[2] . "\n";
                        endforeach;
                        $content .= $str;
                    endif;

                    file_put_contents($path, $content);
                endif;
                
                
                
            break;    
        
            
            
        endswitch;
        
    }
    
    
    /*function set_print_flag( $str ) {
        $e = explode('_', $str);
        //file_put_contents( TMP_PRINT_DIR . 'f.txt', $str );
        
        if( !empty( $e[0] ) ) :
            $found = FALSE;
            $path = TMP_PRINT_DIR . 'flag.txt';
            //$_SESSION[$e[0] . '_flag'] = $e[1] . '`' . $e[2];
            
            if( !file_exists($path) ) :
                file_put_contents($path, $str);
            else :
                $content = '';
                $lines = file($path);
                foreach( $lines as $k => $line ) :
                    preg_match_all('/^'.$e[0].'(.*?)/' , $line, $mtchs);
                    if( $mtchs[0] ) :
                        $found = TRUE;
                        $line = $str;
                    endif;
                    $content .= trim($line)."\n";
                endforeach;
                
                if( !$found ) :
                    $content .= $str;
                endif;
            
                file_put_contents($path, $content);
            endif;
            
        endif;
        
    }*/
    
    /*function auto_startup() {
        $user_data = get_user_data();
        
        if( $user_data['role'] == 3 ) :
            // Super Admin Only
            
            $os_platform    =   "Unknown OS Platform";
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
            
            $os_array       =   array(
                '/windows nt 10/i'     =>  'Windows 10',
                '/windows nt 6.3/i'     =>  'Windows 8.1',
                '/windows nt 6.2/i'     =>  'Windows 8',
                '/windows nt 6.1/i'     =>  'Windows 7',
                '/windows nt 6.0/i'     =>  'Windows Vista',
                '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
                '/windows nt 5.1/i'     =>  'Windows XP',
                '/windows xp/i'         =>  'Windows XP',
                '/windows nt 5.0/i'     =>  'Windows 2000',
                '/windows me/i'         =>  'Windows ME',
                '/win98/i'              =>  'Windows 98',
                '/win95/i'              =>  'Windows 95',
                '/win16/i'              =>  'Windows 3.11',
                '/macintosh|mac os x/i' =>  'Mac OS X',
                '/mac_powerpc/i'        =>  'Mac OS 9',
                '/linux/i'              =>  'Linux',
                '/ubuntu/i'             =>  'Ubuntu',
                '/iphone/i'             =>  'iPhone',
                '/ipod/i'               =>  'iPod',
                '/ipad/i'               =>  'iPad',
                '/android/i'            =>  'Android',
                '/blackberry/i'         =>  'BlackBerry',
                '/webos/i'              =>  'Mobile'
            );

            foreach ($os_array as $regex => $value) { 

                if (preg_match($regex, $user_agent)) {
                    $os_platform    =   $value;
                    break;
                }

            }   
            
            $err = '';
            if( strpos( 'Windows', $os_platform ) == -1 ) :
                $err = 'It seems to be the system doesn\'t have Windows OS!';
            elseif( strpos( $os_platform, '10' ) > 0 || strpos( $os_platform, '8' ) > 0 || strpos( $os_platform, '7' ) > 0 ) :
                $startup_path = 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\\';
            else :
                $startup_path = 'C:\Documents and Settings\All Users\Start Menu\Programs\Startup\\';
            endif;
            
            copy( FCPATH . '\auto-startup.msi', $startup_path.'auto-startup.msi' );
            if( !file_exists( $startup_path . 'auto-startup.msi' ) ) :
                $err = '<li>Can not copy to startup folder! ("<span style="font-size: 14px;">'. $startup_path .'</span>")</li><li>May be the folder permission problem.</li>';
            endif;
            
            if( $err != '' ) :
                $this->session->set_flashdata('error', '<div><ol>'.$err.'<li>Please do it by manually <a href="'. base_url() .'/auto-startup.msi" target="_blank">( Download file )</a> or refer to <a target="_blank" href="'. base_url() .'README (kiosk).txt">this file.</a></li></ol></div>');
            else :
                
                $this->session->set_flashdata('success', 'Setup file is created. "'. $startup_path.'auto-startup.msi"');
            endif;
            
            redirect( 'basic_settings' );
        else :
            die('Sorry, You don\'t have enough privilege!');
        endif;
    }*/
    
    function ajax() {
        
        $post = $this->input->post();
        switch( $post['act'] ) :
            
            case 'booked':
                // Get all Booked
                $return  = $this->common_model->get_booked();
                
            break;    
            
            case 'rec-sett' :
                // Short Rec. Settings
                
                if( $post['submit'] ) :
                    // update
                    $return  = $this->common_model->update();
                    
                elseif( !empty( $post['catID'] ) ) :
                    // Get Items
                    $return = $this->common_model->get(TBL_ITEM, array('order_by' => 'order_sequence', 'where' => array('category_id' => $post['catID'])));
                
                else :
                    // Get Categories
                    if($post['is_category'] == 0) : // is Category
                        $return = $this->common_model->get(TBL_CATEGORY, array('order_by' => 'category_order'));
                    else:
                        $return = $this->common_model->get(TBL_ITEM, array('order_by' => 'order_sequence'));
                    endif;
                endif;
                
            break;
        
            case 'stars' :
               $return = array(
                   'stars' => $this->common_model->get(TBL_STAR, array('order_by' => 'name')),
                   'sms_types' => $this->common_model->get(TBL_SMS_TYPES),
               );    
                
            break;
        
            case 'search-dev':
                
               $return = $this->common_model->search_dev(); 
            break;   
        
            case 'update' :
                $last_id = $this->common_model->update();
                $return = $this->common_model->get_ref_no($last_id);
                
            break;
        
            case 'pass-code' :
                
                $return = $this->common_model->pass_code(); 
                
                //echo "<pre>Data: "; print_r( $return ); die;
                
                if( $post['type'] == 'login' && !empty( $return ) ) :
                    // KIOSK Login Success
                    //$permissions = unserialize_str($return['permissions']);
                    
                    $bill_status =  empty( unserialize_str($return['billing_permissions']) ) ? '21' : 1;
                    $ad_status  = empty( unserialize_str($return['master_permissions']) ) && empty( unserialize_str($return['inventory_permissions']) ) && empty( unserialize_str($return['report_permissions']) ) ? '22' : 1;
                    
                    $status = $bill_status != '1' && $ad_status != '1' ? '2' : ( $bill_status != '1' ? '21' : $ad_status );
                    
                    if( $status != 2 ) {
                        set_user_data((Object)$return); 
                        
                        if( $return['role'] == '1' ) :
                            // Normal User
                            //redirect('kiosk', 'refresh');
                            $return['redirect'] = base_url('kiosk');
                        endif;
                    }
                    
                    $return['status']  = $status;
                 
                endif;
                
            break;  
            
            case 'print' :
                
                // unlink
                $this->session->unset_userdata('print_path');
                $files = $post['files'];
                if( !empty( $files ) ) :
                    
                    $e  = explode(',', $files);
                    foreach($e as $k => $file_name ) :
                        $path = $post['dir'] . $file_name;
                        if( file_exists( $path ) ) :
                            unlink($path);
                        endif;
                        
                    endforeach;
                
                endif;
                
                
            break;    
                
            default :
                
            
            break;
        endswitch;
        
        
        echo json_encode( $return );
        
    }
    public function open_balance_exists() {
        $data = $this->common_model->open_balance_exists();
        echo json_encode($data);
        exit(0);
    }
    
    public function add_open_balance() {
        $user_id = $_POST['user_id'];
        $amount = $_POST['amount'];
        $user_role_id = $_POST['user_role_id'];
        $insert = array(
            'user_id' => $user_id,
            'role' => $user_role_id,
            'date' => date('Y-m-d'),
            'amount' => $amount,
            'machine_name' => gethostbyaddr($_SERVER['REMOTE_ADDR']),
            'ip_address' => $_SERVER['REMOTE_ADDR'],
            'created_by' => $this->user_data['user_id'],
            'created_on' => date('Y-m-d H:i:s')
        );
        $data = $this->common_model->add_open_balance($insert);
        echo json_encode($data);
        exit(0);
    }
    
    public function check_unique_details() {
        $data = $this->common_model->check_unique_details($_POST['val'],$_POST['field_name']);
        echo json_encode($data);
    }
    
}

