<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require(APPPATH.'/libraries/RestController.php');

class Api extends \chriskacerguis\RestServer\RestController
{
    public function __construct() {
        parent::__construct();
        $this->load->model('api_model');        
        $this->load->model('Mobileapp_model');  
        $this->load->model('feedback_model');   
        $this->load->model('invoice_model');       
    }    
     
    public function index(){
        $r = array(
            'key' => 'method issue'
        );
        $this->response($r); 
    }
       
    public function onlinestaff_get(){
        $r = $this->api_model->getOnlineStaff(1);
        $this->response($r); 
    }
    
    public function branches_get(){
        $sql="select id_business, business_name from business;";
        
        $query = $this->db->query($sql);
        $r = $query->result();                
            
        $this->response($r); 
    }
    
    public function pricelist_get(){
        
        $business_id = $this->input->get('businessid');  
        
        //validate
        if($business_id == ''){
             $r = array(
                'key' => 'No Branch Selected!'                 
            );
            $this->response($r); 
            exit();
            
        }
        
        
        $r = $this->api_model->getPriceList($business_id);
        $this->response($r); 
        
    }
    
    public function sms_log_get(){
        
        $start_date = $this->input->get('startdate');
        $end_date = $this->input->get('enddate');
        $business_id = $this->input->get('businessid');
        
        if($start_date == '' || strlen($start_date) != 10){
             $r = array(
                'Error' => 'please use format yyyy-mm-dd!'                 
            );
            $this->response($r); 
            exit();
        }
        if($end_date == '' || strlen($end_date) != 10){
             $r = array(
                'Error' => 'please use format yyyy-mm-dd!'                    
            );
            $this->response($r); 
            exit();
        }
        
        if($business_id == ''){
             $r = array(
                'key' => 'No Branch Selected!'                 
            );
            $this->response($r); 
            exit();
            
        }else{
        
            $sql = "select sms_log.*, business_name from sms_log
                    join business on business_id = id_business
                    where business_id = '".$business_id."' and date(msgdate) >= '".$start_date."' and date(msgdate) <= '".$end_date."'";
            $query = $this->db->query($sql);
            $r = $query->result();                
            
            $this->response($r); 
        }
            
        
    }
    

    public function appointment_post(){
        
        //params[0]=cellNumber
        //params[1]=first_name
        //params[2]=last_name
        //params[3]=gender
        //params[4]=email
        //params[5]=bussinessid
        //params[6]=datetime
        //params[7]=services
        //params[8]=appointment_message
        
        $customer_cell  = $this->input->get('customer_cell');
        $first_name = $this->input->get('first_name');
        $last_name = $this->input->get('last_name');
        $customer_gender = $this->input->get('customer_gender');
        $customer_email = $this->input->get('customer_email');
        $business_id = $this->input->get('businessid');  
        $datetime = $this->input->get('datetime');
        $services = $this->input->get('services');
        $appointment_message = $this->input->get('appointment_message');  
        $discount = $this->input->get('discount');  
        
        if(null == $services || $services == 0){
            
            $this->db->select('id_business_services, service_name');
            $this->db->where('business_id', $business_id);
            $this->db->like('lower(service_name)', 'to be selected', false);
            $query = $this->db->get('business_services');
            $services_data=$query->row();

            if(isset($services_data)){
                $services = $services_data->id_business_services;
            }else{
                $r = array(
                   "Error" => "Service is NOT setup for online bookings."
                );
                $this->response($r); 
                exit();
            }
        } 
        
        //validate
        if($customer_cell == '' || strlen($customer_cell) != 11){
             $r = array(
                'Error' => 'This is not a valid cell number!'                 
            );
            $this->response($r); 
            exit();
        }
        if($first_name == '' || strlen($first_name) < 2){
             $r = array(
                'Error' => 'This is not a valid First Name!'                 
            );
            $this->response($r); 
            exit();
        }
        if($business_id == ''){
             $r = array(
                'Error' => 'Branch not Selected!'                 
            );
            $this->response($r); 
            exit();
        }
        if($datetime == ''){
             $r = array(
                'Error' => 'No Valid Calendar Date Selected!'                 
            );
            $this->response($r); 
            exit();
        }        
        
        
        
        //if all params available
        $staff = $this->Mobileapp_model->getOnlineStaff($business_id);  //get online staff
        $customer = $this->Mobileapp_model->getcustomerbycell($customer_cell); //check customer exists
        
        $customerid=1;
        if(isset($customer) && null!==$customer->id_customers){
            $customerid=$customer->id_customers;
        }else{
            $customerid=$this->Mobileapp_model->addnewcustomer($customer_cell, $first_name, $last_name, $customer_gender, $customer_email, $business_id);
            $customer = $this->Mobileapp_model->getcustomerbyid($customerid);
        }
        
        if(isset($staff) && $staff->staff_fullname=='Online Appointments'){
            
            $services = explode(",", $services);

            ///add visit
            $visit_id=$this->Mobileapp_model->add_visit($customerid, $datetime, $business_id, $appointment_message);

            //add visit services
            ///add visit staff
            $visit_service_id = $this->Mobileapp_model->add_visit_services($visit_id, $customerid, $customer->customer_name, $services, '', $staff->id_staff, $datetime, $business_id);
            
            
            $sql = "select id_customer_visits, service_name, s_rate, service_name, date_format(visit_service_start, '%H:%i') service_time, date_format(visit_service_start, '%a') visit_day, date_format(visit_service_start, '%D') visit_date,  date_format(visit_service_start, '%b') visit_month, date_format(visit_service_start, '%Y') visit_year  from customer_visits join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits where id_customer_visits = ". $visit_id.";";
            
            $query = $this->db->query($sql);
            
            $response_data = $query->result_array();
            
            
            $response = "Dear ". $customer->customer_name . ",\n\nYour Appointment is booked for ".$response_data[0]['visit_day'].", ".$response_data[0]['visit_month']." ". $response_data[0]['visit_year']."\n\n" ;
            
            foreach($response_data as $data){
                
                
                $response .= "⌚". $data['service_name']. " " .$data['service_time']."\n\n";
            }
            $response .= "*Hoping to see you soon!*";
            
            $this->response($response); 
            exit();
            


        } else {

            //return $this->xmlrpc->send_response('System is NOT setup for online bookings');
            $r = array(
                "Error" => "System is NOT setup for online bookings"
            );
            $this->response($r); 
            exit();
        }
        
        //$r = $this->api_model->book_appointment($business_id, $customer_cell, $first_name, $last_name, $customer_gender, $customer_email, $services, $datetime);
        
        
        $this->db->select('business_phone1');
        $this->db->where('id_business', $business_id);
        $this->db->get('business');
        $contact = $this->db->row();
        
        $r = array(
             "Info" => "Sorry but we could not register your request at this time. Please contact us at ". $contact->business_phone1 ." Thank you"
        );
        $this->response($r); 
        
    }


