<?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/';  

                //$url2 = FCPATH . '/cpy/print/';

                $e = explode("`", $str);

                foreach( $e as $k => $file_name ) :

                    if( file_exists( $url . $file_name ) ) :

                        /*

						if (!file_exists($url2)) :

                            mkdir($url2, 0777, true);

                        endif;

                        

                        copy($url . $file_name, $url2 . $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();
		
		//print_r($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

                    $return = $this->common_model->get(TBL_CATEGORY, array('order_by' => 'category_order'));

                    

                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); 

						$ip_user_data 		= get_session_ipdata();				

						update_login_status("login", $ip_user_data['ls_id'],  $ip_user_data['ip_address']);

                        

                        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);

    }
	
	public function check_festival_date() {
		$fun_date 	= date("Y-m-d", strtotime($_POST['fn_date'])); 
       
	    $data 		= $this->common_model->check_festival_date($fun_date);
        echo json_encode($data);
    }
	
	public function updatedevotee() {
		//echo "yes";
        $data = $this->input->post();
        // print_r($this->input->post());
        $cur_url = $data['cur_url'];
        $url = $_SERVER['HTTP_REFERER'];
        // print_r($cur_url);
        // die;
       // print_r($data);
       // die;
        $tname 	= htmlspecialchars($data['tamil_name']);
        $tn1 	= str_replace("'", "&#39;", $tname);
        $tn2 	= str_replace('&quot;', '"', $tn1);
        $db_id 	= $data['db_id'];
        $session_data = $this->session->userdata(TBL_PREFIX . 'user_logged_in');
        $args = array(
            'bd_star_id' => $data['star'],
            'bd_nric_no' => $data['nric_no'],
            'bd_name' => $data['name'],
            'bd_tamil_name' => $tn2, // htmlspecialchars( $data['tamil_name'] ),
            'bd_contact_no' => $data['contact_no'],
            'bd_mobile_no' => $data['mobile_no'],
            'bd_email' => $data['email'],
            'bd_address' => $data['address'],
            'bd_sms_types' => $data['sms_types'],
            'lang_switch' => $data['langval'],
        );
        $date_now = date("Y-m-d H:i:s");
        if (empty($db_id)) :

            // Insert

            /*
             * Get last Ref. ID
             */

            $this->db->select('MAX(bd_ref_no) AS last_count');
            $q = $this->db->get_where(TBL_BD, array());
            $ref_id = $q->row_array()['last_count'];

            $args['bd_ref_no'] = fill_digits( ++$ref_id, 5);
            $args['created_on'] = $date_now;
            $args['created_by'] = $session_data['user_id'];

            $this->db->insert(TBL_BD, $args);
            $db_id = $this->db->insert_id();

        else :
            // Update
            $args['updated_on'] = $date_now;
            $args['updated_by'] = $session_data['user_id'];

            $this->db->update(TBL_BD, $args, array('id' => $db_id));
            $db_id = $db_id;
        endif;

        if (!empty($data['removed-childs'])) :
            $ee = explode(',', trim($data['removed-childs'], ','));
            foreach ($ee as $ek => $e) :
                $args = array(
                    'status' => 2,
                );
                $this->db->update(TBL_BDI, $args, array('id' => $e));
            endforeach;
        endif;

        if (!empty($data['mem_name'][0])) :

            // Members

            foreach ($data['mem_name'] as $k => $mem) :

                $tname = htmlspecialchars($data['mem_tamil_name'][$k]);
                $tn1 = str_replace("'", "&#39;", $tname);
                $tn2 = str_replace('&quot;', '"', $tn1);

                $args = array(
                    'bd_id' => $db_id,
                    'bdi_star_id' => $data['mem_star'][$k],
                    'bdi_name' => $data['mem_name'][$k],
                    'bdi_tamil_name' => $tn2, // htmlspecialchars( $data['mem_tamil_name'][$k] ),
                    'created_on' => $date_now,
                    'created_by' => $session_data['user_id']
                );

                if (empty($data['mem_id'][$k])) :
                    // Insert
                    $args['created_on'] = $date_now;
                    $args['created_by'] = $session_data['user_id'];

                    $this->db->insert(TBL_BDI, $args);
                else :
                    // Update
                    $args['updated_on'] = $date_now;
                    $args['updated_by'] = $session_data['user_id'];

                    $this->db->update(TBL_BDI, $args, array('id' => $data['mem_id'][$k]));
                endif;
            endforeach;
        endif;
        $return = $this->common_model->get_ref_no($db_id);
        //echo $return ;

        $_SESSION['dev_id'] = "dev" . $return;
        //echo  $_SESSION['dev_id'];
        //die;
        //$cururl= current_url();
        redirect($url, "location");
    }

}
?>