<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_details_model extends CI_Model {
    public function __construct() {
        parent::__construct();
        
        $this->login = TBL_LOGIN;
        $this->master = TBL_SETTINGS_MASTER;
        $this->inventory = TBL_SETTINGS_INVENTORY;
        $this->service_menu = TBL_SERVICE_MENU;
        $this->user = TBL_USERS;
        $this->service = TBL_SERVICE;
        $this->refund = TBL_REFUND;
        $this->general_setting = TBL_SETTINGS_GENERAL;
        $this->statue = TBL_SETTINGS_STATUE;
    }
    
    public function get_log_otp_details($data,$auto_id,$user_id,$url,$page_type_id) {
        $this->db->where('user_id',$user_id);
        $this->db->where('service_menu_id',$data['service_menu_id']);
        $this->db->where('menu_type',$data['menu_type']);
        $this->db->where('page_type_id',$page_type_id);
        $this->db->where('auto_id',$auto_id);
        $this->db->where('otp_status = 1');
        //$this->db->where('otp_expire_date_time >=',date('Y-m-d H:i:s'));
        $exists_data = $this->db->get($this->login);
        
        if($exists_data->num_rows > 0) {
            $row = $exists_data->row();
            if($row->otp_expire_date_time >= date('Y-m-d H:i:s')) {
                $return['msg'] = 'SMS has been sent...Please enter OTP';
                $return['status'] = 2;
            } else {
                $this->db->where('id',$row->id);
                $this->db->update($this->login,array('otp_status' => 3));
                $otp = $this->generate_otp();
                
                //User Details
                $userDetails = $this->user_details_by_id($user_id);
                $user_contact_no = $userDetails->contact_no;
                $user_name = $userDetails->name;
                
                // Get Contact NOT
                $contact_no = get_general_setting()->otp_contact_no;
                
                //Get Controller Name
                $controller_name = $this->get_controller_name($data['service_menu_id'],$data['menu_type'])->service_name;
              
                if(!empty($contact_no)) {
                    $sms = $this->send_sms($contact_no,$otp,$user_name,$user_contact_no,$page_type_id,$controller_name);
                    if($sms == 1) {
                        $this->insert($data,$auto_id,$user_id,$url,$otp,$page_type_id);
                        $return['msg'] = 'SMS has been sent successfully!';
                        $return['status'] = 1;
                    } else {
                        $return['msg'] = 'SMS has not been sent for some number!';
                        $return['status'] = 0;
                    }
                } else {
                    $return['msg'] = 'None of the contact no is given to sent!';
                    $return['status'] = 0;
                }
            }
        } else {
            $otp = $this->generate_otp();
            
            //User Details
            $userDetails = $this->user_details_by_id($user_id);
            $user_contact_no = $userDetails->contact_no;
            $user_name = $userDetails->name;
            
            // Get Contact NOT
            $contact_no = get_general_setting()->otp_contact_no;
                
            //Get Controller Name
            $controller_name = $this->get_controller_name($data['service_menu_id'],$data['menu_type'])->service_name;
            
            if(!empty($contact_no)) {
                $sms = $this->send_sms($contact_no,$otp,$user_name,$user_contact_no,$page_type_id,$controller_name);
                if($sms == 1) {
                    $this->insert($data,$auto_id,$user_id,$url,$otp,$page_type_id);
                    $return['msg'] = 'SMS has been sent successfully!';
                    $return['status'] = 1;
                }else {
                    $return['msg'] = 'SMS has not been sent for some number!';
                    $return['status'] = 0;
                }
            } else {
                $return['msg'] = 'None of the contact no is given to sent!';
                $return['status'] = 0;
            }
        }
        
        return $return;
    }
    
    public function insert_log_details_by_id($data,$auto_id,$user_id,$url,$page_type_id) {
        $this->db->where('user_id',$user_id);
        $this->db->where('service_menu_id',$data['service_menu_id']);
        $this->db->where('menu_type',$data['menu_type']);
        $this->db->where('page_type_id',$page_type_id);
        $this->db->where('auto_id',$auto_id);
        //$this->db->where('otp_expire_date_time >=',date('Y-m-d H:i:s'));
        $exists_data = $this->db->get($this->login);
         
        #if($exists_data->num_rows == 0) {
            $args = array(
                'ip_address' => $_SERVER['REMOTE_ADDR'],
                'user_id' => $user_id,
                'service_menu_id' => $data['service_menu_id'],
                'menu_type' => $data['menu_type'],
                'page_type_id' => $page_type_id,
                'auto_id' => $auto_id,
                'desc' => (($page_type_id == 2) ? 'Edit Operation' : 'Delete Opertaion'),
                'log_date_time' => date('Y-m-d H:i:s'),
                'otp_status' => 2,
                'url' => $url
            );
            $this->db->insert($this->login,$args);
            $insert_id = $this->db->insert_id();
        #}
    }
    
    public function insert($data,$auto_id,$user_id,$url,$otp,$page_type_id) {
        $args = array(
            'ip_address' => $_SERVER['REMOTE_ADDR'],
            'user_id' => $user_id,
            'service_menu_id' => $data['service_menu_id'],
            'menu_type' => $data['menu_type'],
            'page_type_id' => $page_type_id,
            'auto_id' => $auto_id,
            'desc' => (($page_type_id == 2) ? 'Edit Operation' : 'Delete Opertaion'),
            'log_date_time' => date('Y-m-d H:i:s'),
            'otp' => $otp,
            'otp_status' => 1,
            'url' => $url,
            'otp_expire_date_time' => date('Y-m-d H:i:s',strtotime(OTP_EXPIRE_TIME))
        );
        $this->db->insert($this->login,$args);
        $insert_id = $this->db->insert_id();
    }
    
    public function check_otp_correct($user_id,$otp_value) {
        $this->db->where('user_id',$user_id);
        $this->db->where('otp',$otp_value);
        $this->db->where('otp_status',1);
        $getData = $this->db->get($this->login);
        return $getData;
    }
    
    public function update_otp_status($id) {
        $this->db->where('id',$id);
        $this->db->update($this->login,array('otp_status' => 2));
        return $this->db->affected_rows();
    }
    
     public function used_otp_rows($user_id,$otp_value) {
        $this->db->where('user_id',$user_id);
        $this->db->where('otp',$otp_value);
        $this->db->where('otp_status !=',1);
        $getData = $this->db->get($this->login);
        return $getData;
    }
    
    public function get_master_controller_id($controller) {
        $this->db->where('controller_name',$controller);
        $this->db->where('status',1);
        return $this->db->get($this->master)->row()->id;
    }
    
    public function get_inventory_controller_id($controller){
        $this->db->where('controller_name',$controller);
        $this->db->where('status',1);
        return $this->db->get($this->inventory)->row()->id;
    }
    
    public function get_statue_controller_id($controller){
        $this->db->where('controller_name',$controller);
        $this->db->where('status',1);
        return $this->db->get($this->statue)->row()->id;
    }
    
    public function get_billing_controller($controller){
        $this->db->where('controller_name',$controller);
        $this->db->where('status',1);
        return $this->db->get($this->service_menu)->row();
    }
    
    public function get_controller_name($service_menu_id,$menu_type) { error_log($service_menu_id . $menu_type);
        if($menu_type == 1) {
            $service_name = 'master_name as service_name';
        } elseif($menu_type == 3) {
            $service_name = 'inventory_name as service_name';
        } elseif($menu_type == 4) {
            $service_name = 'service_name as service_name';
        } elseif($menu_type == 5) {
            $service_name = 'menu_name as service_name';
        }
        $this->db->select('id,controller_name,' . $service_name ,FALSE);
        $this->db->where('id',$service_menu_id);
        $this->db->where('status',1);
        if($menu_type == 1)
            $getData = $this->db->get($this->master);
        
        /* elseif($data['menu_type'] == 2) 
            $getData = $this->db->get($this->master); */
            
        elseif($menu_type == 3)
            $getData = $this->db->get($this->inventory);
            
        elseif($menu_type == 4)
            $getData = $this->db->get($this->service_menu);
            
        elseif($menu_type == 5)
            $getData = $this->db->get($this->statue);
        
        return $getData->row();
    }
    
    public function generate_otp() {
		/*$chars = "0123456789";
		$password = substr(str_shuffle($chars), 0, MAX_OTP_LIMIT);
		return $password; */
        
        $otp_digit_limit = MAX_OTP_LIMIT;
        $min_limit = MAX_OTP_LIMIT - 1;
        
        $getData = $this->db->get($this->login)->num_rows();
        if($getData > 0) {
            $query = $this->db->query('SELECT FLOOR( RAND() *(POW(10,' . $otp_digit_limit . ')-(POW(10,' . $min_limit . ')-1)) )+POW(10,' . $min_limit . ') AS rand FROM `thiru_log_details` WHERE "rand" NOT IN (SELECT `otp` FROM `thiru_log_details` WHERE `otp` IS NOT NULL AND `otp_status` != 2 AND `otp_status` != 3) LIMIT 1');
            $row = $query->row()->rand;
        } else {
            /* $query = $this->db->query('SELECT FLOOR( RAND() *(POW(10,' . $otp_digit_limit . ')-(POW(10,' . $min_limit . ')-1)) )+POW(10,' . $min_limit . ') AS rand FROM `thiru_log_details`');
            $row = $query->row()->rand; */
            $chars = "0123456789";
            $row = substr(str_shuffle($chars), 0, MAX_OTP_LIMIT);
        }
        
        return $row;
	}    

    public function send_sms($contact_no,$otp,$user_name,$user_contact_no,$page_type_id,$controller_name) {
        $return = array();
        $status = 1;
        $message = '';
        $e = explode(',', $contact_no);
        
        $i = 0;
        $nos = array();
        foreach( $e as $k => $no) :
            $nos[$i] .= MOB_PREFIX . trim($no).',';  
            if( $k == 40 ) :
                ++$i;
            endif;
        endforeach;
        
        if($page_type_id == 2) :
            $page = 'Edit';
        else :
            $page = 'Delete';
        endif;
        
        $module = (strlen($controller_name) > 30) ? substr($controller_name,0,30).'...' : $controller_name;
        $userName = (strlen($user_name) > 20) ? substr($user_name,0,20).'...' : $user_name;
        
        foreach($nos as $k => $no) :
        
        
            // Send SMS
            $sms_to  = substr($no, 0, -1);

            #$sms_msg = "OTP: " . $otp . ' ' . $userName . "(" . $user_contact_no .") is requested to " . $page . " on " . $module;
              
            $sms_msg = "OTP: " . $otp . ' ' . $userName . " is requested to " . $page . " on " . $module;
            
            $query_string = "api.aspx?apiusername=".SMS_USER."&apipassword=".SMS_PWD;
            $query_string .= "&senderid=".rawurlencode(SMS_FROM)."&mobileno=".rawurlencode($sms_to);
            $query_string .= "&message=".rawurlencode(stripslashes($sms_msg)) . "&languagetype=1";       

            // $url = "http://gateway.onewaysms.com.au:10001/".$query_string; 
            $url = "http://gateway.onewaysms.sg:10002/".$query_string; 

            if( TO_SEND ) :

                $fd = @implode ('', file ($url));
                if( !$fd ) :
                    ++$status;
                endif;
            else :
                $fd = 1;
            endif; // to send
        endforeach;    
        
        return $status;
    }
    
    public function user_details_by_id($user_id){
        $this->db->where('id',$user_id);
        $this->db->where('status','1');
        return $this->db->get($this->user)->row();
    }
    
    public function get_amount_by_service_id($id) {
        $this->db->where('id',$id);
        return $this->db->get($this->service)->row();
    }
    
    public function get_service_menu_by_id($id) {
        $this->db->where('id',$id);
        return $this->db->get($this->service_menu)->row();
    }
   
    public function insert_refund_amount($data){
        $this->db->insert($this->refund,$data);
        return $this->db->insert_id();
    }
    
    public function get_refund_amount($date) {
        $this->db->select('CASE WHEN amount IS NULL THEN "0.00" ELSE SUM(amount) END as refund_amount',FALSE);
        if(!empty($date)) {
            $this->db->where('created_on >=',date('Y-m-d 00:00:00',strtotime($date)));
            $this->db->where('created_on <=',date('Y-m-d 23:00:00',strtotime($date)));
        } else {
            $this->db->where('created_on >=',date('Y-m-d 00:00:00'));
            $this->db->where('created_on <=',date('Y-m-d 23:00:00'));
        }
        $this->db->where('status',1);
        return $this->db->get($this->refund)->row()->refund_amount;
    }
    
    public function get_refund_details_by_ids($menu_id,$service_id,$auto_id) {
        $this->db->select('SUM(amount) as refund_amount');
        $this->db->where('menu_id',$menu_id);
        $this->db->where('service_id',$service_id);
        $this->db->where('auto_id',$auto_id);
        $this->db->where('status !=',2);
        return $this->db->get($this->refund)->row();
    }
}
?>