    public function update_service_post(){

        $visit_service_id = $this->input->post('id_visit_services');     
        $visit_service_start = $this->input->post('visit_date') . "T" . $this->input->post('start_time') .":00";
        $visit_service_end = $this->input->post('visit_date') . "T" . $this->input->post('end_time') .":00";    
        $visit_service_status =  $this->input->post('service_status');            

        $this->db->where('id_visit_services', $visit_service_id);
        $this->db->set('visit_service_start', $visit_service_start);
        $this->db->set('visit_service_end', $visit_service_end);
        $this->db->set('visit_service_status', $visit_service_status);
        $this->db->update('visit_services');
        $r = array(
            "Info" => "Service has been updated for visit ".$visit_service_id
        );
        $this->response($r); 

    }

    public function update_visit_post(){

        $this->db->select('id_business, business_opening_time, business_closing_time, rec_allow_prev as previous');
        $this->db->where('id_business', $this->session->userdata('businessid'));
        $query = $this->db->get('business');
        $business=$query->row();
        
        $business_end_time = date("H:i:s",strtotime($business->business_closing_time.":00")) ;

        $visit_id = $this->input->post('id_customer_visits');     
        $visit_date = $this->input->post('visit_date');     
        $visit_status =  $this->input->post('visit_status');      
        $visit_service_start =  $this->input->post('start_time') .":00";      
        $start = $this->input->post('start_time');

        $sql = "update visit_services set visit_service_start = concat('".$visit_date."', substr(visit_service_start, position('T' IN visit_service_start ), length(visit_service_start))), 
            visit_service_end = concat('".$visit_date."', substr(visit_service_end, position('T' IN visit_service_end ), length(visit_service_end))) where
            customer_visit_id = ".$visit_id."
        ";

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

        $sql1 = "update customer_visits set visit_status = '".$visit_status."' where id_customer_visits = ".$visit_id.";";        
        $query1 = $this->db->query($sql1);
 


        $r = array(
            "Info" => "Visit ".$visit_id. " has been updated."
        );
        $this->response($r); 
    }
    
    

    public function add_appointment_post(){

        $customer_cell  = $this->input->post('customer_cell');
        $first_name = $this->input->post('first_name');
        $last_name = $this->input->post('last_name');
        $customer_gender = $this->input->post('customer_gender');
        $customer_email = $this->input->post('customer_email');
        $business_id = $this->input->post('businessid');  
        $datetime = $this->input->post('datetime');
        $services = $this->input->post('services');
        $appointment_message = $this->input->post('appointment_message');  
        $extra = $this->input->post('extra');      
        $discount = $this->input->post('discount');  

        

        if(null == $services || $services == 0){
            
            $this->db->select('id_business_services, service_name');
            $this->db->where('business_id', $business_id);
            $this->db->like('lower(service_name)', 'to be selected', false);
            $query = $this->db->get('business_services');
           
            
            $services_data=$query->row();
            if(isset($services_data)){
                $services = $services_data->id_business_services;
            }else{
                $r = array(
                   "Error" => "Service is NOT setup for online bookings."
                );
                $this->response($r); 
                exit();
            }
        } 
        
        //validate
        if($customer_cell == '' || strlen($customer_cell) != 11){
             $r = array(
                'Error' => 'This is not a valid cell number!'                 
            );
            $this->response($r); 
            exit();
        }
        if($first_name == '' || strlen($first_name) < 2){
             $r = array(
                'Error' => 'This is not a valid First Name!'                 
            );
            $this->response($r); 
            exit();
        }
        if($business_id == ''){
             $r = array(
                'Error' => 'Branch not Selected!'                 
            );
            $this->response($r); 
            exit();
        }
        if($datetime == ''){
             $r = array(
                'Error' => 'No Valid Calendar Date Selected!'                 
            );
            $this->response($r); 
            exit();
        }        
        
        
        
        //if all params available
        //$staff = $this->Mobileapp_model->getOnlineStaff($business_id);  //get online staff

        $this->db->select('id_staff, staff_fullname');
        $this->db->where('business_id', $business_id);
        $this->db->like('lower(staff_fullname)', 'online');
        $query = $this->db->get('staff');

        $staff =$query->row();

        $customer = $this->Mobileapp_model->getcustomerbycell($customer_cell); //check customer exists
        
        $customerid=1;
        if(isset($customer) && null!==$customer->id_customers){
            $customerid=$customer->id_customers;
        }else{
            $customerid=$this->Mobileapp_model->addnewcustomer($customer_cell, $first_name, $last_name, $customer_gender, $customer_email, $business_id);
            $customer = $this->Mobileapp_model->getcustomerbyid($customerid);
        }
        
        if(isset($staff)){
             //ensure service presence
             $sql="select id_business_services 
             from business_services where id_business_services in 
             (".$services.") and business_id = ".$business_id;             
            $query = $this->db->query($sql);
            if($query->num_rows() ==0){
                $r = array(
                    "Error" => "Wrong Services"
                );
                $this->response($r); 
                exit();
            }
            
            $services = explode(",", $services);
           

            ///add visit
            $visit_id=$this->Mobileapp_model->add_visit($customerid, $datetime, $business_id, $appointment_message, 0, $discount);

            if($extra != null){
                if ($this->db->field_exists('visit_extra', 'customer_visits')) {
                    $this->db->set('visit_extra', $extra);
                    $this->db->where('id_customer_visits', $visit_id);
                    $this->db->update('customer_visits');
                }
            }

            //add visit services
            ///add visit staff
            $visit_service_id = $this->Mobileapp_model->add_visit_services($visit_id, $customerid, $customer->customer_name, $services, '', $staff->id_staff, $datetime, $business_id);
            
            
            $sql = "select id_customer_visits, service_name, s_rate, service_name, date_format(visit_service_start, '%H:%i') service_time, date_format(visit_service_start, '%a') visit_day, date_format(visit_service_start, '%D') visit_date,  date_format(visit_service_start, '%b') visit_month, date_format(visit_service_start, '%Y') visit_year  from customer_visits join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits where id_customer_visits = ". $visit_id.";";
            
            $query = $this->db->query($sql);
            
            $response_data = $query->result_array();
            
            
            $response = "Dear ". $customer->customer_name . ",\n\nYour Appointment is booked for ".$response_data[0]['visit_day'].", ".$response_data[0]['visit_month']." ". $response_data[0]['visit_year']."\n\n" ;
            
            foreach($response_data as $data){
                
                
                $response .= "⌚". $data['service_name']. " " .$data['service_time']."\n\n";
            }
            $response .= "*Hoping to see you soon!*";
            
            
            $r = array(
                "Success" => $response
            );
            $this->response($r); 
            exit();
            
            


        } else {

          
            $r = array(
                "Error" => "Staff is NOT setup for online bookings"
            );
            $this->response($r); 
            exit();
        }
        
        //$r = $this->api_model->book_appointment($business_id, $customer_cell, $first_name, $last_name, $customer_gender, $customer_email, $services, $datetime);
        
        
        $this->db->select('business_phone1');
        $this->db->where('id_business', $business_id);
        $this->db->get('business');
        $contact = $this->db->row();
        
        $r = array(
             "Info" => "Sorry but we could not register your request at this time. Please contact us at ". $contact->business_phone1 ." Thank you"
        );
        $this->response($r); 
        
    }
    
