<?php

class Sms_model extends CI_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
         
    }

    
    function get_sms_cred($business_id=1){
        
        $this->db->select('*');
        $this->db->where('status','valid');
        $this->db->where('business_id', $business_id);
        $this->db->not_like('channel', 'OTP');
        $this->db->not_like('channel', 'Receipt');
        $query = $this->db->get('sms_cred');               
        
        return $query->result_array();
    }

    function get_otp_cred($business_id=1){
        
        $this->db->select('*');
        $this->db->where('status','valid');
        $this->db->where('business_id', $business_id);
        $this->db->like('channel', 'OTP');
        $query = $this->db->get('sms_cred');               
        
        return $query->result_array();
    }

    function get_receipts_cred($business_id=1){
        $this->db->select('*');
        $this->db->where('status','valid');
        $this->db->where('business_id', $business_id);
        $this->db->like('channel', 'Receipt');
        $query = $this->db->get('sms_cred');               
        
        return $query->result_array();
    }
    
    function get_countofcustomers(){
        
        
        $result=0;
        
        $this->db->select('count(*) as count');
        ///Where
        $this->db->where('customers.business_id', $this->session->userdata('businessid'));
        //$this->db->where('length(customers.customer_cell) =', 11);
       ///Where
        if(null !== $this->input->post('customer_name') && $this->input->post('customer_name')!==''){
            $this->db->like('customers.customer_name', $this->input->post('customer_name'));
        }
        if(null !== $this->input->post('customer_cell') && $this->input->post('customer_cell')!==''){
            $this->db->like('customers.customer_cell', $this->input->post('customer_cell'));
        }
        if(null !== $this->input->post('customer_gender') && $this->input->post('customer_gender')!==''){
            $this->db->like('customers.customer_gender', $this->input->post('customer_gender'));
        }
        if(null !== $this->input->post('customer_careof') && $this->input->post('customer_careof')!==''){
            $this->db->like('customers.customer_careof', $this->input->post('customer_careof'));
        }
        if(null !== $this->input->post('customer_email') && $this->input->post('customer_email')!==''){
            $this->db->like('customers.customer_email', $this->input->post('customer_email'));
        }
        if(null !== $this->input->post('profession') && $this->input->post('profession')!==''){
            $this->db->like('customers.profession', $this->input->post('profession'));
        }
        $query = $this->db->get('customers');
       
        foreach ($query->result() as $row){
            $result=$row->count;
        }
        return $result;
        
    }
    
    function get_customersbysearch() {

        $today = date('Y-m-d');
        $tomorrow= date('Y-m-d H:i:s', strtotime('tomorrow'));
        
        
        //** get all table definitions **//
        $draw = $this->input->post('draw');
        $start = $this->input->post('start');
        $length = $this->input->post('length');
        
        if (Null!==$this->input->post('order')) {
            $order = $this->input->post('order');
            $columns = $this->input->post('columns');
            $orderby = $columns[$order[0]['column']]['data'];
            $orderdir = $order[0]['dir'];
        } else {
            $orderby = 'id_customers';
            $orderdir = 'asc';
        }
        //openupdate        
        $this->db->select('concat("<a href=\'#\' onclick=\'previousdirect(", id_customers,");\'>",id_customers,"</a>") as id_customers, customer_name customer_name, concat("<span style=\'cursor:pointer;\' class=\'text-primary\' onclick=\"addtophone(\'", customers.customer_cell ,"\',\'", customers.customer_name,"\');\">",customers.customer_name,"</span>") name, customers.customer_careof, customer_gender, staff_fullname, '
                . 'concat("<span style=\'cursor:pointer;\' class=\'text-primary\' onclick=\"addtophone(\'", customers.customer_cell ,"\',\'", customers.customer_name,"\');\">",customers.customer_cell,"</span>") customer_cell, customer_email, customer_address, profession, concat("<span style=\'cursor:pointer;\' class=\'text-primary\' onclick=\"openupdate(\'", customers.id_customers ,"\');\">","<button class=\'btn btn-sm btn-primary\'>edit</button>","</span>") type', False);

        $this->db->select('concat("<span style=\'cursor:pointer;\' class=\'text-primary\' onclick=\"previousdirect(\'", customers.id_customers ,"\');\">","<button class=\'btn btn-sm btn-warning\'>Account</button>","</span>") account');        
        $this->db->join('staff','id_staff=referencing_staff','left');           
        $this->db->where('customers.business_id', $this->session->userdata('businessid'));
        //$this->db->where('length(customers.customer_cell) =', 11);
        
        ///Where
        if(null !== $this->input->post('customer_name') && $this->input->post('customer_name')!==''){
            $this->db->like('customers.customer_name', $this->input->post('customer_name'));
        }
        if(null !== $this->input->post('customer_cell') && $this->input->post('customer_cell')!==''){
            $this->db->like('customers.customer_cell', $this->input->post('customer_cell'));
        }
        if(null !== $this->input->post('customer_gender') && $this->input->post('customer_gender')!==''){
            $this->db->like('customers.customer_gender', $this->input->post('customer_gender'));
        }
        if(null !== $this->input->post('customer_careof') && $this->input->post('customer_careof')!==''){
            $this->db->like('customers.customer_careof', $this->input->post('customer_careof'));
        }
        if(null !== $this->input->post('customer_email') && $this->input->post('customer_email')!==''){
            $this->db->like('customers.customer_email', $this->input->post('customer_email'));
        }
        if(null !== $this->input->post('profession') && $this->input->post('profession')!==''){
            $this->db->like('customers.profession', $this->input->post('profession'));
        }
        if(null !== $this->input->post('referencing_staff') && $this->input->post('referencing_staff')!==''){
            $this->db->like('staff.staff_fullname', $this->input->post('referencing_staff'));
        }
        
        
        if(Null!==$this->input->post('order')){
            $this->db->order_by($orderby, $orderdir);
        }
        
        if($length>-1){
           $this->db->limit($length);
        }
        if($start>0){
            $this->db->offset($start);
        }
        
        $query = $this->db->get('customers');
        
        return $query->result_array();
    }

    
    function httpRequest($url)
    {
       
        $args;
        $pattern = "/http...([0-9a-zA-Z-.]*).([0-9]*).(.*)/";
        preg_match($pattern,$url,$args);
        $in = "";
        $fp = fsockopen("$args[1]", $args[2], $errno, $errstr, 30);
        if (!$fp)
        {
           return("$errstr ($errno)");
        }
        else
        {
            $out = "GET /$args[3] HTTP/1.1\r\n";
            $out .= "Host: $args[1]:$args[2]\r\n";
            $out .= "User-agent: PHP Web SMS client\r\n";
            $out .= "Accept: */*\r\n";
            $out .= "Connection: Close\r\n\r\n";

            fwrite($fp, $out);
            while (!feof($fp))
            {
               $in.=fgets($fp, 128);
            }
        }
        fclose($fp);
        return($in);
    } 
    
    function send_sms($msg, $phone, $debug=true, $using="SMSReminder", $echo=true , $business_id=1, $invoice_id=1)
    {
        
        
//        print_r(str_replace('%5Cn','+%0A+',urlencode($msg)));
//        exit();
        if ($msg == '' || $phone == '' || strlen($phone)!==11){

            echo('Invalid phone or message!');

        } else {
        
            $username='';
            $password='';   
            $smsurl='';

            if($using =='LoyaltyOTP'){
                $sms_cred = $this->sms_model->get_otp_cred($business_id);
            }elseif($using == 'ReceiptsSMS'){
                $sms_cred = $this->sms_model->get_receipts_cred($business_id);
            }elseif($using == 'ReceiptsSMSretail'){
                $sms_cred = $this->sms_model->get_receipts_cred($business_id);
            }else{
                $sms_cred = $this->sms_model->get_sms_cred($business_id);
            }
            //print_r($sms_cred); exit();
            
            if($using == "ReceiptsSMS"){                    
                $data = $this->receiptsjson_service($invoice_id, $sms_cred, $msg, $business_id);

                $urltouse = $sms_cred[0]['domain']."insert-receipt";
                $authorization = "Authorization: Bearer ".$sms_cred[0]['password'];

                $curl = curl_init();

                curl_setopt_array($curl, array(
                    CURLOPT_URL => $urltouse,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS =>$data,
                    CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/json',
                        'secret-key: '.$sms_cred[0]['password']
                        )
                    )
                    // CURLOPT_HTTPHEADER => array(
                    //     'Content-Type: application/json',
                    //     'Authorization: '.$authorization
                    //     ),
                    // )
                    
                );

               
                // Execute and get the response
                $response = curl_exec($curl);
                // Check for cURL errors
                if (curl_errno($curl)) {
                    echo 'Error: ' . curl_error($curl);
                } else {
                 //   echo $response;
                }
                // Close cURL session
                curl_close($curl);
                if($debug)
                {
                    echo "Request: <br>$urltouse<br><br>";
                    print_r($response);
                }
                //Update Invoice with code                
                $a = $this->updateslipcode($invoice_id, $response);
                return $a;            
            } elseif($using == "ReceiptsSMSretail"){
               
                $data = $this->receiptsjson_sale($invoice_id, $sms_cred, $msg, $business_id);

                $urltouse = $sms_cred[0]['domain']."insert-receipt";
                $authorization = "Authorization: Bearer ".$sms_cred[0]['password'];

                $curl = curl_init();

                curl_setopt_array($curl, array(
                    CURLOPT_URL => $urltouse,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS =>$data,
                    CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/json',
                        'secret-key: '.$sms_cred[0]['password']
                        )
                    )
                    // CURLOPT_HTTPHEADER => array(
                    //     'Content-Type: application/json',
                    //     'Authorization: '.$authorization
                    //     ),
                    // )
                    
                );

               
                // Execute and get the response
                $response = curl_exec($curl);
                // Check for cURL errors
                if (curl_errno($curl)) {
                    echo 'Error: ' . curl_error($curl);
                } else {
                 //   echo $response;
                }
                // Close cURL session
                curl_close($curl);
                if($debug)
                {
                    echo "Request: <br>$urltouse<br><br>";
                    print_r($response);
                }
                //Update Invoice with code                
                $a = $this->updateslipcode($invoice_id, $response);
                return $a;
                
            } elseif ($sms_cred) {
                if($sms_cred[0]['domain'] == 'https://secure.h3techs.com/sms/api/send'){

                    $smsurl = 'https://secure.h3techs.com/sms/api/send';                    
                    $email   = $sms_cred[0]['username']; 
                    $key   = $sms_cred[0]['password'];
                    $mask = $sms_cred[0]['mask'];
                    $to = urlencode($phone);
                    $channel = $sms_cred[0]['channel'];                    
                    // Preparing Data to POST Request / DO NOT TOUCH BELOW
                    $mask = urlencode($mask);
                    $message =  str_replace('%5Cn','%0A',urlencode($msg));

                    $data = "email=".$email."&key=".$key."&mask=".$mask."&to=".$to."&message=".$message;
                     if($debug)
                     {
                        print_r("Request: <br>$data<br><br>");
                     }

                    // Sending the POST Request with cURL to Branded SMS Pakistan Server
                    $ch = curl_init('https://secure.h3techs.com/sms/api/send');
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $result = curl_exec($ch); // Result from Branded SMS Pakistan including Return ID
                    curl_close($ch);

                    if ($debug)
                    {
                        print_r($result);
                       // print_r($urltouse);

                    }
                    //Update sms_log Table
                    $updated = $this->update_smslog_simple($result, $phone, $using, $msg, $echo, $business_id);


                }elseif($sms_cred[0]['domain'] == 'https://www.tilismtechservices.com/messaging/'){
                    $username   = $sms_cred[0]['username']; 
                    $password   = $sms_cred[0]['password'];
                    $mask = $sms_cred[0]['mask'];
                    $channel = $sms_cred[0]['channel'];
                    
                    $smsurl = 'https://www.tilismtechservices.com/messaging/url/msgurl.aspx?';
                    
                    
                    $url = 'username='.urlencode($username);
                    $url  .= '&password='.urlencode($password);
                    $url  .= '&mask='.urlencode($mask);
                    $url .= '&mobileno='.urlencode($phone);
                    $url  .= '&msgid=123';
                     $url .= '&message='.str_replace('%5Cn','%0A',urlencode($msg));
                    $url .= '&channel='.urlencode($channel);
                    
                    $urltouse =  $smsurl.$url;
                    if($debug)
                    {
                        echo "Request: <br>$urltouse<br><br>";
                    }
                   // echo $urltouse; 
                    //exit();
                    $response = file_get_contents($urltouse); 
                    
                    if ($debug)
                    {
                        print_r($response);
                        print_r($urltouse);

                    }
                    //Update sms_log Table
                    $updated = $this->update_smslog_simple($response, $phone, $using, $msg, $echo, $business_id);
                
                
                    
                }elseif($sms_cred[0]['domain'] == 'https://bsms.ufone.com/bsms_v8_api/sendapi-0.3.jsp?id=03348970448'){
                    //$url = "https://bsms.ufone.com/bsms_v8_api/sendapi-0.3.jsp?id=03348970448&message=this+is+a+test&shortcode=Pengs.&lang=English&mobilenum=03332127277&password=Karachi@123";
                    $url="https://sms.skedwise.xyz/sendsms.php?";
                    
                    //$url = "https://bsms.ufone.com/bsms_v8_api/sendapi-0.3.jsp?id=03348970448&";
                    
                     $username   = urlencode($sms_cred[0]['username']);
                     //$message = 'message='.urlencode($msg);
                     $message = 'message='.str_replace('%5Cn','%0A',urlencode($msg));
                     $shortcode = '&shortcode='.urlencode($sms_cred[0]['mask']) ;
                     $lang = '&lang=English';
                     $mobile = '&mobilenum='.$phone ;
                     $password   = '&password='. urlencode($sms_cred[0]['password']);
                     $urltouse = $url.$message.$shortcode.$lang.$mobile.$password;
                    
                     

                     $ch = curl_init();
                     // Set URL and other appropriate options
                     curl_setopt($ch, CURLOPT_URL, $urltouse);
                     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable SSL verification
                     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                     // Execute and get the response
                     $response = curl_exec($ch);
                     // Check for cURL errors
                     if (curl_errno($ch)) {
                         echo 'Error: ' . curl_error($ch);
                     } else {
                         //echo $response;
                     }
                     // Close cURL session
                     curl_close($ch);
                     if($debug)
                     {
                         echo "Request: <br>$urltouse<br><br>";
                         print_r($response);
                     }
                      //Update sms_log Table
                     $updated = $this->update_smslog_simple($response, $phone, $using, $msg, $echo, $business_id);
                 
                 }elseif($sms_cred[0]['domain'] == 'https://bsms.its.com.pk/') {
                    $username   = $sms_cred[0]['username']; 
                    $password   = $sms_cred[0]['password'];
                    $mask = $sms_cred[0]['mask'];
                    $channel = $sms_cred[0]['channel'];
                    
                    
                    $smsurl = "https://bsms.its.com.pk/api.php?key=";
                    
                    $url = urlencode($password);
                    $url  .= '&receiver='.urlencode($phone);
                    $url  .= '&sender='.urlencode($mask);                    
                    $url  .= '&msgdata='.str_replace('%5Cn','%0A',urlencode($msg));
                    $url  .= '&channel='.urlencode($channel);
                    
                    $urltouse =  $smsurl.$url;
//                    echo $urltouse; 
//                    exit();
                    if($debug)
                    {
                        echo "Request: <br>$urltouse<br><br>";
                    }
//                    echo $urltouse; 
//                    exit();
                    $response = file_get_contents($urltouse); 
                    
                    if ($debug)
                    {
                        print_r($response);
//                        echo "Response: <br><pre>".
//                        str_replace(array("<",">"),array("<",">"),$response).
//                        "</pre><br>";
                    }
                    //Update sms_log Table
                    $updated = $this->update_smslog_simple($response, $phone, $using, $msg, $echo, $business_id);
                
                
                }else {
                    echo('SMS Service is not setup!');
                }                
               
            } 
        }
    }
    
    
    function update_smslog_simple($response, $receiver, $using="SMSReminder", $msg="", $echo=false, $businessid=1){
        $this->db->set('errorno', $response);
        $this->db->set('status', $response);
        $this->db->set('msgdata', $msg);
                
                
        $this->db->set('using', $using);
        $this->db->set('business_id', $businessid);
        $today= date('Y-m-d H:m');
        $this->db->set('senton', $today);
        $this->db->set('receiver',$receiver);
        
        if($echo == true){
            echo('Message ready for delivery').'<br/>';
        
            echo('error = '.$response).'<br/>';
            echo($msg).'<br/>';
           
        }
        
        
        $this->db->insert('sms_log');
        return $this->db->insert_id();
        
    }
    
    function update_smslog($response, $using="SMSReminder", $msg="", $echo=true, $businessid=1){
        $pos=528;
        $today= date('Y-m-d H:m');
        //var_dump( $response );
        //$xml= json_decode($response);
        //echo $response;
        
        if($response !== 'SMS Service is not setup!' ){
            
            //$myXMLData= substr($response, $pos);
           
            $xml = simplexml_load_string($response);
            //echo $xml->errorno;
          
            //$xml= json_decode($response);
          
            
            $responseaction = $xml->errorno;
            
           
            
            if(intval($responseaction)==0){
                $this->db->set('errorno', $xml->errorno);
                $this->db->set('status', $xml->status);
                $this->db->set('msgdata', $msg);
                //$this->db->set('receiver', $xml->receivers->reciever);
                  foreach($xml->children() as $child) {
                        foreach($child as $key => $value) {
                           $this->db->set('receiver',$value);

                        }
                    }

                $this->db->set('senton', $today);

                if($echo == true){
                    echo('Message Sent').'<br/>';
                   // echo($xml->response->errorno).'<br/>';
                    echo($xml->status).'<br/>';
                    echo($msg).'<br/>';
                   // echo($xml->receivers->receiver).'<br/>';
                    foreach($xml->children() as $child) {
                        foreach($child as $key => $value) {
                            echo("[".$key ."] ".$value . "<br />");

                        }
                    }
                }

                $this->db->set('using', $using);
                $this->db->set('business_id', $businessid);

                $this->db->insert('sms_log');
                return $this->db->insert_id();
            } else { //Error returned
                
                $this->db->set('errorno', $xml->errorno);
                $this->db->set('status', $xml->description);
                $this->db->set('msgdata', $msg);
                //$this->db->set('receiver', $xml->response->numberlist[0]->number);
                $this->db->set('senton', $today);

                if($echo == true){
                    echo('Error Received').'<br/>';
                    echo($xml->response->errorno).'<br/>';
                    echo($xml->description).'<br/>';
                    //echo( $msg ).'<br/>';
                    //echo($xml->response->numberlist[0]->number).'<br/>';
                }

                $this->db->set('using', $using);
                $this->db->set('business_id', $this->session->userdata('businessid'));

                $this->db->insert('sms_log');
                return $this->db->insert_id();
            }
        } else {
            return 0;
        }
        
        
    } 

    function get_smstext(){
        
        $this->db->select('*');
        $query = $this->db->get('sms_text');
        
        return $query->result_array();
    }
 
    function getsmslog(){
        $today = date('Y-m-d');
        $tomorrow= date('Y-m-d H:i:s', strtotime('tomorrow'));
        
        
        //** get all table definitions **//
        $draw = $this->input->post('draw');
        $start = $this->input->post('start');
        $length = $this->input->post('length');
        
        if (Null!==$this->input->post('order')) {
            $order = $this->input->post('order');
            $columns = $this->input->post('columns');
            $orderby = $columns[$order[0]['column']]['data'];
            $orderdir = $order[0]['dir'];
        } else {
            $orderby = 'id_sms_log';
            $orderdir = 'asc';
        }
        
        $this->db->select("id_sms_log, CASE WHEN msgdata LIKE '%OTP%' then 'hidden' ELSE msgdata END as msgdata, replace(receiver,'92','0') as receiver, senton, using, '' as type", TRUE);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        ///Where
        if(null !== $this->input->post('msgdata') && $this->input->post('msgdata')!==''){
            $this->db->like('msgdata', $this->input->post('msgdata'));
        }
        if(null !== $this->input->post('receiver') && $this->input->post('receiver')!==''){
            $this->db->like('receiver', $this->input->post('receiver'));
        }
        if(null !== $this->input->post('senton') && $this->input->post('senton')!==''){
            $this->db->like('senton', $this->input->post('senton'));
        }
        if(null !== $this->input->post('using') && $this->input->post('using')!==''){
            $this->db->like('using', $this->input->post('using'));
        }
        
        
        if(Null!==$this->input->post('order')){
            $this->db->order_by($orderby, $orderdir);
        }
        
        if($length>-1){
           $this->db->limit($length);
        }
        if($start>0){
            $this->db->offset($start);
        }
        
        
        $query = $this->db->get('sms_log');
        
        
       
        return $query->result_array();
    }
    
    function get_countoflog(){
        $this->db->select('count(*) as count');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        ///Where
        if(null !== $this->input->post('msgdata') && $this->input->post('msgdata')!==''){
            $this->db->like('msgdata', $this->input->post('msgdata'));
        }
        if(null !== $this->input->post('receiver') && $this->input->post('receiver')!==''){
            $this->db->like('receiver', $this->input->post('receiver'));
        }
        if(null !== $this->input->post('senton') && $this->input->post('senton')!==''){
            $this->db->like('senton', $this->input->post('senton'));
        }
        if(null !== $this->input->post('using') && $this->input->post('using')!==''){
            $this->db->like('using', $this->input->post('using'));
        }
        
        
        $query = $this->db->get('sms_log');
       foreach ($query->result() as $row){
            $result=$row->count;
        }
        return $result;
    }

    function  update_status($visit_id){
         $data = array(
            'reminder_sms' => 'Y'
        );
        //print_r($data);exit;
        $this->db->where('id_customer_visits', $visit_id);
        $this->db->update('customer_visits', $data);
        return $this->db->affected_rows();
    }
    
    function insert_smscred(){
        //insert new
            $data=array(
                'username' => $this->input->post('username'),
                'password' => $this->input->post('password'),
                'domain' => $this->input->post('domain'),
                'status' => $this->input->post('status'),
                'business_id' => $this->session->userdata('businessid'),
            );
            
            $this->db->insert('sms_cred', $data);
            return $this->db->insert_id();
    }
    
    function update_smscred($id){
        //insert new
            $data=array(
                'username' => $this->input->post('username'),
                'password' => $this->input->post('password'),
                'domain' => $this->input->post('domain'),
                'status' => $this->input->post('status'),
                'business_id' => $this->session->userdata('businessid'),
            );
            
            $this->db->where('id_sms_cred', $id);
            $this->db->update('sms_cred', $data);
            return $this->db->affected_rows();
    }
    
    
    function get_scheduled_tasks(){
        
        $this->db->select('*');
        $query = $this->db->get('scheduled_tasks');
        return $query->result_array();
        
    }
    
    function update_scheduled_task(){
        
        $data=array(
                
                'task_name' => $this->input->post('task_name', True),
                's_query' => $this->input->post('s_query', True),
                'status' => $this->input->post('status', True),
                'msg' => $this->input->post('msg', True)
                
            );
        $this->db->where('id_scheduled_tasks', $this->input->post('id_scheduled_tasks', True));
        $this->db->update('scheduled_tasks',$data);
        return $this->db->affected_rows();
        
    }

    
    public function receiptsjson_service($invoiceid, $sms_cred, $loyaltypoints, $business_id=1){

        $sql="select tax_mode, CASE WHEN srb_fiscal_service = 'Yes' THEN 'SRB' ELSE 'PRA' END as tax_org from business where id_business = ". $business_id ;
        $query=$this->db->query($sql);
        $tx = $query->row();
        $taxmode =$tx->tax_mode;
        $taxorg =$tx->tax_org;

       // $invoiceid = $this->input->post('invoiceid');

        $this->db->select("invoice.*, invoice_details.*, invoice_staff.staff_id, invoice_staff.staff_name, invoice.payment_mode as mode, business.id_business, business.business_name, business.business_address, SUBSTRING(business_address, position('BR>' IN business_address)+3, length(business_address)) as business_taxcode, business.business_phone1, customers.customer_email, case when instrument_number like 'Online%' then 'Online' ELSE payment_mode END as payment_mode, invoice.discount as invoice_discount, invoice_details.invoice_discount as invoice_discount_item, round(100*taxes/ invoice_details.discounted_price ,2) as beforerate ", false);
        $this->db->join('customers','customers.id_customers=invoice.customer_id');
        $this->db->join('business','invoice.business_id=business.id_business');
        $this->db->join('invoice_details','invoice_details.invoice_id = invoice.id_invoice');
        $this->db->join('invoice_staff','invoice_staff.invoice_detail_id = invoice_details.id_invoice_details');
        $this->db->where('id_invoice', $invoiceid);
        $this->db->group_by('id_invoice_details');
        $query = $this->db->get('invoice');
        
        $invoice_data = $query->result_array();

        


        $businessbranch = explode("|", $sms_cred[0]['mask']);

        $invoice = new stdClass();

        if($query->num_rows() > 0){
           
            
            $invoice->inv_id = $invoice_data[0]["id_invoice"];
            $invoice->invoice_number = $invoice_data[0]['invoice_number'];
            $invoice->date = $invoice_data[0]['invoice_date'];
            $invoice->userId = $sms_cred[0]['username'];
            $invoice->business_id = $businessbranch[0];
            $invoice->branch_id = $businessbranch[1];
            
            $invoice->taxation_code = $invoice_data[0]['business_taxcode'];
            $invoice->ims_code = $invoice_data[0]['imsfiscal_invoice_number'];
            //$invoice->ims_code ="804236DF6N39554356*test*";

            if($invoice_data[0]['imsfiscal_invoice_number'] != ""){
                if($taxorg=="SRB"){
                    $invoice->tax_org = "SRB";
                    $invoice->tax_org_link = "https://pos.srb.gos.pk/InvoiceVerification/InvoiceStatus.jsp?invoiceVerification=".$invoice_data[0]['imsfiscal_invoice_number'];
                }else{
                    $invoice->tax_org ="PRA";
                    $invoice->tax_org_link ="https://e.pra.punjab.gov.pk/IMSFiscalReport/SearchPOSInvoice_Report.aspx?PRAInvNo=".$invoice_data[0]['imsfiscal_invoice_number'];                
                }
            }else{
                $invoice->tax_org = "";
                $invoice->tax_org_link = "";
            }

            $invoice->customer_name = $invoice_data[0]['customer_name'];
            $invoice->customer_cell = $invoice_data[0]['customer_cell'];
            $invoice->customer_cnic= '';
            $invoice->customer_email = $invoice_data[0]['customer_email'];

            $invoice->invoice_status = "Active";
            $invoice->payment_mode = $invoice_data[0]['mode'];
            $invoice->instrument_number = $invoice_data[0]['instrument_number'];
            $invoice->cashier = $invoice_data[0]['created_by'];

            $invoice->subtotal = $invoice_data[0]['sub_total'];
            $invoice->other_charges = $invoice_data[0]['other_charges'];

            $invoice->points_earned = $invoice_data[0]['loyalty_earned'];
            $invoice->points_used = $invoice_data[0]['loyalty_used'];
            $invoice->total_points = $loyaltypoints;

            $invoice->discount = 0;// $invoice_data[0]['invoice_discount'];

            if($taxmode=='after'){
                $invoice->total_before_tax = $invoice_data[0]['gross_wo_tax'];
            }elseif($taxmode=='before'){
                $invoice->total_before_tax = $invoice_data[0]['sub_total'];
            }
            $invoice->total_tax = $invoice_data[0]['tax_total'];           
                        
            $invoice->total_after_tax = $invoice_data[0]['total_payable'];
            
            $invoice->paid_amount = $invoice_data[0]['paid_amount'];
            $invoice->remaining_amount = $invoice_data[0]['balance'];
            $myItems = new stdClass();
            $x=1;
            foreach($invoice_data as $d){
                $detail = new stdClass();
                
                $detail->inv_detail_id = $d["id_invoice_details"];
                $detail->product_id = $d['service_id'];
                $detail->staff_id = $d['staff_id'];
                $detail->staff_name = $d['staff_name'];
                $detail->deal_name = $d['service_flag'] == 'packagetype' ?  $d['service_type'] :  '';
                $detail->type = $d["service_type"];                    
                $detail->category = $d["service_category"];
                $detail->product_name = $d['service_name'];
                $detail->barcode = $d['service_id'];
                $detail->product_id = $d['service_id'];
                $detail->unit_price =  $d['price']+$d['service_addition'];
                $detail->qty =  1.0;
                $detail->discount_percentage = $d['final_price'] > 0 ?  ceil((($d['discount']+$d['invoice_discount_item'])*100)/($d['price']+$d['service_addition'])) : 0;                
                $detail->discount_amount = round($d['invoice_discount_item']+$d['discount'],2);                

                // $detail->tax_percentage = $d['final_price'] > 0 ? ceil(($d['taxes']*100)/($d['final_price'])) : 0 ;
                // $detail->tax_amount =  round($d['taxes'],2);


                $detail->tax_percentage=0;
                $detail->tax_amount=0;

                $detail->total_price =  round($d['final_price'],2);
                
                $invoice->detail[]= $detail;            
                $x++;
            }
        }       

        //print_r($invoice); exit();
        $myJSON = json_encode($invoice);
        
        return $myJSON;
        
    }


    public function receiptsjson_sale($invoiceid, $sms_cred, $loyaltypoints, $business_id){

        $sql="select tax_mode, CASE WHEN srb_fiscal_sale = 'Yes' THEN 'SRB' ELSE 'PRA' END as tax_org from business where id_business = ". $business_id;
        $query=$this->db->query($sql);
        $tx = $query->row();
        $taxmode =$tx->tax_mode;
        $taxorg =$tx->tax_org;

        $businessbranch = explode("|", $sms_cred[0]['mask']);

        // $this->db->select("invoice.*, invoice_products.*, business_products.barcode_products, business.id_business, business.business_name, business.business_address, 
        // SUBSTRING(business_address, position('BR>' IN business_address)+3, length(business_address)) as business_taxcode, 
        // business.business_phone1, customers.customer_email,
        //  case when instrument_number like 'Online%' then 'Online' ELSE 'Check' END as payment_mode, 
        //  invoice.discount as invoice_discount, invoice_products.invoice_discount as invoice_discount_item, round(100*taxes/discounted_price ,2) as beforerate ", false);
        // $this->db->join('customers','customers.id_customers=invoice.customer_id');
        // $this->db->join('business','invoice.business_id=business.id_business');
        // $this->db->join('invoice_products','invoice_products.invoice_id = invoice.id_invoice');
        // $this->db->join('business_products','invoice_products.product_id = business_products.id_business_products');
        // $this->db->where('id_invoice', $invoiceid);
        // $query = $this->db->get('invoice');

        $sql = "select invoice.*, invoice_products.*, business_products.barcode_products, business.id_business, business.business_name, business.business_address, 
        SUBSTRING(business_address, position('BR>' IN business_address)+3, length(business_address)) as business_taxcode, 
        business.business_phone1, customers.customer_email,
        case when instrument_number like 'Online%' then 'Online'          
        Else payment_mode END as payment_mode, 
        invoice.discount as invoice_discount, invoice_products.invoice_discount as invoice_discount_item, round(100*taxes/discounted_price ,2) as beforerate 
        from invoice
        join customers on customers.id_customers=invoice.customer_id
        join business on invoice.business_id=business.id_business
        join invoice_products on invoice_products.invoice_id = invoice.id_invoice
        join business_products on invoice_products.product_id = business_products.id_business_products
        where id_invoice = ".$invoiceid;

        $query = $this->db->query($sql);  
        
        $invoice_data = $query->result_array();

        $invoice = new stdClass();

        if($query->num_rows() > 0){
            
             $invoice->inv_id = $invoice_data[0]["id_invoice"];
            $invoice->invoice_number = $invoice_data[0]['invoice_number'];
            $invoice->date = $invoice_data[0]['invoice_date'];
            $invoice->userId = $sms_cred[0]['username'];
            $invoice->business_id = $businessbranch[0];
            $invoice->branch_id = $businessbranch[1];
            
            
            $invoice->taxation_code = $invoice_data[0]['business_taxcode'];
            $invoice->ims_code = $invoice_data[0]['imsfiscal_invoice_number'];
            
            if($invoice_data[0]['imsfiscal_invoice_number'] != ""){
                if($taxorg=="SRB"){
                    $invoice->tax_org = "SRB";
                    $invoice->tax_org_link = "https://pos.srb.gos.pk/InvoiceVerification/InvoiceStatus.jsp?invoiceVerification=".$invoice_data[0]['imsfiscal_invoice_number'];
                }else{
                    $invoice->tax_org ="PRA";
                    $invoice->tax_org_link ="https://e.pra.punjab.gov.pk/IMSFiscalReport/SearchPOSInvoice_Report.aspx?PRAInvNo=".$invoice_data[0]['imsfiscal_invoice_number'];                
                }
            }else{
                $invoice->tax_org = "";
                $invoice->tax_org_link = "";
            }
            
            $invoice->customer_name = $invoice_data[0]['customer_name'];
            $invoice->customer_cell = $invoice_data[0]['customer_cell'];
            $invoice->customer_cnic= '';
            $invoice->customer_email = $invoice_data[0]['customer_email'];

            $invoice->invoice_status = "Active";
            $invoice->payment_mode = $invoice_data[0]['payment_mode'];
            $invoice->instrument_number = $invoice_data[0]['instrument_number'];
            $invoice->cashier = $invoice_data[0]['created_by'];


            $invoice->subtotal = $invoice_data[0]['sub_total'];
            $invoice->other_charges = $invoice_data[0]['other_charges'];

            $invoice->points_earned = $invoice_data[0]['loyalty_earned'];
            $invoice->points_used = $invoice_data[0]['loyalty_used'];
            $invoice->total_points = $loyaltypoints;

            if($taxmode=='after'){
                $invoice->total_before_tax = $invoice_data[0]['gross_wo_tax'];
            }elseif($taxmode=='before'){
                $invoice->total_before_tax = $invoice_data[0]['sub_total'];
            }
            $invoice->total_tax = $invoice_data[0]['tax_total'];           
                        
            $invoice->total_after_tax = $invoice_data[0]['total_payable'];
            
            $invoice->paid_amount = $invoice_data[0]['paid_amount'];
            $invoice->remaining_amount = $invoice_data[0]['balance'];


            $myItems = new stdClass();
            $x=1;
            foreach($invoice_data as $d){
                $detail = new stdClass();
                
                $detail->inv_detail_id = $d["id_invoice_products"];
                $detail->product_id = $d['product_id'];
                $detail->staff_id = $d['staff_id'];
                $detail->staff_name = $d['staff_name'];
                $detail->deal_name = '';

                $detail->type = $d["brand_name"];                    
                $detail->category = $d["brand_name"];
                

                $detail->product_name = $d['product_name'];
                $detail->barcode = $d['barcode_products'];
                $detail->unit_price =  $d['price']+$d['service_addition'];
                $detail->qty =  1.0;
                $detail->discount_percentage =  ceil(($d['discount']*100)/($d['price']+$d['service_addition']));   
                $detail->discount_amount = round($d['invoice_discount_item']+$d['discount'],2);                

                $detail->tax_percentage=0;
                $detail->tax_amount=0;

                $detail->total_price =  round($d['final_price'],2);
                
                $invoice->detail[]= $detail;            
                $x++;

                
            }
        }       

        //print_r($invoice); exit();
        $myJSON = json_encode($invoice);
        
        return $myJSON;
        
    }
    // ========================> jun-14-2024 End <========================

    function updateslipcode($invoice_id, $receipt_response){

        $response = json_decode($receipt_response);
        $receipt_url = '';

        if($invoice_id != null){
            foreach($response as $key=>$value){
                if($key == 'receipt_code'){
                    $this->db->set('receipt_code', $value);
                }elseif($key == 'reciept_url'){
                    $this->db->set('receipt_url', $value);
                    $receipt_url = $value;
                }
            }
            $this->db->where('id_invoice', $invoice_id);
            if($receipt_url != ""){
                $this->db->update('invoice');
            }else{
                return $receipt_response;
            }
            
            return $receipt_url;
        } else {
            return 0;
        }

    }

}
