<?php

class Customer_model extends CI_Model {

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

        if ($this->session->userdata('role') == '') {
            redirect('logout');
        }
    }

    function get_customer($match) {

        $this->db->select('*, id_customers as "id", "" as "customer_cell"');
        //$this->db->from('customers');
        $array = array('customer_name' => $match, 'customer_cell' => $match, 'customer_phone1' => $match, 'customer_card' => $match);
        $this->db->or_like($array);
        //$this->db->where('business_id', $this->session->userdata('businessid'));

        $query = $this->db->get('customers');
        
        return $query->result_array();
    }
    
    function get_customer_withcell($match) {

        $this->db->select('*, id_customers as "id"');
        //$this->db->from('customers');
        $array = array('customer_name' => $match, 'customer_cell' => $match, 'customer_phone1' => $match, 'customer_card' => $match);
        $this->db->or_like($array);
        //$this->db->where('business_id', $this->session->userdata('businessid'));

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

    function get_byid($match) {
        
        if( $this->session->userdata('hide_cell') && $this->session->userdata('hide_cell') == "Yes"){
            $sql="select *, '' as 'customer_cell' ";
        } else {
            $sql="select * ";
        }
        $sql .= "
            from customers 
            left join ( 
                    select customer_id, ifnull(sum(loyalty_earned),0) 'earned', ifnull(sum(loyalty_used),0) 'used' ,
                    sum(ifnull(loyalty_earned,0)) - sum(ifnull(loyalty_used,0)) as 'customer_loyalty_points' 
                    from invoice 
                    where invoice_status='valid' 
                    group by customer_id 
            ) as a on a.customer_id = customers.id_customers 
            where 
             id_customers=".$match.";"; 
      
        $query=$this->db->query($sql);
        
        return $query->result_array();
    }
    
    function update_customer_info($id, $info){
        
        $this->db->where('id_customers', $id);
        $this->db->update('customers', $info);
    }
    
    function get_byname($match) {
        
        $this->db->select('*');
        $this->db->like('customer_name', $match);
        //$this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customers');

        return $query->result_array();
    }
     function get_bynameco($match) {
        
        $this->db->select('*, customer_name as "id"');
        $this->db->like('customer_name', $match);
        //$this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customers');

        return $query->result_array();
    }

    function get_bycell($match) {
        
        $this->db->select('*');
        $this->db->like('customer_cell', $match);
        //$this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customers');

        return $query->result_array();
    }
    
    function get_bycard($match) {
        
        $this->db->select('*');
        $this->db->like('customer_card', $match);
        //$this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customers');
        
        return $query->result_array();
    }

    function get_byemail($match) {
        
        $this->db->select('*');
        $this->db->like('customer_email', $match);
        //$this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customers');

        return $query->result_array();
    }

    function add_new_customer() {
        
        $data = array(
            'business_id' => $this->session->userdata('businessid'),
            'customer_name' => $this->input->post('txt-customer-name', TRUE),
            'customer_email' => $this->input->post('txt-customer-email', TRUE),
            'customer_cell' => $this->input->post('txt-customer-cell', TRUE),
            //'customer_gender' => $this->input->post('txt-customer-gender', TRUE),
            'customer_address' => $this->input->post('txt-customer-address', TRUE),
            'customer_birthday' => $this->input->post('txt-customer-bday', TRUE),
            'customer_birthmonth' => $this->input->post('txt-customer-bmonth', TRUE),
            'profession' => $this->input->post('txt-customer-profession', TRUE),
            'customer_careof' =>$this->input->post('txt-customer-co', TRUE),
            'customer_gender' =>$this->input->post('txt-customer-gender', TRUE),
            'referencing_staff' =>$this->input->post('txt-customer-refstaff', TRUE),
            'created_by' => $this->session->userdata('username')
        );

        if($this->db->field_exists('customer_area','customers')){ 
            
            $data['customer_area'] = $this->input->post('txt-customer-area', TRUE);                    
        }
        
        $this->db->insert('customers', $data);
        return $this->db->insert_id();
    }

    function update_customer() {
        
        $customerid = $this->input->post('detail-customer-id');

        //$phpdate = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$this->input->post('detail-customer-wedding'))));
        $phpdate = strtotime($this->input->post('detail-customer-wedding'));
        $mysqldate = date('Y-m-d', $phpdate);
        if( null!==$this->session->userdata('hide_cell') && $this->session->userdata('hide_cell') == "Yes"){
            $data = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_name' => $this->input->post('detail-customer-name', TRUE),
                'customer_email' => $this->input->post('detail-customer-email', TRUE),
               
                'customer_phone1' => $this->input->post('detail-customer-phone1', TRUE),
                'customer_phone2' => $this->input->post('detail-customer-phone2', TRUE),
                'customer_address' => $this->input->post('detail-customer-address', TRUE),
                'customer_birthday' => $this->input->post('detail-customer-bday', TRUE),
                'customer_birthmonth' => $this->input->post('detail-customer-bmonth', TRUE),
                'customer_anniversary' => $mysqldate,
                'customer_allergies' => $this->input->post('detail-customer-allergies', TRUE),
                'customer_alert' => $this->input->post('detail-customer-alert', TRUE),
                'profession' => $this->input->post('detail-customer-profession', TRUE),
                'referencing_staff' => $this->input->post('detail-customer-refstaff', TRUE),
                
                'customer_careof' => $this->input->post('detail-customer-careof', TRUE),
                'customer_gender' => $this->input->post('detail-customer-gender', TRUE),
                'customer_card' => $this->input->post('detail-customer-card', TRUE),
                'customer_type' => $this->input->post('detail-customer-type', TRUE)

            );
        } else {
            $data = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_name' => $this->input->post('detail-customer-name', TRUE),
                'customer_email' => $this->input->post('detail-customer-email', TRUE),
                'customer_cell' => $this->input->post('detail-customer-cell', TRUE),
                'customer_phone1' => $this->input->post('detail-customer-phone1', TRUE),
                'customer_phone2' => $this->input->post('detail-customer-phone2', TRUE),
                'customer_address' => $this->input->post('detail-customer-address', TRUE),
                'customer_birthday' => $this->input->post('detail-customer-bday', TRUE),
                'customer_birthmonth' => $this->input->post('detail-customer-bmonth', TRUE),
                'customer_anniversary' => $mysqldate,
                'customer_allergies' => $this->input->post('detail-customer-allergies', TRUE),
                'customer_alert' => $this->input->post('detail-customer-alert', TRUE),
                'profession' => $this->input->post('detail-customer-profession', TRUE),
                'referencing_staff' => $this->input->post('detail-customer-refstaff', TRUE),
                'customer_careof' => $this->input->post('detail-customer-careof', TRUE),
                'customer_gender' => $this->input->post('detail-customer-gender', TRUE),
                'customer_card' => $this->input->post('detail-customer-card', TRUE),
                'customer_type' => $this->input->post('detail-customer-type', TRUE)

            );
        }
        
         if($this->db->field_exists('customer_area','customers')){ 
            
            $data['customer_area'] = $this->input->post('detail-customer-area', TRUE);                    
        }
        
        $this->db->where('id_customers', $customerid);
        $this->db->update('customers', $data);

        return $customerid;
    }

    //make a list of customer for current session business...in list view file...
    function get_customers() {
        
        $this->db->select('*');
        //$this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customers');

        return $query->result_array();
    }

    function get_customers_birthday_today() {
        
        
        $day = ltrim(date('d'), '0');
        $month = date('F');
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('customer_birthday', $day);
        $this->db->where('customer_birthmonth', $month);
        $query = $this->db->get('customers');
        return $query->result();
    }

    function get_customers_birthday_tomorrow() {
        
        $tomorrow = date('d', strtotime('tomorrow'));
        $tomorrow = ltrim($tomorrow, '0');
        $month = date('F');
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('customer_birthday', $tomorrow);
        $this->db->where('customer_birthmonth', $month);
        $query = $this->db->get('customers');
        return $query->result();
    }

    //Customer add function by modal..in list view file
    function add_new_customer_by_list() {
        
        $phpdate = strtotime($this->input->post('customer_anniversary'));
        $mysqldate = date('Y-m-d', $phpdate);

        $data = array(
            'business_id' => $this->session->userdata('businessid'),
            'customer_name' => $this->input->post('customer_name', TRUE),
            'customer_email' => $this->input->post('customer_email', TRUE),
            'customer_cell' => $this->input->post('customer_cell', TRUE),
            'customer_gender' => $this->input->post('customer_gender', TRUE),
            'customer_phone1' => $this->input->post('customer_phone1', TRUE),
            'customer_phone2' => $this->input->post('customer_phone2', TRUE),
            'customer_card' => $this->input->post('customer_card', TRUE),
            'customer_address' => $this->input->post('customer_address', TRUE),
            'customer_birthday' => $this->input->post('customer_birthday', TRUE),
            'customer_birthmonth' => $this->input->post('customer_birthmonth', TRUE),
            'customer_anniversary' => $mysqldate,
            'customer_allergies' => $this->input->post('customer_allergies', TRUE),
            'customer_alert' => $this->input->post('customer_alert', TRUE),
            'customer_type' => $this->input->post('customer_type', TRUE),
            'profession' => $this->input->post('profession', TRUE),
            'customer_careof' => $this->input->post('customer_careof', TRUE),
            'created_by' => $this->session->userdata('username')
        );

        $this->db->insert('customers', $data);
        return $this->db->insert_id();
    }

    //Customer update by modal function...in list view file...
    function update_customer_by_list() {
        
        $customerid = $this->input->post('id_customer');

        //$phpdate = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$this->input->post('detail-customer-wedding'))));
        $phpdate = strtotime($this->input->post('customer_anniversary'));
        $mysqldate = date('Y-m-d', $phpdate);
        if( null!==$this->session->userdata('hide_cell') && $this->session->userdata('hide_cell') == "Yes"){
            $data = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_name' => $this->input->post('customer_name', TRUE),
                'customer_email' => $this->input->post('customer_email', TRUE),               
                'customer_gender' => $this->input->post('customer_gender', TRUE),
                'customer_phone1' => $this->input->post('customer_phone1', TRUE),
                'customer_phone2' => $this->input->post('customer_phone2', TRUE),
                'customer_card' => $this->input->post('customer_card', TRUE),
                'customer_address' => $this->input->post('customer_address', TRUE),
                'customer_birthday' => $this->input->post('customer_birthday', TRUE),
                'customer_birthmonth' => $this->input->post('customer_birthmonth', TRUE),
                'customer_anniversary' => $mysqldate,
                'customer_allergies' => $this->input->post('customer_allergies', TRUE),
                'customer_alert' => $this->input->post('customer_alert', TRUE),
                'customer_type' => $this->input->post('customer_type', TRUE),
                'profession' => $this->input->post('profession', TRUE),
                'referencing_staff' => $this->input->post('referencing_staff', TRUE),
                'customer_careof' => $this->input->post('customer_careof', TRUE)
            );
            
        }else{
            $data = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_name' => $this->input->post('customer_name', TRUE),
                'customer_email' => $this->input->post('customer_email', TRUE),
                'customer_cell' => $this->input->post('customer_cell', TRUE),
                'customer_gender' => $this->input->post('customer_gender', TRUE),
                'customer_phone1' => $this->input->post('customer_phone1', TRUE),
                'customer_phone2' => $this->input->post('customer_phone2', TRUE),
                'customer_card' => $this->input->post('customer_card', TRUE),
                'customer_address' => $this->input->post('customer_address', TRUE),
                'customer_birthday' => $this->input->post('customer_birthday', TRUE),
                'customer_birthmonth' => $this->input->post('customer_birthmonth', TRUE),
                'customer_anniversary' => $mysqldate,
                'customer_allergies' => $this->input->post('customer_allergies', TRUE),
                'customer_alert' => $this->input->post('customer_alert', TRUE),
                'customer_type' => $this->input->post('customer_type', TRUE),
                'profession' => $this->input->post('profession', TRUE),
                'referencing_staff' => $this->input->post('referencing_staff', TRUE),
                'customer_careof' => $this->input->post('customer_careof', TRUE)
            );
        }
        // print_r($customerid);die;
        $this->db->where('id_customers', $customerid);
        $this->db->update('customers', $data);

        
        if ($this->db->field_exists('allowed_balance', 'customers')) {
            $this->db->set('allowed_balance', $this->input->post('allowed_balance'));
            $this->db->where('id_customers', $customerid);
            $this->db->update('customers');
        }
        
        return $customerid;
    }

    function customer_history($idcustomer, $sh=false) {
        
        $this->db->select('i.id_invoice,date_format(i.invoice_date,"%d-%m-%Y") as invoice_date,date_format(i.invoice_date,"%a") as day,i.customer_name,i.customer_cell,ind.service_category,ind.service_name,ind.products,ind.staff');
        $this->db->join('invoice_details ind', 'ind.invoice_id = i.id_invoice');
        $this->db->where('i.customer_id', $idcustomer);
        $this->db->where('i.invoice_status', 'valid');
        //$this->db->where('i.business_id', $this->session->userdata('businessid'));
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
             $this->db->where('i.invoice_seq >', 0);
        }
        
        $this->db->order_by('i.id_invoice', 'DESC');
        $query = $this->db->get('invoice i');

        return $query->result_array();
    }

    //Previous visit.....work start............
    function customer_visit_count($idcustomer, $sh=false){
        
        $this->db->select('count(*) count',False);
        $this->db->join('invoice', 'cv.id_customer_visits = invoice.visit_id');
        $this->db->where('cv.customer_id', $idcustomer);
        $this->db->where('cv.visit_status', 'invoiced');
         $this->db->where('invoice.invoice_status', 'valid');
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
             $this->db->where('invoice.invoice_seq >', 0);
        }
        $query = $this->db->get('customer_visits cv');
        
        return $query->row();
    }
    
    function customer_all_visits($idcustomer, $limit=0, $sh=false) {
        
        $this->db->select("cv.*, id_invoice, visit_services.id_visit_services, business_name, id_business,
            group_concat(concat('- ', visit_services.service_name, ' ', visit_services.service_id, ' ', visit_service_staffs.staff_name) order by visit_services.service_id SEPARATOR '<br>') service_name,
            DATE_FORMAT(visit_service_start, '%d-%m-%Y') AS customer_visit_date,
            DATEDIFF(NOW(), visit_service_start) AS daysago", False);
        $this->db->join("visit_services", "visit_services.customer_visit_id=cv.id_customer_visits and visit_services.visit_service_status='Active'");
        $this->db->join("visit_service_staffs", "visit_services.id_visit_services = visit_service_staffs.visit_service_id");
        $this->db->join('invoice', "cv.id_customer_visits = invoice.visit_id and invoice.invoice_status = 'valid' and ifnull(reference_invoice_number,'') = ''", false);
        $this->db->join('business', 'cv.business_id = business.id_business');        
        $this->db->where('cv.customer_id', $idcustomer);
        $this->db->where('cv.visit_status', 'invoiced');
        $this->db->where('invoice.invoice_status', 'valid');
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
             $this->db->where('invoice.invoice_seq >', 0);
        }
        $this->db->group_by('id_customer_visits');
        $this->db->order_by('date(visit_service_start)', 'Desc');
        if($limit >0){
            $this->db->limit($limit);
        }
       // $this->db->where('cv.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customer_visits cv');
        //echo $query; exit();
        return $query->result_array();

        //print_r($visit_ids);die;
    }

    function customer_visit_services($visit_ids) {
        if ($visit_ids) {
            
            $this->db->select('*');
            $this->db->join('business_services','business_services.id_business_services = vs.service_id');
            $this->db->where('vs.service_flag', 'servicetype');
            $this->db->where('vs.visit_service_status', 'Active');
            $this->db->where_in('vs.customer_visit_id', $visit_ids);
            
            //$this->db->where('vs.business_id', $this->session->userdata('businessid'));
             
            $query = $this->db->get('visit_services vs');

            return $query->result_array();
        }
    }

    function get_visit_staff($visit_ids) {
        if ($visit_ids) {
            $this->db->distinct('ss.staff_id');
            $this->db->select('s.staff_fullname, vst.customer_visit_id as visit_id, vst.staff_id, bs.service_name, service_category, service_type');
            $this->db->join("visit_services vs", "vs.id_visit_services = vst.visit_service_id and vs.visit_service_status='Active'");
            $this->db->join('customer_visits cv', 'cv.id_customer_visits = vst.customer_visit_id');
            $this->db->join('staff s', 'vst.staff_id = s.id_staff');
            $this->db->join('business_services bs', 'vs.service_id = bs.id_business_services');
            $this->db->join('service_category sc', 'bs.service_category_id = sc.id_service_category');
            $this->db->join('service_type st', 'st.id_service_types = sc.service_type_id');
            $this->db->where_in('vst.customer_visit_id', $visit_ids);
            $this->db->where_in('vs.service_flag', 'servicetype');
            //$this->db->where('vst.business_id', $this->session->userdata('businessid'));
            $this->db->where('cv.visit_status !=', 'canceled');
            
            $subQuery1 = $this->db->get_compiled_select('visit_service_staffs vst');
            
            $this->db->distinct('ss.staff_id');
            $this->db->select('s.staff_fullname, vst.customer_visit_id as visit_id, vst.staff_id, bs.service_name, service_category, service_type');
            $this->db->join("visit_services vs", "vs.id_visit_services = vst.visit_service_id and vs.visit_service_status='Active'");
            $this->db->join('customer_visits cv', 'cv.id_customer_visits = vst.customer_visit_id');
            $this->db->join('staff s', 'vst.staff_id = s.id_staff');
            $this->db->join('package_services ps', 'vs.service_id = ps.service_id and vs.id_service_category = ps.package_category_id');
            $this->db->join('package_category pc', 'pc.id_package_category = ps.package_category_id');            
            $this->db->join('package_type st', 'st.id_package_type = pc.package_type_id');
            $this->db->join('business_services bs', 'vs.service_id = bs.id_business_services');
            $this->db->where_in('vst.customer_visit_id', $visit_ids);
            $this->db->where_in('vs.service_flag', 'packagetype');
            //$this->db->where('vst.business_id', $this->session->userdata('businessid'));
            $this->db->where('cv.visit_status !=', 'canceled');      
            
            $subQuery2 = $this->db->get_compiled_select('visit_service_staffs vst');
        //echo $subQuery2; exit();
            $query = $this->db->query("select * from (".$subQuery1." UNION ".$subQuery2.") as unionTable");
        
            
            
            return $query->result_array();
        }
    }

    function get_visit_product($visit_ids) {
        if ($visit_ids) {
            $this->db->distinct();
            $this->db->select('vsp.visit_service_id,vsp.customer_visit_id,vsp.product_id,vsp.product_name');
            $this->db->where_in('vsp.customer_visit_id', $visit_ids);
            //$this->db->where('vsp.business_id', $this->session->userdata('businessid'));

            $query = $this->db->get('visit_service_products vsp');

            return $query->result_array();
        }
    }

    function customer_invoice_count($idcustomer, $sh=false){
        
        $this->db->select('count(*) count');
        $this->db->where('invoice.customer_id', $idcustomer);
        $this->db->where('invoice.invoice_status', 'valid');
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('invoice.invoice_seq >', 0);
        }
        $query = $this->db->get('invoice');
        return $query->row();
    }
    
    function get_invoice_visit($idcustomer, $limit=0, $sh=false) {
        
        if ($idcustomer) {
            //$this->db->distinct();
            $this->db->select('*,date_format(invoice_date,"%d-%m-%Y") as invoice_date, visit_id as visit_date');
            $this->db->where('invoice.customer_id', $idcustomer);
            $this->db->where('invoice.invoice_status', 'valid');
            $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
            if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                 $this->db->where('invoice.invoice_seq >', 0);
            }
            $this->db->order_by('date(invoice_date)', 'Desc');
            if($limit>0){
                $this->db->limit($limit);
            }
            
            $query = $this->db->get('invoice');

            return $query->result_array();
        }
    }

    function get_customer_openvisit($idcustomer) {
        
        if($idcustomer == null || $idcustomer == ''){
            exit();
        }
        $this->db->select('*');
        $this->db->where('cv.customer_id', $idcustomer);
        $this->db->where('cv.visit_status', 'open');
        $this->db->where('cv.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customer_visits cv');

        return $query->result_array();
    }

    //Previous visit.....work end............

    function customerbalance($customerid, $sh=false) {
        
        //if ($customerid) {
            //$this->db->distinct();
            $this->db->select('ifnull(balance,0) as totalbalance, id_invoice, visit_id, invoice_type',false);
            $this->db->where('customer_id', $customerid);
            $this->db->where('balance >', 0);
            $this->db->where('is_recovery', 'Yes');
            $this->db->where('invoice_status', 'valid');
            if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                $this->db->where('invoice_seq >', 0);
            }
           // $this->db->where('business_id', $this->session->userdata('businessid'));
           // $this->db->group_by('id_invoice, visit_id, invoice_type');
            $query = $this->db->get('invoice');

            return $query->result_array();
        //}
    }
    
    function customerenrollment($customerid){
        
        $this->db->select('id_program_enrollment');
        $this->db->where('customer_id', $customerid);
        $query = $this->db->get('program_enrollment');

        return $query->row();
    }
    
    function get_customer_alerts($customerid){
        
            $this->db->select('id_customers, customer_allergies, customer_alert',false);
            $this->db->where('id_customers', $customerid);
//            $this->db->where('business_id', $this->session->userdata('businessid'));
            $query = $this->db->get('customers');

            return $query->result_array();        
        
    }
    
    
    function customer_exist($customername = NULL, $customercell = NULL) {
        
        if ($customername !== NULL && $customercell !== NULL) {
            $query = $this->db->query("SELECT customer_name, customer_cell FROM customers WHERE  customer_name LIKE '%$customername%' AND customer_cell = $customercell");

            $result = $query->row();
            if (isset($result->customer_name) && isset($result->customer_cell)) {
                return "name " . $result->customer_name;
                die;
            } else {
                $query = $this->db->query("SELECT customer_name, customer_cell FROM customers WHERE  customer_cell = $customercell");
                $result = $query->row();
                if (isset($result->customer_cell)) {
                    return "cell " . $result->customer_cell;
                    die;
                } else {
                    return "false";
                }
            }
        }
    }
    
    function customer_update_exist($customer_id, $customername = NULL, $customercell = NULL) {
        
        if ($customer_id && $customername !== NULL && $customercell !== NULL) {
            $query = $this->db->query("SELECT id_customers, customer_name, customer_cell FROM customers WHERE customer_name LIKE '%$customername%' AND customer_cell = $customercell AND id_customers != $customer_id");

            $result = $query->result();
            if (isset($result[0]->customer_name) && isset($result[0]->customer_cell)) {
                echo "name " . $result[0]->customer_name;
                die;
            } else {
                $query = $this->db->query("SELECT id_customers, customer_name, customer_cell FROM customers WHERE customer_cell = $customercell  AND id_customers != $customer_id");
                $result = $query->result();
                if (isset($result[0]->customer_cell)) {
                    echo "cell " . $result[0]->customer_cell;
                    die;
                } else {
                    return "false";
                }
            }
        }
    }
    
    function edit_customers(){
        
        $this->db->select('*');
        
        $this->db->where('c.id_customers', $this->input->post('id_customers'));
        $query = $this->db->get('customers c');

        return $query->row();
    }
    
    function CheckCustomer_Exist($customername = NULL, $customercell = NULL) {
        
        if ($customername !== NULL && $customercell !== NULL) {
            $query = $this->db->query("SELECT id_customers, customer_name, customer_cell FROM customers WHERE customer_name = '$customername' AND customer_cell = $customercell");

            $result = $query->row();
            if (isset($result->customer_name) && isset($result->customer_cell)) {
                return "name " . strtolower($result->customer_name);
                die;
            } else {
                $query = $this->db->query("SELECT id_customers, customer_name, customer_cell FROM  customers WHERE customer_cell = $customercell");
                $result = $query->row();
                if (isset($result->customer_cell)) {
                    return "cell " . $result->customer_cell;
                    die;
                } else {
                    return "false";
                }
            }
        }
    }
    
    function get_customer_loyalty($customer_id, $sh=false){
        
        if(null == $customer_id || $customer_id=='' ){
            exit();
        }
        
        
        //get loyalty
        $this->db->select("id_customers as customer_id, customers.customer_name, customers.customer_cell, customers.customer_type, round(sum(ifnull(loyalty_earned,0)),2) 'earned', round(sum(ifnull(loyalty_used,0)),2) 'used', round(sum(ifnull(loyalty_earned,0)) - sum(ifnull(loyalty_used,0)),2) 'loyalty_points', 0 'retained'");
         if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
             $this->db->join('invoice','invoice.customer_id = customers.id_customers and invoice_status="valid" and invoice.invoice_seq > 0', 'left') ; 
        } else {
             $this->db->join('invoice','invoice.customer_id = customers.id_customers and invoice_status="valid"', 'left') ;
        }               
        $this->db->where("id_customers =", $customer_id);        
        $this->db->group_by('id_customers');
        $query2 = $this->db->get('customers');       
        
        $loyalty=$query2->row();
        
        //get loyalty from vouchers (new feature)
        $loyalty_ah = "0";
        //check if business has common products
        if(defined('LOYALTY_VOUCHER')){                    
            if(LOYALTY_VOUCHER==TRUE){ 
                if($this->session->userdata('common_products')=='Yes'){
                    $sqlb="select id_business from business where business.ho='Yes'";
                    $b=$this->db->query($sqlb);
                    
                    if($b->num_rows() > 0){
                        $ho=$b->row();

                        $sql="select account_head_id from account_event_mapping where entity_name = 'loyalty_amount' and account_event_id = 1 and business_id = ".$ho->id_business."";
                        $q=$this->db->query($sql);
                        
                        $ah_result=$q->row();
                        if($ah_result){
                            $loyalty_ah = $ah_result->account_head_id;
                        }
                    } else {
                        $sql="select account_head_id from account_event_mapping where entity_name = 'loyalty_amount' and account_event_id = 1 and business_id = ".$this->session->userdata('businessid')."";
                        $q=$this->db->query($sql);
                        $ah_result=$q->row();
                        if($ah_result){
                            $loyalty_ah = $ah_result->account_head_id;
                        }
                    }
                } else{
                    $sql="select account_head_id from account_event_mapping where entity_name = 'loyalty_amount' and account_event_id = 1 and business_id = ".$this->session->userdata('businessid')."";
                    $q=$this->db->query($sql);
                    $ah_result=$q->row();
                    if($ah_result){
                        $loyalty_ah = $ah_result->account_head_id;
                    }
                }
                if(null !=$loyalty_ah && $loyalty_ah!='' && $loyalty_ah > 0){
                    $sql="select id_customers as customer_id, customer_name, customer_cell, customer_type, 0 as earned, 0 as used, round(ifnull(sum(credit)-sum(debit),0),2) as loyalty_points, 0 as 'retained'        
                            from customers           
                            left join  
                            (select business_partner_id, debit, credit from
                                account_vouchers 			
                                join account_voucher_detail on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
                                where account_voucher_detail.account_head_id = ".$loyalty_ah."  
                                and business_partner = 1 
                                and account_vouchers.voucher_status= 'Active'
                            ) as account_vouchers on customers.id_customers = account_vouchers.business_partner_id 
                            where id_customers=".$customer_id." 
                            group by id_customers, customer_name, customer_cell, customer_type";
                    $queryloyalty = $this->db->query($sql);
                    $loyaltyfromaccountvouchers=$queryloyalty->row();
                }else {
                    $loyaltyfromaccountvouchers=0;
                }
            }
        }
        //echo $sql; exit();

        //get retained from invoices
        $this->db->select("id_customers as customer_id, customers.customer_name, customers.customer_cell, customers.customer_type, 0 'earned', 0 'used', 0 'loyalty_points', sum(ifnull(retained_amount,0)) - sum(ifnull(retained_amount_used,0)) 'retained'");
         if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
             $this->db->join('invoice','invoice.customer_id = customers.id_customers and invoice_status="valid" and invoice.invoice_seq > 0 and invoice.business_id = '.$this->session->userdata("businessid").'  AND id_invoice not in (select invoice_id from account_vouchers where business_partner_id ="'.$customer_id.'") ', 'left') ;
        } else {
             $this->db->join('invoice','invoice.customer_id = customers.id_customers and invoice_status="valid" and invoice.business_id = '.$this->session->userdata("businessid").'   AND id_invoice not in (select invoice_id from account_vouchers where business_partner_id ="'.$customer_id.'") ', 'left') ;
        }
               
        $this->db->where("id_customers =", $customer_id);
      
        $this->db->group_by('id_customers');
        $query = $this->db->get('customers');
        //echo $query; exit();
        $frominvoices=$query->row();
        
        
        //get retained from vouchers
        $account_head_id=0;
        $sql="select account_head_id from account_event_mapping where entity_name = 'retained_amount' and business_id = ".$this->session->userdata('businessid')."";
        $q=$this->db->query($sql);
        $ah=$q->row();
        
        if($ah){
            $account_head_id=$ah->account_head_id;
        }
        
        $sql="select id_customers as customer_id, customer_name, customer_cell, customer_type, 0 as earned, 
                0 as used, 0 as loyalty_points,
                ifnull(sum(credit)-sum(debit),0) as 'retained' 
                            from customers           
                left join  
                    (select business_partner_id, debit, credit from
                    account_vouchers 			
                    join account_voucher_detail on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
                    where account_voucher_detail.account_head_id = ".$account_head_id." 
                    and business_partner = 1 
                    and account_vouchers.voucher_status= 'Active'
                ) as account_vouchers on customers.id_customers = account_vouchers.business_partner_id 
                
                
                where id_customers=".$customer_id." 
                group by id_customers, customer_name, customer_cell, customer_type";
        
        $query1 = $this->db->query($sql);
        $fromaccountvouchers=$query1->row();
        $resultset = [];

        $totalloyalty=0;
        if(defined('LOYALTY_VOUCHER')){                    
            if(LOYALTY_VOUCHER==TRUE){ 
                $totalloyalty = $loyaltyfromaccountvouchers->loyalty_points;
            }else {
                $totalloyalty = $loyalty->loyalty_points;
            }
        }else{
            $totalloyalty = $loyalty->loyalty_points;
        }
            
        $resultset1 = array(
            'customer_id' => $frominvoices->customer_id,
            'customer_name' => $frominvoices->customer_name,
            'customer_cell' => $frominvoices->customer_cell,
            'customer_type' => $frominvoices->customer_type,
            'earned' => $loyalty->earned,
            'used'=> $loyalty->used,
           // 'loyalty_points'=> $loyalty->loyalty_points + $loyaltyfromaccountvouchers->loyalty_points,
           //'loyalty_points'=> $loyalty->loyalty_points, 
           'loyalty_points'=> $totalloyalty,            
            'retained'=> $frominvoices->retained + $fromaccountvouchers->retained            
        );
        array_push($resultset, $resultset1);
        //print_r($resultset); exit();
        return $resultset;
    }

    function get_other_branch_retained($customer_id, $sh=false){

        
        if(null == $customer_id || $customer_id=='' ){
            exit();
        }
        
        $fromaccountvouchers= array();
        //get retained from vouchers

        $sql="select * from business where common_products = 'Yes'";
        $query = $this->db->query($sql);
        $businesses = $query->result_array();

        foreach ($businesses as $business){
            $account_head_id=0;

            $sql="select  account_head_id from account_event_mapping where entity_name = 
            'retained_amount' and business_id = ".$business['id_business']." 
            group by business_id
            ";

            $q=$this->db->query($sql);
            $ah=$q->row();
        
            if($ah){
                $account_head_id=$ah->account_head_id;
            }
            $sql="select id_business, business_name, id_customers as customer_id,
                ifnull(sum(credit)-sum(debit),0) as 'retained' 
                from customers           
                left join  
                    (select id_business, business_name,  business_partner_id, debit, credit from
                    account_vouchers 			
                    join account_voucher_detail on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
                    join business on business.id_business = account_vouchers.business_id
                    where account_voucher_detail.account_head_id = ".$account_head_id." 
                    and business_partner = 1 and business_partner_id=".$customer_id." 
                    and account_vouchers.voucher_status= 'Active'
                ) as account_vouchers on customers.id_customers = account_vouchers.business_partner_id                 
                where id_customers=".$customer_id." 
                group by id_business, id_customers, customer_name, customer_cell, customer_type";
                

            $query1 = $this->db->query($sql);
            $fromaccountvouchers[]=$query1->row();
        }

        //print_r($fromaccountvouchers); exit();
        return $fromaccountvouchers;
    }

    function general_search($name='', $cell='', $card=''){
        
        //echo $cell; exit();
        if( $this->session->userdata('hide_cell') && $this->session->userdata('hide_cell') == "Yes"){
            $sql="select *, '' as 'customer_cell', 0 as program_enrollment_id ";
        } else {
            $sql="select *, 0 as program_enrollment_id ";
        }
        $sql .= "
            from customers 

            
            where customers.id_customers > 0 ";
        
//            left join ( 
//                    select customer_id, ifnull(sum(loyalty_earned),0) 'earned', ifnull(sum(loyalty_used),0) 'used' ,
//                    sum(ifnull(loyalty_earned,0)) - sum(ifnull(loyalty_used,0)) as 'customer_loyalty_points' 
//                    from invoice 
//                    where invoice_status='valid' group by customer_id 
//            ) as a on a.customer_id = customers.id_customers   
        if($name!==""){
            $sql.=" and customer_name like '%".$name."%' ";
        }
        if($cell!==""){
            $sql.=" and customer_cell like '%".$cell."%' ";
        }
        if($card!==""){
            $sql.=" and customer_card like '%".$card."%' ";
        }
        $sql.=" ;";
        
       //echo $sql; exit();
        
        $query=$this->db->query($sql);
        
        
        return $query->result_array();
        
    }
    
    function checkvariables($variables){
        $result=true;
        foreach($variables as $var){
            if(null == $var && $var == ''){
                $result=false;
            }
        }
        return $result;
    }

    function get_customer_openvisits($customerid){
        
        $sql = "select id_business, business_name, id_customer_visits, group_concat(visit_services.service_name, ' ', visit_service_staffs.staff_name,'<br>') as services,
                date_format(visit_services.visit_service_start, '%d-%m-%Y %H:%i:%s') as visit_date, customer_visits.created_by, 
                ifnull(visit_advance.advance_amount,0) as advance, date_format(convert(replace(visit_service_start,'T',' '),datetime),'%Y-%m-%d') date1
                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 visit_service_staffs on visit_service_staffs.visit_service_id = visit_services.id_visit_services and visit_service_staffs.visit_service_staff_status='Active' 
                left join (
                    select customer_visit_id, sum(advance_amount) as advance_amount 
                    from
                    visit_advance 
                    group by customer_visit_id) as visit_advance
                    on visit_advance.customer_visit_id = customer_visits.id_customer_visits
                join business on business.id_business = customer_visits.business_id
                where customer_visits.visit_status='open'
                and customer_visits.customer_id = " . $customerid . " group by id_customer_visits;";
        
        $query = $this->db->query($sql);
        
        return $query->result_array();
        
    }
    
    function get_city_areas($city_id = null){
        
        $this->db->select('city_areas.*');
        $this->db->join('cities', 'id_cities=city_id');
        $this->db->join('business', 'id_business = cities.business_id');
        
        if($city_id !=null){
            $this->db->where('city_id', $city_id);
        } else if($this->session->userdata('common_products')=='Yes'){
            $this->db->where('business.common_products', 'Yes');
        } else {
            $this->db->where('business.id_business', $this->session->userdata('businessid'));
        }
        
        $query = $this->db->get('city_areas');
        return $query->result_array();
        
    }
    
}