    function appointments_get(){

        $customer_cell = $this->input->get('customer_cell');  
        $this->db->select('customers.customer_name, customers.customer_cell, customers.id_customers, customers.customer_gender, customers.customer_email');
        $this->db->select('customer_visits.id_customer_visits, customer_visits.business_id');
        $this->db->select("visit_services.id_visit_services, date_format(visit_service_start, '%a, %b %Y') as visit_date, date_format(visit_service_start, '%H:%i') as start_time, date_format(visit_service_end, '%H:%i') as end_time");
        $this->db->select("business.id_business, business_name, business_address");
        $this->db->join('customers', 'customers.id_customers = customer_visits.customer_id');
        $this->db->join('visit_services', 'visit_services.customer_visit_id = customer_visits.id_customer_visits');
        $this->db->join('business', 'business.id_business = customer_visits.business_id');
        $this->db->where('customers.customer_cell', $customer_cell);
        $this->db->where('customer_visits.visit_status', 'open');
        $this->db->where('date(visit_services.visit_service_start) >=', date('Y-m-d'));
        $query = $this->db->get('customer_visits');
        $data = $query->result();

        $response = '';
        foreach($data as $d){

            $response .= "\n📝 Appointment No.: ". $d->id_customer_visits."\n";
            $response .= "🦱 Name: ". $d->customer_name."\n";
            $response .= "📆 Date: ". $d->visit_date."\n";
            $response .= "⏰ Slot: ". $d->start_time." to ".$d->end_time."\n";

        }
        echo $response;

    //     $r = array(
    //         "Info" => $response
    //    );
    //    $this->response($r); 

    }

    function cancel_appointment_post(){

        $id_customer_visits = $this->input->get('appointment_id');  

        $this->db->set('visit_status', 'Cancelled');
        //$this->db->set('cancelled_on', date('Y-m-d H:i:s'));
        $this->db->set('canceled_by', 'Customer');
        $this->db->set('cancelreason', 'Customer Cancellation');
        $this->db->where('customer_visits.id_customer_visits', $id_customer_visits);
        $this->db->update('customer_visits');
        
        $response = '';
        $response .= "📝 Appointment No.: ". $id_customer_visits."\n";
        $response .= "has been cancelled.\n";
        
        
        echo $response;

    //     $r = array(
    //         "Info" => $response
    //    );
    //    $this->response($r); 

    }

    function service_types_get(){
        $business_id = $this->input->get('businessid');  

        $data=[];
        $this->db->select('id_service_types id, business_id, service_type as name, concat("'. 'assets/images/servicetype/' .'", ifnull(service_type_image, "nu.jpg")) as service_type_image, service_type_active, order_id, "servicetype" as "flag"');
        $this->db->where('business_id', $business_id);
        $this->db->where('service_type_active', 'Yes');
        
        $subQuery1 = $this->db->get('service_type');
        $services=$subQuery1->result_array();
        
        $key_values = array_column($services, 'order_id'); 
        array_multisort($key_values, SORT_ASC, $services);
        
        $this->response($services); 
        
        // $this->db->select('id_package_type as "id_service_types", business_id, service_type, concat("'. 'assets/images/servicetype/' .'", ifnull(service_type_image, "nu.jpg")) as service_type_image, service_type_active, order_id, "packagetype" as "flag"');
        // $this->db->where('business_id', $business_id);
        // $this->db->where('service_type_active', 'Yes');
        // $this->db->where('expiry_date >', date('Y-m-d'));
        
        // $subQuery2 = $this->db->get('package_type');
        // $packages=$subQuery2->result_array();
        
        // $key_values = array_column($packages, 'order_id'); 
        // array_multisort($key_values, SORT_ASC, $packages);
        
        // $data = array_merge($services, $packages);
        // $this->response($data); 
    }


    function service_categories_get(){        
        $business_id = $this->input->get('businessid');  
        $type_id = $this->input->get('typeid');  
        
        $flag = $this->input->get('flag');  

        if($flag==="servicetype"){
            $this->db->select('id_service_category, id_service_category id, service_type_id, service_type, service_category.order_id, service_category, service_category name, service_category.business_id, business_name, service_category_active,  concat("assets/images/category/", ifnull(service_category_image, "nu.png")) as service_category_image, \'servicetype\' flag', false);
            $this->db->join('service_type','service_type.id_service_types = service_category.service_type_id');
            $this->db->join('business','business.id_business = service_category.business_id');
            $this->db->where('service_category.service_category_active', 'Yes');      
            if(null!=$type_id){
                $this->db->where('service_category.service_type_id', $type_id);
            } 
            $Query1 = $this->db->get('service_category');
            $data=$Query1->result_array();
        } else {
            $this->db->select('id_package_category, id_package_category id, package_type_id service_type_id, service_type, package_category.order_id, service_category, service_category name, package_category.business_id, business_name, service_category_active, concat("assets/images/category/", ifnull(service_category_image, "nu.png")) as service_category_image, \'packagetype\' flag', false);
            $this->db->join('package_type','package_type.id_package_type = package_category.package_type_id');
            $this->db->join('business','business.id_business = package_category.business_id');
            $this->db->where('package_category.service_category_active', 'Yes'); 
            if(null!=$type_id){
                $this->db->where('package_catgory.package_type_id', $type_id);
            }        
            $Query2 = $this->db->get('package_category');
            $data=$Query2->result_array();
        }
        
        
        $this->response($data); 
    }

    function services_get(){
        $business_id = $this->input->get('businessid');  
        $category_id = $this->input->get('categoryid');  
        $flag = $this->input->get('flag');  

        if($flag==="packagetype"){
            $this->db->select("business_services.*, id_business_services as id, concat(business_services.service_name, ' | ', service_rate, ' | ', service_duration) as name, package_services.service_rate as price, package_type.service_type, package_type.id_package_type as id_service_type, package_category.service_category,  package_category_id as service_category_id, 'packagetype' as flag, service_duration, '20' as discount ", false);
            $this->db->select('format(package_services.service_rate,2) as "service_rate" ', false);
            $this->db->join('package_services', 'business_services.id_business_services = package_services.service_id');
            $this->db->join('package_category', 'package_category.id_package_category = package_services.package_category_id');
            $this->db->join('package_type', 'package_type.id_package_type = package_category.package_type_id');            
            $this->db->where('package_category_id', $category_id);
            $this->db->where('service_active', 'Yes');
            
            $this->db->order_by('order_id', 'ASC');
        } else {
            $this->db->select("business_services.*, id_business_services as id, concat(business_services.service_name, ' | ', service_rate, ' | ', service_duration)  as name,  service_rate as price, service_type.service_type, service_type.id_service_types as id_service_type, service_category.service_category,'servicetype' as flag, service_duration, '20' as discount", false);
            $this->db->select("format(business_services.service_rate,2) as 'service_rate' ", false);
             $this->db->join('service_category', 'service_category.id_service_category = business_services.service_category_id');
            $this->db->join('service_type', 'service_type.id_service_types = service_category.service_type_id');
            //$this->db->where('business_id', $this->session->userdata('businessid'));
            $this->db->where('service_category_id', $category_id);
            $this->db->where('service_active', 'Yes');
            //$this->db->order_by('id_business_services', 'ASC');
            $this->db->order_by('order_id', 'ASC');
        }
        $query = $this->db->get('business_services');
              
        $this->response($query->result());  

    }

    function available_slots_get(){
        $business_id = $this->input->get('businessid');  
        $selecteddate = $this->input->get('selecteddate');  

        $slotduration = $this->input->get('slotduration') != null ?  $this->input->get('slotduration') : '00:15';  

        $this->db->select('business_opening_time, business_closing_time');
        $this->db->where('id_business', $business_id);
        $query = $this->db->get('business');

        

        $businesstime = $query->row();

        if($query->num_rows() == 0){
            $r = array(
                'Error' => 'No Such Business!'                    
            );
            $this->response($r); 
            exit();
        }

        $this->db->select('count(id_staff) as staffcount');
        $this->db->where('staff_active', 'y');
        $this->db->where('staff_scheduler', 'On');
        $this->db->where('staff_firstname !=', 'Online');
        $this->db->where('business_id', $business_id);
        $query1 = $this->db->get('staff');
        $staff = $query1->row();

        if($query1->num_rows() == 0){
            $r = array(
                'Error' => 'No Staff Available!'                    
            );
            $this->response($r); 
            exit();
        }

        $business_opening_time = $businesstime->business_opening_time;
        $business_closing_time = $businesstime->business_closing_time;
        if(date("Y-m-d") == $selecteddate){
            $my_minutes = date('i');
            $my_minutes = $my_minutes + ( 5- ($my_minutes % 5)) +5 ;            
            $business_opening_time = date('H:').$my_minutes;
        } 
        
        
        $sql="SELECT  ".$staff->staffcount." as totalstaff, count(staff_id) as busystaff,  ".$staff->staffcount."-count(staff_id) as availablestaff, start_time, end_time ,
                null as id, concat(start_time, ' - ', end_time) as name
                FROM (
                        WITH RECURSIVE time_slots AS (
                            SELECT TIME(CONCAT('".$business_opening_time."',':00')) AS start_time                    
                            UNION ALL                    
                            SELECT ADDTIME(start_time, '".$slotduration."')                    
                            FROM time_slots                    
                            WHERE time(start_time) < time('".$business_closing_time."')                
                        )                
                        SELECT date('".$selecteddate."') md, start_time, ADDTIME(start_time, '".$slotduration."') AS end_time                
                        FROM time_slots                
                        WHERE ADDTIME(start_time, '".$slotduration."') < time('".$business_closing_time."')            
                        ) as a        
                LEFT JOIN (
                        SELECT staff_id, date_format(visit_service_start, '%Y-%m-%d %H:%i:%s') visit_service_start, date_format(visit_service_end, '%Y-%m-%d %H:%i:%s') visit_service_end
                            FROM visit_services             
                            JOIN visit_service_staffs ON visit_service_staffs.visit_service_id = visit_services.id_visit_services            
                            WHERE visit_services.business_id=".$business_id."           
                            AND DATE(visit_service_start) = '".$selecteddate."'      
                        UNION
                            SELECT id_staff as staff_id, date_format(concat('".$selecteddate."',' ', '".$business_opening_time."'), '%Y-%m-%d %H:%i:%s')  visit_service_start,  date_format(concat('".$selecteddate."',' ', staff.day_start_time), '%Y-%m-%d %H:%i:%s')   visit_service_end            
                            FROM staff			
                            WHERE staff.business_id=".$business_id."  and staff.staff_active='Y' and staff.staff_scheduler='On'
                        UNION
                            SELECT id_staff as staff_id, date_format(concat('".$selecteddate."',' ', staff.day_end_time), '%Y-%m-%d %H:%i:%s')  visit_service_start,  date_format(concat('".$selecteddate."',' ', '".$business_closing_time."'), '%Y-%m-%d %H:%i:%s')   visit_service_end            
                            FROM staff			
                            WHERE staff.business_id=".$business_id."  and staff.staff_active='Y' and staff.staff_scheduler='On' 
                        UNION
                            SELECT id_staff as staff_id, date_format(block_staff_time.start_time, '%Y-%m-%d %H:%i:%s')  visit_service_start, date_format(block_staff_time.end_time, '%Y-%m-%d %H:%i:%s')  visit_service_end 
                            FROM staff
                            JOIN block_staff_time on staff.id_staff = block_staff_time.staff_id
                            WHERE DATE(block_staff_time.start_time) = '".$selecteddate."' and staff.business_id=".$business_id."  and staff.staff_active='Y' and staff.staff_scheduler='On' 
                        order by 1,2
                    ) as visit_services ON a.md = DATE(visit_services.visit_service_start)  ";        

        $sql.=" AND
                (TIME(visit_services.visit_service_start) >= TIME(a.start_time) AND TIME(visit_services.visit_service_end) <= TIME(a.end_time) AND TIME(visit_services.visit_service_start) < TIME(a.end_time) AND TIME(visit_services.visit_service_end) > TIME(a.start_time))
                or
                (TIME(visit_services.visit_service_start) <= TIME(a.start_time) AND TIME(visit_services.visit_service_end) <= TIME(a.end_time) AND TIME(visit_services.visit_service_start) < TIME(a.end_time) AND TIME(visit_services.visit_service_end) > TIME(a.start_time))
                or
                (TIME(visit_services.visit_service_start) >= TIME(a.start_time) AND TIME(visit_services.visit_service_end) >= TIME(a.end_time) AND TIME(visit_services.visit_service_start) < TIME(a.end_time) AND TIME(visit_services.visit_service_end) > TIME(a.start_time))
                or
                (TIME(visit_services.visit_service_start) <= TIME(a.start_time) AND TIME(visit_services.visit_service_end) >= TIME(a.end_time) AND TIME(visit_services.visit_service_start) < TIME(a.end_time) AND TIME(visit_services.visit_service_end) > TIME(a.start_time))
                or
                (TIME(visit_services.visit_service_start) = TIME(a.start_time) AND TIME(visit_services.visit_service_end) = TIME(a.end_time) AND TIME(visit_services.visit_service_start) < TIME(a.end_time) AND TIME(visit_services.visit_service_end) > TIME(a.start_time))
                
            GROUP BY start_time, end_time 
            having ".$staff->staffcount."-count(staff_id)>0    
            ORDER BY 5";


       // echo $sql; exit();

        $q = $this->db->query($sql);        
        
        $this->response($q->result_array());  
        
    }

    function check_customer_get(){

        $customer_cell = $this->input->get('cell');

        $sql="select id_customers, customer_name, customer_cell, customer_email, customer_address, customer_gender 
            from customers 
            where 
            customer_cell like '%".$customer_cell."%' order by id_customers limit 1";

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

    }

    function locations_get(){

        $sql = "select id_business, id_business as id, business_name as name, business_name, business_address, business_phone1, business_owner, business_email from business where id_business < 50";
        $q = $this->db->query($sql);        
        
        $this->response($q->result_array());  

    }

    function booking_extra_get(){

        $extra = $this->input->get('extra'); 


        $sql = "SELECT customer_visits.id_customer_visits, customer_visits.visit_extra, visit_services.id_visit_services, visit_services.visit_service_start servicestart, visit_services.visit_service_end serviceend,
                date_format(visit_service_start, '%Y-%m-%d') servicedate, date_format(visit_service_start, '%H:%i') starttime,
                date_format(visit_service_end, '%H:%i') endtime, visit_services.service_id, visit_services.service_name,
                visit_services.s_category service_category, visit_services.s_type service_type,
                visit_services.service_flag, visit_services.s_rate, discount,
                customers.customer_name, customers.customer_cell, customers.customer_gender, customers.customer_email,
                id_business, business_name
                FROM customer_visits
                JOIN visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits AND visit_services.visit_service_status = 'Active'
                JOIN customers on customers.id_customers = customer_visits.customer_id
                JOIN business on customer_visits.business_id = business.id_business
                WHERE visit_extra = '".$extra."' AND customer_visits.visit_status = 'open'
                order by id_customer_visits desc";

        $q = $this->db->query($sql);        

        $this->response($q->result_array());  
        

    }

    function booking_cell_get(){

        $cell = $this->input->get('cell'); 

        $sql = "SELECT customer_visits.id_customer_visits, customer_visits.visit_extra, visit_services.id_visit_services, visit_services.visit_service_start servicestart, visit_services.visit_service_end serviceend,
                date_format(visit_service_start, '%Y-%m-%d') servicedate, date_format(visit_service_start, '%H:%i') starttime,
                date_format(visit_service_end, '%H:%i') endtime, visit_services.service_id, visit_services.service_name,
                visit_services.s_category service_category, visit_services.s_type service_type,
                visit_services.service_flag, visit_services.s_rate, discount,
                customers.customer_name, customers.customer_cell, customers.customer_gender, customers.customer_email,
                id_business, business_name
                FROM customer_visits
                JOIN visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits AND visit_services.visit_service_status = 'Active'
                JOIN customers on customers.id_customers = customer_visits.customer_id
                JOIN business on customer_visits.business_id = business.id_business
                WHERE customers.customer_cell = '".$cell."' AND customer_visits.visit_status = 'open'
                order by id_customer_visits desc";

        $q = $this->db->query($sql);        

        $this->response($q->result_array());  
        

    }


    function last_invoice_get(){

        $cell = $this->input->get('cell'); 

        $sql = "select id_invoice, invoice_number, receipt_url, receipt_code, 
        date_format(invoice_date, '%d-%m-%Y %H:%i') as invoice_date        
        From invoice
        Where customer_cell like '%".$cell."%'  and invoice_status='valid' order by id_invoice desc limit 1;";

        $q = $this->db->query($sql);        

        $this->response($q->result_array());  

    }


    ///////////Inventory API///////////////////////
    public function  addbrand_post() {
        if($this->input->post('business_brand_name', TRUE) !='' && $this->input->post('business_id', TRUE)!=''){        
            $data = array(
                'business_brand_name' => $this->input->post('business_brand_name', TRUE),
                'business_brand_short' => $this->input->post('business_brand_short', TRUE),
                'business_brand_website' => $this->input->post('business_brand_website', TRUE),
                'business_id' => $this->input->post('business_id', TRUE)
            );

            $this->db->insert('business_brands', $data);
            $id =  $this->db->insert_id();

            $r = array(
                "Success" => "Brand Added with ID ".$id
            );
            $this->response($r); 
            exit();
        } else {
            
            $r = array(
                "Error" => "Incomplete Data passed"
            );
            $this->response($r); 
            exit();
            
        }
    }
    
    
    function updatebrand_post() {
        if($this->input->post('business_brand_name', TRUE) !='' && $this->input->post('business_id', TRUE)!=''){        
            $data = array(
                'business_brand_name' => $this->input->post('business_brand_name', TRUE),
                'business_brand_short' => $this->input->post('business_brand_short', TRUE),
                'business_brand_website' => $this->input->post('business_brand_website', TRUE),
                'business_brand_active' => $this->input->post('business_brand_active', TRUE)
            );

            $this->db->where('id_business_brands', $this->input->post('id_business_brands', TRUE));
            //$this->db->where('business_brands.business_id', $this->session->userdata('businessid'));
            $this->db->update('business_brands', $data);
             $id =  $this->db->affected_rows();
           

            $r = array(
                "Success" => "Brand update"
            );
            $this->response($r); 
            exit();
        } else {
            
            $r = array(
                "Error" => "Incomplete Data passed"
            );
            $this->response($r); 
            exit();
            
        }
    }
    
    public function addproduct_post(){
        if($this->input->post('brand_id', TRUE) !='' && $this->input->post('business_id', TRUE)!=''){        
            $data = array(
                'brand_id' => $this->input->post('brand_id', TRUE),
                'category' => $this->input->post('category', TRUE),
                'product' => str_replace("&", "-", trim($this->input->post('product', TRUE))),
                'sku' => $this->input->post('sku', TRUE),
                'commission' => $this->input->post('commission', TRUE),
                'barcode_products' => $this->input->post('barcode', TRUE),
                'price' => $this->input->post('price', TRUE),
                'purchase_price' => $this->input->post('purchase_price', TRUE),
                'measure_unit' => $this->input->post('measurement_unit', TRUE),
                'unit_type' => $this->input->post('unit_type', TRUE),
                'qty_per_unit' => $this->input->post('qty_per_unit', TRUE),
                'professional' => $this->input->post('professional', TRUE),
                'business_id' => $this->input->post('business_id', TRUE),
                'product_threshold'=> $this->input->post('threshold', TRUE),
                'product_type'=>$this->input->post('product_type', TRUE)
            );

            $this->db->insert('business_products', $data);
            $insert_id = $this->db->insert_id();

             $r = array(
                "Success" => "Product Added with ID ".$insert_id
            );
            $this->response($r); 
            exit();
        } else {
            
            $r = array(
                "Error" => "Incomplete Data passed"
            );
            $this->response($r); 
            exit();
            
        }
    }    
    
    public function updateproduct_post(){
        if($this->input->post('id_business_products', TRUE) !='' && $this->input->post('business_id', TRUE)!=''){        
            $data = array(
                'brand_id' => $this->input->post('brand_id', TRUE),
                'category' => $this->input->post('category', TRUE),
                'product' => str_replace("&", "-", trim($this->input->post('product', TRUE))),
                'sku' => $this->input->post('sku', TRUE),
                'commission' => $this->input->post('commission', TRUE),
                'barcode_products' => $this->input->post('barcode', TRUE),
                'price' => $this->input->post('price', TRUE),
                'purchase_price' => $this->input->post('purchase_price', TRUE),
                'measure_unit' => $this->input->post('measurement_unit', TRUE),
                'unit_type' => $this->input->post('unit_type', TRUE),
                'qty_per_unit' => $this->input->post('qty_per_unit', TRUE),
                'professional' => $this->input->post('professional', TRUE),
                'business_product_active' => $this->input->post('business_product_active', TRUE),
                'product_threshold'=> $this->input->post('threshold', TRUE),
                'product_type'=>$this->input->post('product_type', TRUE)
            );

            $this->db->where('id_business_products', $this->input->post('id_business_products', TRUE));
            // $this->db->where('business_products.business_id', $this->session->userdata('businessid'));
             $this->db->update('business_products', $data);


            $update_id = $this->db->affected_rows();

            $r = array(
                "Success" => "Product Updated"
            );
            $this->response($r); 
            exit();
        } else {
            
            $r = array(
                "Error" => "Incomplete Data passed"
            );
            $this->response($r); 
            exit();
            
        }   
    }
    
    
    public function brands_get(){
        
        $lastupdated = $this->input->get('lastupdated');
        
        $this->db->select("*");
        $this->db->where("last_updated >=", $lastupdated);
        $query = $this->db->get('business_brands'); 
        
        $brands = $query->result_array();
        $this->response($brands); 
        
    }
    
    public function products_get(){
         
        $lastupdated = $this->input->get('lastupdated');
        
        $this->db->select("*");
        $this->db->where("last_updated >=", $lastupdated);
        $query = $this->db->get('business_products');         
        $products = $query->result_array();
        
        $this->response($products); 
        
    }
    
    
    public function batches_get(){
        
        $storeid = $this->input->get('storeid');
        $lastupdated = $this->input->get('lastupdated');
        
        $this->db->select("*");
        $this->db->where("store_id", $storeid);
        $this->db->where("last_updated >=", $lastupdated);
        $query = $this->db->get('product_batch');         
        $batches = $query->result_array();
        
        $this->response($batches); 
        
    }
    
    public function transfernotes_get(){
        
        $storeid = $this->input->get('storeid');
        $lastupdated = $this->input->get('lastupdated');
        
        $this->db->select("transfer_notes.*,  gtn.*");
        $this->db->join("product_batch","product_batch.id_batch = transfer_notes.batch_id");
        $this->db->join("gtn","gtn.id_gtn = transfer_notes.gtn_id");
        $this->db->where("product_batch.store_id", $storeid);
        $this->db->where("tranfer_in_qty >", 0);
        $this->db->where("transfer_notes.last_updated >=", $lastupdated);
        $query = $this->db->get('transfer_notes');
        $transfernotes = $query->result_array();
        
        $this->response($transfernotes); 
        
    }
    
    
    


    public function incentivizer_services_get(){

        $services[] = $this->input->get('services');
        $invoicedate = $this->input->get('calendar_date_service');
        
        //print_r($services[0]); exit();
        $sql_create_table = "select invoice_details.*, invoice_staff.staff_id, invoice_staff.staff_name, 
            business.business_name , 
            date(invoice.invoice_date) as invoice_date
            from invoice 
            join invoice_details on invoice.id_invoice=invoice_details.invoice_id
            join invoice_staff on invoice_detail_id = invoice_details.id_invoice_details and additional_staff = 'No'
            join business on invoice.business_id = business.id_business
            join
            (
            SELECT  id_business_services, service_name, service_rate
            FROM business_services
            JOIN service_category on id_service_category = business_services.service_category_id 
            WHERE id_service_category in (";
        $x=1;
        foreach($services[0] as $service){           
            
            if($x < sizeof($services[0])){
                $sql_create_table .=  $service .", ";
                $x++;
            }else{
                $sql_create_table .=  $service ."";
                $x++;
            }            
        }
               
        $sql_create_table .= "))as a
                    on a.id_business_services = invoice_details.service_id 
                WHERE
                invoice.invoice_status='valid'
                and date_format(invoice_date,'%Y-%m') = '".$invoicedate."'
                ";
       
      $this->db->query($sql_create_table);       
        
        
        $report_sql="SELECT business_name, staff_id, staff_name, service_category, service_name,
            month(invoice_date) month, year(invoice_date) year,
            discounted_price as price
            FROM (".$sql_create_table.") as subtable 
            group by business_id, staff_id, month(invoice_date), year(invoice_date), service_category, service_name
            order by business_id, staff_id, month(invoice_date), year(invoice_date), service_category, service_name;";
        $query = $this->db->query($report_sql);
        $data['response_services'] = $query->result_array();
        
        $data['brands'] =  $this->get_brands();
           
        //get service categories
        $data['services'] = $this->get_service_categories();
        
        $data['selected_date']=$invoicedate;
        $data['selected_services']=$services;
        
        
        $this->response($data); 
    }


    public function inventivizer_product_get(){
        $data['nav'] = 'reports';
        $data['subnav'] = 'incentivizer';
        
        $brands[] = $this->input->get('brands');
        $invoicedate = $this->input->get('calendar_date_product');
         
       // print_r($brands[0]); exit();
        $sql_create_table = "select invoice_products.*, business.business_name ,            
            date(invoice.invoice_date) as invoice_date
            from invoice 
            join invoice_products on invoice.id_invoice=invoice_products.invoice_id 
            join business on invoice.business_id = business.id_business
            join
            (
            SELECT  id_business_products, product, business_products.price
            FROM `business_products`
            JOIN business_brands on id_business_brands = business_products.brand_id 
            WHERE id_business_brands in (";
        $x=1;
        foreach($brands[0] as $brand){           
            
            if($x < sizeof($brands[0])){
                $sql_create_table .=  $brand .", ";
                $x++;
            }else{
                $sql_create_table .=  $brand ."";
                $x++;
            }            
        }
               
        $sql_create_table .= "))as a
                    on a.id_business_products = invoice_products.product_id 
                WHERE
                invoice.invoice_status='valid'
                and date_format(invoice_date,'%Y-%m') = '".$invoicedate."'
                ";
   
        $report_sql="SELECT business_name, staff_id, staff_name, brand_name, product_name,
            month(invoice_date) as month, year(invoice_date) as year,
            sum(invoice_qty) as qty, sum(invoice_qty * discounted_price) as price
            FROM (".$sql_create_table.") as subtable 
            group by business_id, staff_id, month(invoice_date), year(invoice_date), brand_name, product_name
            order by business_id, staff_id, month(invoice_date), year(invoice_date), brand_name, product_name;";
        $query = $this->db->query($report_sql);
        $data['response_products'] = $query->result_array();
        
        
        $data['brands'] =  $this->get_brands();
        $data['services'] = $this->get_service_categories();
        $data['selected_date']=$invoicedate;
        $data['selected_brands']=$brands;
        $data['selected_date']=$invoicedate;

        $this->response($data); 
    }


    function get_brands(){
        $this->db->select("business_brands.*, id_business, business_name");
        $this->db->join('business','business.id_business = business_brands.business_id');
        if($this->session->userdata('common_products')=='No'){

        } else {
            $this->db->where('business.common_products', 'Yes');
        }
        $this->db->where('business_brands.business_brand_active', 'Yes');

        $query = $this->db->get('business_brands');
        return $query->result_array();
        
    }

    
    function get_service_categories(){
        
        $this->db->select('id_service_category, service_type_id, service_type, service_category.order_id, service_category, service_category.business_id, business_name, service_category_active,  concat("assets/images/category/", ifnull(service_category_image, "nu.png")) as service_category_image, \'servicetype\' flag', false);
        $this->db->join('service_type','service_type.id_service_types = service_category.service_type_id');
        $this->db->join('business','business.id_business = service_category.business_id');
        $this->db->where('service_category.service_category_active', 'Yes');       
        $Query1 = $this->db->get('service_category');
        $d1=$Query1->result_array();
        
        $this->db->select('id_package_category id_service_category, package_type_id service_type_id, service_type, package_category.order_id, service_category, package_category.business_id, business_name, service_category_active, concat("assets/images/category/", ifnull(service_category_image, "nu.png")) as service_category_image, \'packagetype\' flag', false);
        $this->db->join('package_type','package_type.id_package_type = package_category.package_type_id');
        $this->db->join('business','business.id_business = package_category.business_id');
        $this->db->where('package_category.service_category_active', 'Yes');        
        $Query2 = $this->db->get('package_category');
        $d2=$Query2->result_array();
        
        $data=[];
        $data= array_merge($d1, $d2);
        return $data;
    }

    ///////////////////////////////////////////////


     ///FEED BACK FUNCTIONS/////
     public function invoice_details_get(){

        $invoice_id = $this->input->get('invoice_id');

        $sql = " SELECT
        invoice.invoice_seq,
        id_invoice,
        visit_id,
        invoice_type,
        invoice.customer_name,
        invoice.customer_cell,
        invoice.customer_id,
        invoice_d.staff_id,
        invoice_d.staff_name AS staff,
        reference_invoice_number,
        returnamount,
        CONCAT(
            invoice_d.service_type,
            ' ',
            invoice_d.service_category,
            ' ',
            invoice_d.service_name
        ) AS service,
        invoice_d.service_name,
        invoice_d.service_id,
        invoice_d.service_type,
        invoice_d.service_category,
        invoice.discount AS 'invoice_discount',
        invoice.service_addition as invoice_addition,
        invoice.payment_mode,
        paid_amount,
        sub_total,
        other_charges,
        gross_amount AS gross,
        total_payable AS gross_amount,
        retained_amount,
        invoice.balance,
        invoice.advance_amount,
        cctip,
        tax_total,
        cc_charge,
        invoice_d.id_invoice_details,
        invoice_d.price + invoice_d.service_addition price,
        invoice_d.paid AS paid_details,
        invoice_d.service_addition,
        invoice_d.discount,
        paid_amount,
        paid_cash,
        paid_card,
        paid_voucher,
        paid_check,
        CONCAT(
            invoice_products.brand_name,
            ' ',
            invoice_products.product_name,
            ' x ',
            invoice_products.invoice_qty
        ) product_name,
        invoice_qty,
        invoice_products.price product_price,
        invoice_products.discount discounted_price,
        invoice_products.service_addition product_addition,
        invoice_products.staff_name product_staff,
        invoice_products.discount product_discount,
        
        feedback_status,
        invoice_status,
        DATE_FORMAT(invoice_date, '%d-%c-%Y') AS invoice_date,
        DATE_FORMAT(invoice_date, '%H:%i') AS invoice_time,
        case when ifnull(customer_visits.inservice_time,'')!='' then DATE_FORMAT(customer_visits.inservice_time, '%H:%i') else 'N/A' end AS inservice_time,
        case when invoice.invoice_type='service' then DATE_FORMAT(detail_visit_date, '%H:%i') else  'N/A' end  AS visit_time,        
        case when invoice.invoice_type='service' then DATE_FORMAT(detail_visit_date, '%d-%c-%Y') else  'N/A' end  AS visit_date,
        case when invoice.invoice_type='service' then DATE_FORMAT(detail_visit_date, '%d-%c-%Y') else  'N/A' end  AS visit_date,
        retained_amount_used,
        invoice.created_by
        FROM invoice
        LEFT join customer_visits on invoice.visit_id = customer_visits.id_customer_visits
        LEFT JOIN (select invoice_details.*, invoice_staff.staff_id, invoice_staff.staff_name 
           FROM invoice_details
           JOIN invoice_staff ON invoice_staff.invoice_detail_id = invoice_details.id_invoice_details
           JOIN invoice on invoice.id_invoice = invoice_details.invoice_id
           WHERE 1=1 ";
    
       
        $sql .=" ) as invoice_d 
            ON invoice_d.invoice_id = invoice.id_invoice        
            LEFT JOIN invoice_products on invoice_products.invoice_id = invoice.id_invoice ";
        
        $sql .=" Where invoice.invoice_status ='valid' ";
        $sql .=" AND ifnull(reference_invoice_number,'') ='' ";
        $sql .=" AND id_invoice = ".$invoice_id." ";
        
       // echo $sql; exit();
        $query = $this->db->query($sql);
        
        $r = $query->result_array();
        $this->response($r); 

     }
     


    public function insertfeedback_post(){ 

        
        $entityBody = file_get_contents('php://input');
        //$entityBody = stream_get_contents(STDIN);
        
        $data = json_decode($entityBody);
        
        //get customer and business id
        $sql = "select invoice.customer_id, invoice.business_id, invoice.visit_id from invoice where id_invoice =". $data->invoice_id;
        $q = $this->db->query($sql);
        $ids = $q->row();
        
        $invoice_id = $data->invoice_id;
        $visit_id = $ids->visit_id;
        $customer_id = $ids->customer_id;
        $business_id = $ids->business_id;

        $insertdata=array(
            'customer_id'=>$customer_id,
            'invoice_id'=>$invoice_id,
            'visit_id'=>$visit_id,
            'business_id'=>$business_id,
            'created_on'=> date('Y-m-d H:i:s'),
            'qos'=> $data->qos,
            'atmosphere'=>$data->atmosphere,
            'experience'=>$data->experience,
            'valueformoney'=>$data->valueformoney,
            'recommendable'=>$data->recommendable,
            'comment'=>$data->comment,
            'feedback_type'=>$data->feedback_type
        );
        
     //   var_dump($data); exit();
         
        $feedbackid = $this->feedback_model->insert_feedback($insertdata);
        
        $servicedetails = $data->servicedetails;
        
        $index=0;
        foreach($servicedetails as $sid){
           
            $servicedata=array(
                'invoice_detail_id'=>$sid->invoice_detail_id,
                'feedback_id'=> $feedbackid,
                'service_id'=>$sid->service_id,
                'service_type'=>$sid->service_type,
                'service_category'=>$sid->service_category,
                'service_name'=>$sid->service_name,
                'staff'=>$sid->staff,
                'staff_id'=>$sid->staff_id,                
                'expectation'=> $sid->expectation,                
                'skill'=>  $sid->skill,
                'knowledge'=> $sid->knowledge,
                'hospitality'=> $sid->hospitality,
                
                'information_provided'=> $sid->information_provided,
                'satisfaction'=> $sid->satisfaction,
                'comments'=>$sid->comments
            );
            
            $this->feedback_model->insert_details($servicedata);
            
            $index++;
        }
        
        $this->invoice_model->update_feedback($data->invoice_id, 'entered');


        $response = "😀 Thank you for providing us with your Valuable Feedback.\n We are always trying to improve our services and your opinion matters the most!💖\n";
        echo $response;

    }
    

    function wa_data_get(){


        $this->db->select('*');
         
        $this->db->join('user_roles', 'user_roles.user_id = users.id_users');
        $this->db->join('roles', 'user_roles.role_id = roles.id_roles');
        $this->db->where('users.business_id', $this->session->userdata('businessid'));
        $this->db->where('roles.role_name', 'Admin');
        $query = $this->db->get_compiled_select('users');
        echo $query; exit();


        $businessid = $this->input->get('businessid');

        // $sql = "select id_wa, invoice.customer_name, concat('+92', substr(invoice.customer_cell, 2, length(invoice.customer_cell)-1)) as receiver, invoice_id, 
        //         concat(replace(text_msg,'\\n', '\n'),  wa_msg_list.receipt_url) as wa_message
        //         from wa_msg_list 
        //         join invoice on invoice.id_invoice = wa_msg_list.invoice_id
        //         where sent_status = 'Pending' and wa_msg_list.business_id = ".$businessid;

        $sql = "select id_wa, wa_msg_list.receiver, wa_msg_list.invoice_id, 
        concat(replace(text_msg,'\\n', '\n'),  wa_msg_list.receipt_url) as wa_message
        from wa_msg_list 
        where sent_status = 'Pending' and wa_msg_list.business_id = ".$businessid;

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

        $r = $query->result_array();

        $my_array = [];
        
        foreach($r as $data){
            $my_array[] = $data['id_wa'];
        }

        // if(sizeof($my_array) > 0){
        
        //   $this->db->where_in('id_wa', $my_array);
        //   $this->db->update('wa_msg_list', array('sent_status'=>'Sent', 'sent_on'=>date('Y-m-d H:i:s')));
            
        // }
        $this->response($r);
    }


    function wa_mark_sent_get(){

        $wa_id = $this->input->get('wa_id');
        if($wa_id == null){
            $r = array(
                'Error' => 'No ID Passed'
            );
            $this->response($r);
            exit();
        }

        $this->db->where('id_wa', $wa_id);
        $this->db->update('wa_msg_list', array('sent_status'=>'Sent', 'sent_on'=>date('Y-m-d H:i:s')));

        $r = array(
            'Success' => 'Marked as Sent'
        );

        $this->response($r);

    }

}


