<?php

class Sh_model extends CI_Model {

    function __construct() {

        // Call the Model constructor
        parent::__construct();
    }
///dashboard///
    function get_business_sale_year_month($month, $year){
        
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('month', $month);
        $this->db->where('year', $year);
        $query = $this->db->get('sh_business_sales');
        
        return $query->row();
        
    }
    function get_this_month_year_sale($start, $end) {
        
        $this->db->select('SUM(paid_amount) as total_sale');
        $this->db->where('year(invoice_date) = date_format(\''.$start.'\',\'%Y\')');
        $this->db->where('month(invoice_date) = date_format(\''.$start.'\',\'%m\')');
       // $this->db->where("reference_invoice_number <>","bad debts");
        $this->db->where('invoice_status', 'valid');
        $this->db->where('invoice_seq >', 0);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        //$this->db->group_by('invoice_date');
        $query = $this->db->get('invoice');
      

        return $query->row();
    }
    
    function add_this_month_year_sale($data){
        $this->db->insert('sh_business_sales', $data);
        return $this->db->insert_id();
    }
    function get_business_sale_years(){
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->group_by('year');
        $query = $this->db->get('sh_business_sales');
        return $query->result();
    }
    
    function get_business_sales($year){        
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('year', $year);
        $query = $this->db->get('sh_business_sales');
        
        return $query->result();
    }
    
    
    function get_workweek(){
        $today=date('Y-m-d'); 
        $sql = "select date_format(day, '%a %D') day, customers 'Customers', services 'Services',
        ifnull(paid_amount,0) 'Revenue', ifnull(balance,0) 'Balance', 
	 ifnull(paid_amount,0)
        from
        (SELECT '".$today."' AS day
           UNION SELECT '".$today."' - INTERVAL 1 DAY
           UNION SELECT '".$today."' - INTERVAL 2 DAY
           UNION SELECT '".$today."' - INTERVAL 3 DAY
           UNION SELECT '".$today."' - INTERVAL 4 DAY
           UNION SELECT '".$today."' - INTERVAL 5 DAY
           UNION SELECT '".$today."' - INTERVAL 6 DAY
        ) as week
        left join (
                select date_format(invoice_date, '%Y-%m-%d') invoice_date, count(customer_name) as customers,
				ifnull(sum(paid_amount),0) paid_amount, ifnull(sum(balance),0) as balance
                from invoice as inv
                where invoice_status = 'valid'
                and invoice_seq > 0 
                and business_id = ". $this->session->userdata('businessid')." 
                group by date_format(invoice_date, '%Y-%m-%d') 		
            ) as invoice on date_format(invoice.invoice_date, '%Y-%m-%d') = week.day 
        left join (
                select date_format(invoice_detail_date, '%Y-%m-%d') as invoice_detail_date,
				count(service_name) as services 
				from invoice_details
				join invoice on invoice.id_invoice = invoice_details.invoice_id 
                where invoice.business_id = ". $this->session->userdata('businessid')." 
                    and invoice_seq > 0 
                group by date_format(invoice_detail_date, '%Y-%m-%d')
            ) as invoice_d on date_format(invoice_detail_date, '%Y-%m-%d') = week.day 
        
        
        
        group by day";
        //echo $sql;
        $query = $this->db->query($sql);        
        
        return $query->result_array();
    }
    
    function get_workmonth(){
        $today=date('Y-m-d'); 
        $sql = "select date_format(day, '%a %D') day, customers 'Customers', services 'Services',
        ifnull(paid_amount,0) 'Revenue', ifnull(balance,0) 'Balance', 
		ifnull(paid_amount,0)
        from
        (SELECT '".$today."' AS day
           UNION SELECT '".$today."' - INTERVAL 1 DAY
           UNION SELECT '".$today."' - INTERVAL 2 DAY
           UNION SELECT '".$today."' - INTERVAL 3 DAY
           UNION SELECT '".$today."' - INTERVAL 4 DAY
           UNION SELECT '".$today."' - INTERVAL 5 DAY
           UNION SELECT '".$today."' - INTERVAL 6 DAY
           UNION SELECT '".$today."' - INTERVAL 7 DAY
           UNION SELECT '".$today."' - INTERVAL 8 DAY
           UNION SELECT '".$today."' - INTERVAL 9 DAY
           UNION SELECT '".$today."' - INTERVAL 10 DAY
           UNION SELECT '".$today."' - INTERVAL 11 DAY
           UNION SELECT '".$today."' - INTERVAL 12 DAY
           UNION SELECT '".$today."' - INTERVAL 13 DAY
           UNION SELECT '".$today."' - INTERVAL 14 DAY
           UNION SELECT '".$today."' - INTERVAL 15 DAY
           UNION SELECT '".$today."' - INTERVAL 16 DAY
           UNION SELECT '".$today."' - INTERVAL 17 DAY
           UNION SELECT '".$today."' - INTERVAL 18 DAY
           UNION SELECT '".$today."' - INTERVAL 19 DAY
           UNION SELECT '".$today."' - INTERVAL 20 DAY
           UNION SELECT '".$today."' - INTERVAL 21 DAY
           UNION SELECT '".$today."' - INTERVAL 22 DAY
           UNION SELECT '".$today."' - INTERVAL 23 DAY
           UNION SELECT '".$today."' - INTERVAL 24 DAY
           UNION SELECT '".$today."' - INTERVAL 25 DAY
           UNION SELECT '".$today."' - INTERVAL 26 DAY
           UNION SELECT '".$today."' - INTERVAL 27 DAY
           UNION SELECT '".$today."' - INTERVAL 28 DAY
           UNION SELECT '".$today."' - INTERVAL 29 DAY
           UNION SELECT '".$today."' - INTERVAL 30 DAY    
        ) as week
        left join (
                select date_format(invoice_date, '%Y-%m-%d') invoice_date, count(customer_name) 'customers',
                ifnull(sum(paid_amount),0) paid_amount, ifnull(sum(balance),0) as balance
                from invoice 
                where invoice_status = 'valid'
                and invoice_seq > 0 
                and business_id = ". $this->session->userdata('businessid')." 
                group by date_format(invoice_date, '%Y-%m-%d') 		
            ) as invoice on date_format(invoice.invoice_date, '%Y-%m-%d') = week.day 
        left join (
                select date_format(invoice_detail_date, '%Y-%m-%d') as invoice_detail_date, 
				count(service_name) 'services'
				from invoice_details
				join invoice on invoice.id_invoice=invoice_details.invoice_id
                where invoice.business_id = ". $this->session->userdata('businessid')." 
				and invoice_seq > 0 
                group by date_format(invoice_detail_date, '%Y-%m-%d')
            ) as invoice_d on date_format(invoice_detail_date, '%Y-%m-%d') = week.day 
        
      
        group by day ";
        //echo $sql;
        $query = $this->db->query($sql);        
        
        return $query->result_array();
    }
    
    function get_todaysale() {
        $today = date('Y-m-d');
        $yesterday= date('Y-m-d', strtotime('yesterday'));
        $tommorrow= date('Y-m-d', strtotime('tommorrow'));
        
       
        $sql="SELECT Date_Format(invoice_date, '%Y-%m-%d') 'saleon', 
            sum(paid_amount) as 'Total'
            FROM invoice 
            
            WHERE invoice_date >= '".$today."' 
            AND invoice_status = 'valid' 
            and invoice_seq > 0 
            AND invoice.business_id = '".$this->session->userdata('businessid')."' 
            GROUP BY Date_Format(invoice_date, '%Y-%m-%d') 
            ORDER BY Date_Format(invoice_date, '%Y-%m-%d')";
       
        $query =$this->db->query($sql);
        
        return $query->result_array();
    }
    
    function get_yesterdaysale() {
        $today = date('Y-m-d');
        $yesterday= date('Y-m-d', strtotime('yesterday'));
        $tommorrow= date('Y-m-d', strtotime('tommorrow'));
        
        $this->db->select('Date_Format(invoice_date, "%Y-%m-%d") "saleon",  sum(total_payable) as "Total"');
        $this->db->where('invoice_date >=', $yesterday);
        $this->db->where('invoice_date <=', $today);
        $this->db->where('invoice_status', 'valid');
        $this->db->where('invoice_seq >', 0);
       // $this->db->where("reference_invoice_number <>","bad debts");
        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->group_by('Date_Format(invoice_date, "%Y-%m-%d")');
        $this->db->order_by('Date_Format(invoice_date, "%Y-%m-%d")');
        $query = $this->db->get('invoice');
       
        return $query->result_array();
    }
    
     ///month queries
    
    function m_invoice($month, $year){
       
        
        $today = date('Y-m-d');
        
//        $this->db->select("date_format(invoice_date, '%M') as 'Month', ifnull(sum(paid_amount),0) as 'Total'",false);
//        $this->db->where('month(invoice_date) = ',$month);
//        $this->db->where('year(invoice_date) = ',$year);
//        $this->db->where('invoice_status', 'valid');
//        $this->db->where('invoice_seq >', 0);
//        //$this->db->where('reference_invoice_number <>', 'bad debts');
//        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
//        
//        $query = $this->db->get('invoice');
       
        $sql="select date_format(invoice_date, '%M') Month, date_format(invoice_date, '%Y') Year, sum(invoice.other_charges) as 'Other Charges',
            sum(ifnull(service.service_price,0)) Services, round(sum(ifnull(service.service_price,0))*(10/100)) as 'ServiceTax', 
            sum(ifnull(product.retail_price,0)) Retail, round(sum(ifnull(product.retail_price,0))*(10/100)) as 'RetailTax',
            sum(ifnull(service.service_price,0)) + sum(ifnull(product.retail_price,0))  as 'TotalSale',
            sum(ifnull(recoveries.recoveries,0)) 'Recovery'
            FROM `invoice` 
            LEFT Join (
                SELECT id_invoice, ifnull(invoice_details.price,0) 'service_price'
                FROM `invoice` 
                JOIN invoice_details on invoice_details.invoice_id=invoice.id_invoice
                WHERE `invoice_status` = 'valid'
                AND `invoice`.`business_id` = '".$this->session->userdata('businessid')."' 
                AND month(`invoice_date`) = '".$month."'
                AND year(`invoice_date`) = '".$year."'
                AND invoice.invoice_seq > 0
                AND invoice_type='service'
                and ifnull(reference_invoice_number,'')=''

                ) as service on service.id_invoice = invoice.id_invoice
            LEFT Join (
                SELECT id_invoice, ifnull(invoice_products.price,0) 'retail_price'
                FROM `invoice` 
                JOIN invoice_products on invoice_products.invoice_id=invoice.id_invoice
                WHERE `invoice_status` = 'valid'
                AND `invoice`.`business_id` = '".$this->session->userdata('businessid')."' 
                 AND month(`invoice_date`) = '".$month."'
                AND year(`invoice_date`) = '".$year."' 
                AND invoice.invoice_seq > 0
                AND invoice_type='sale'
                and ifnull(reference_invoice_number,'')=''

                ) as product on product.id_invoice=invoice.id_invoice

            LEFT Join (
                SELECT id_invoice, ifnull(invoice.paid_amount,0) 'recoveries'
                FROM `invoice`    
                WHERE `invoice_status` = 'valid'
                AND `invoice`.`business_id` = '".$this->session->userdata('businessid')."' 
                 AND month(`invoice_date`) = '".$month."'
                AND year(`invoice_date`) = '".$year."'
                AND invoice.invoice_seq > 0
                and ifnull(reference_invoice_number,'') <> ''

                ) as recoveries on recoveries.id_invoice=invoice.id_invoice



            WHERE `invoice_status` = 'valid'
            AND `invoice`.`business_id` = '".$this->session->userdata('businessid')."' 
            AND month(`invoice_date`) = '".$month."'
                AND year(`invoice_date`) = '".$year."'
            AND invoice.invoice_seq > 0
            GROUP BY date_format(invoice_date, '%M'), date_format(invoice_date, '%Y')";
        
        
      
        $query =$this->db->query($sql);
        return $query->result_array();
        
    }

     function get_year(){
        $today = date('Y-m-d');
        
        $sql="SELECT year(invoice_date) as 'Year', sum(paid_amount) as 'Total' 
                
                FROM invoice 
               
                
                WHERE year(invoice_date) = year('".$today."') 
                AND invoice_status = 'valid' 
                AND invoice_seq > 0
                AND invoice.payment_mode != 'Voucher'
                
                AND invoice.business_id = '".$this->session->userdata('businessid')."' 
                   
                GROUP BY year(invoice_date)";
        //echo $sql; exit();
        $query =$this->db->query($sql);
        return $query->result_array();
    }
    
    
     function get_month_receiving($month, $year){
        $today = date('Y-m-d');
        
        $sql="SELECT date_format(invoice_date, '%M') Month, sum(total_payable)-sum(tax_total) as 'Total'                 
                FROM invoice 
                WHERE month(invoice_date) = '".$month."'
                AND year(invoice_date)='".$year."'
                AND invoice_status = 'valid' 
                AND ifnull(reference_invoice_number,'') = ''
                AND invoice_seq > 0
                AND invoice.payment_mode != 'Voucher'
                
                AND invoice.business_id = '".$this->session->userdata('businessid')."' 
                   
                GROUP BY month(invoice_date)";
        //echo $sql; exit();
        $query =$this->db->query($sql);
        return $query->result_array();
    }
    
    
     function get_monthly(){
        $today = date('Y-m-d');
        
        $this->db->select("date_format(invoice_date, '%M') as 'Month', sum(paid_amount) as 'Total' ");
        $this->db->where('year(invoice_date) =  date_format(\''.$today.'\',\'%Y\')');
       // $this->db->where("reference_invoice_number <>","bad debts");
        $this->db->where('invoice_status', 'valid');
        $this->db->where('invoice_seq >', 0);
        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->group_by("date_format(invoice_date,'%M')");
        $this->db->order_by("date_format(invoice_date,'%M')");
        $query = $this->db->get('invoice');
        
         return $query->result_array();
    }
    
     function get_daily(){
        $today = date('Y-m-d');
        $this->db->select("date_format(invoice_date, '%d') as 'Day', sum(paid_amount) as 'Total' ");
        $this->db->where('year(invoice_date) =  date_format(\''.$today.'\',\'%Y\')');
        $this->db->where('month(invoice_date) =  date_format(\''.$today.'\',\'%m\')');
       // $this->db->where("reference_invoice_number <>","bad debts");
        $this->db->where('invoice_status', 'valid');
        $this->db->where('invoice_seq >', 0);
        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->group_by("date_format(invoice_date,'%d')");
        $this->db->order_by("date_format(invoice_date,'%d')");
        $query = $this->db->get('invoice');
        
         return $query->result_array();
    }
    
    function get_month_commission(){
         $today = date('Y-m-d');
        $this->db->select("date_format(staff_service_date, '%M') as 'Month', 
        date_format(staff_service_date, '%Y') as 'Year',
        sum(staff_commission) as 'Commission'");
        $this->db->join("invoice", " invoice.id_invoice = staff_services.invoice_id");
        $this->db->join("staff", "staff.id_staff = staff_services.staff_id");
      //  $this->db->where("reference_invoice_number <>","bad debts");
        $this->db->where('invoice_type', 'service');
        $this->db->where('invoice_status', 'valid');
        $this->db->where('invoice_seq >', 0);
        $this->db->where('staff_services.business_id', $this->session->userdata('businessid'));
        $this->db->where('year(invoice_date) =  date_format(\''.$today.'\',\'%Y\')');
        $this->db->where('month(invoice_date) =  date_format(\''.$today.'\',\'%m\')');
        $this->db->group_by("date_format(staff_service_date, '%M'), date_format(staff_service_date, '%Y')");
        $this->db->order_by("3 desc");
        $query = $this->db->get('staff_services');
        
        
        
        return $query->result_array();
        
    }
    
    function top_4_staff(){
        
        $today = date('Y-m-d');
        $month=date('m', strtotime($today));
        $year=date('Y', strtotime($today));
        
        
                $sql="SELECT staff.id_staff, 
                staff.staff_fullname Staff, 
                staff.staff_image, 
                count(id_invoice_staff)  as 'Services', 
                format(sum(paid), 2) as 'Paid', 
                ifnull(a.Recovery,0) 'Recovery', 
                format(ifnull(sum(paid) + ifnull(a.total,0),0),2) as 'Amount',
                ifnull(sum(invoice_details.paid) + ifnull(a.total,0),0)
                FROM invoice_staff 
                Join invoice_details on invoice_details.id_invoice_details=invoice_staff.invoice_detail_id
                JOIN invoice ON invoice.id_invoice = `invoice_staff`.`invoice_id` 
                JOIN staff ON staff.id_staff = invoice_staff.staff_id 
                left join (
                        SELECT id_staff, format(sum(ifnull(invoice_details.paid,0)), 2) as 'Recovery', 
                        sum(ifnull(invoice_details.paid,0)) as 'total',
                        count(id_invoice_staff) as 'rec_count'
                        FROM `invoice_staff` 
                        Join invoice_details on invoice_details.id_invoice_details=invoice_staff.invoice_detail_id
                        JOIN `invoice` ON `invoice`.`id_invoice` = `invoice_staff`.`invoice_id` 
                        JOIN staff ON staff.id_staff = invoice_staff.staff_id 
                        WHERE month(invoice_date) = '".$month."' AND year(invoice_date) = '".$year."' 
                       
                        AND ifnull(reference_invoice_number,'') != '' 
                        AND `invoice_type` = 'service' 
                        AND `invoice_status` = 'valid' 
                        AND `invoice_seq` >0 
                        AND invoice.business_id= ".$this->session->userdata('businessid')."
                        GROUP BY id_staff, staff_name, staff_image
                ) as a on a.id_staff = staff.id_staff
                WHERE month(invoice_date) = '".$month."' AND year(invoice_date) = '".$year."' 
               
                AND ifnull(reference_invoice_number,'') = '' 
                AND invoice_type = 'service' 
                AND invoice_status = 'valid' 
                AND invoice_seq > 0 
                AND invoice.business_id=".$this->session->userdata('businessid')."
                GROUP BY invoice_staff.staff_id, staff.staff_image
                ORDER BY 8 desc";
        
                
        $query = $this->db->query($sql);
        
        return $query->result_array();
        
    }
    
    function top_4_clients(){
        $today = date('Y-m-d');
        $months=[];
        $years=[];
        $dp=new DatePeriod(date_create(),DateInterval::createFromDateString('last month'),2);
        foreach($dp as $dt) {
            array_push($months, $dt->format("m"));
            array_push($years, $dt->format("Y"));
            
        }


        $this->db->select("customer_name, customer_cell, customer_email, CONCAT('".CURRENCY_CODE.". ', FORMAT(sum(paid_amount), 2)) as 'Total', customer_id", True);
        $this->db->where("invoice_status='valid'");
        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->where_in('month(invoice_date)',$months);
        //$this->db->where("reference_invoice_number <>","bad debts");
        //$this->db->where('invoice_type', 'service');
        $this->db->where('invoice_status', 'valid');
        $this->db->where('invoice_seq >' , 0);
        $this->db->where_in('year(invoice_date)',$years);
        $this->db->group_by("customer_name, customer_cell, customer_email");
        $this->db->order_by("sum(paid_amount) desc");
        $this->db->limit(20); 
        $query = $this->db->get('invoice');

       
        return $query->result_array();

    }
    
    function grossing_services(){
        $today = date('Y-m-d');
        $month=date('m', strtotime($today));
        $year=date('Y', strtotime($today));
        
        $sql="select invoice_details.service_category as 'name', sum(paid)/T.total*100 as 'y' , sum(paid) 'share', T.total as 'paid'
                from invoice_details 
                join invoice on invoice.id_invoice = invoice_details.invoice_id 
                and invoice.invoice_status = 'valid'
                and invoice.invoice_seq >0 
                and  month(invoice_detail_date) = '".$month."'
                and  year(invoice_detail_date) = '".$year."'
                and reference_invoice_number=''     
                and service_category is not null 
                and invoice_details.business_id= ".$this->session->userdata('businessid').",
                (
                    select sum(subtotal) as 'total' 
                    from 
                        (
                        SELECT service_category, sum(paid) as subtotal 
                        FROM invoice_details
                        join invoice on invoice.id_invoice = invoice_details.invoice_id 
                        and invoice.invoice_status = 'valid'
                        and invoice.invoice_seq >0 
                        and  month(invoice_detail_date) = '".$month."'
                        and  year(invoice_detail_date) = '".$year."'                       
                        and reference_invoice_number=''    
                         and service_category is not null
                        and invoice_details.business_id= ".$this->session->userdata('businessid')."                       
                        order by 2 desc
                        
                        ) as M
                    ) as T
                group by service_category
                order by 2 desc
                
                ";
       
        $query = $this->db->query($sql);        
        
        return $query->result_array();
        
    }
    
    /////Dashboard//////
    
    
    function invoices($startdate,  $sh=false) {

       // $date = strtotime("+ 1 days", strtotime($enddate));
       //  $enddate = date("Y-m-d", $date);

        $this->db->select('*,DATE_FORMAT(invoice_date, "%d-%m-%Y") as invoice_date');
       // $this->db->join('discount_invoice_users', 'discount_invoice_users.invoiceid = invoice.id_invoice', 'left');
        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->where('date(invoice_date) =', $startdate." ");
       
        //$this->db->where('reference_invoice_number <>', 'bad debts');
        $this->db->where('invoice.invoice_status=', 'valid');
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('invoice_seq > ', 0);
        } 
        $this->db->order_by('invoice_seq', 'DESC');
        $query = $this->db->get('invoice');
        //echo $query;exit();
        
        return $query->result_array();
    }
    
    function generate_seq($invoiceid, $today){
        $seq=0;
        $sql = "select max(invoice_seq)+1 as 'seq', payment_mode 
            from invoice where day(invoice_date)= day('".$today."') 
            and month(invoice_date)= month('".$today."') and year(invoice_date)= year('".$today."')";
        $query = $this->db->query($sql);
        $invoice_seq =  $query->row();
        
        if(isset($invoice_seq) && null !== $invoice_seq->seq){$seq=$invoice_seq->seq;}
        
        //get the visit_id
        $this->db->select('id_invoice, visit_id');
        $this->db->where('id_invoice', $invoiceid);
        $query=$this->db->get('invoice');
        $visit_id =  $query->row();
        
        $update_invoice = array(          
            'invoice_seq' => $seq
        );            
        $this->db->where(array(
            'business_id' => $this->session->userdata('businessid'),
            'id_invoice' => $invoiceid
        ));
        $this->db->update('invoice', $update_invoice);
        
        //update customer visit
        $this->db->set('invoice_seq', $seq);
        $this->db->where('id_customer_visits', $visit_id->visit_id);
        $this->db->update('customer_visits');
        
    }
    
    function remove_seq($invoiceid, $today){
        
        ///get the invoice_seq of selected invoice
        $this->db->select('invoice_seq, visit_id');
        $this->db->where('id_invoice', $invoiceid);
        $query=$this->db->get('invoice');
        $invoice_seq =  $query->row();
        $seq=$invoice_seq->invoice_seq;
        
        //get all invoices with greater seq numbers
        $sql="select id_invoice, visit_id from invoice where 
            day(invoice_date)= day('".$today."') 
            and month(invoice_date)= month('".$today."') and year(invoice_date)= year('".$today."')
            and invoice_seq > ".$invoice_seq->invoice_seq ." order by id_invoice;";
        $query = $this->db->query($sql);
        
        $greater_invoices =  $query->result_array();
        
      
        ///set selected invoice to 0
        $update_invoice = array(          
            'invoice_seq' => 0
        );            
        $this->db->where(array(
            'business_id' => $this->session->userdata('businessid'),
            'id_invoice' => $invoiceid
        ));
        $this->db->update('invoice', $update_invoice);
        
         //update customer visit
            $this->db->set('invoice_seq', 0);
            $this->db->where('id_customer_visits', $invoice_seq->visit_id);
            $this->db->update('customer_visits');
            
        //resequence greater invoices
        
        foreach($greater_invoices as $invoice){
            
            $update_invoice = array(          
                'invoice_seq' => $seq
            );            
            $this->db->where(array(
                'business_id' => $this->session->userdata('businessid'),
                'id_invoice' => $invoice['id_invoice']
            ));
            $this->db->update('invoice', $update_invoice);
            
            //update the visit
            //update customer visit
            $this->db->set('invoice_seq', $seq);
            $this->db->where('id_customer_visits', $invoice['visit_id']);
            $this->db->update('customer_visits');
            
            $seq++;
        }
        
    }
    
    function monthstotalservice($date){
        $date = strtotime($date);
        
        $month= date("m",$date);
         $year= date("Y",$date);
         
       $sql="select month(invoice_date) month, year(invoice_date) year, round(sum(ifnull(total_payable,0)),2) as total_payable 
               from  invoice 
               where month(invoice_date)= '".$month."' 
               and year(invoice_date)= '".$year."'
               and invoice.invoice_seq >0
               and invoice_status = 'valid'
               and invoice_type = 'service'
               and business_id= ".$this->session->userdata('businessid')."  
               group by month(invoice_date), year(invoice_date)";
              
         $query = $this->db->query($sql);        
        
        return $query->result_array();
    }
    function monthstotalsale($date){
        $date = strtotime($date);
        
        $month= date("m",$date);
         $year= date("Y",$date);
         
       $sql="select month(invoice_date) month, year(invoice_date) year, round(sum(ifnull(total_payable,0)),2) as total_payable 
               from  invoice 
               where month(invoice_date)= '".$month."' 
               and year(invoice_date)= '".$year."'
               and invoice.invoice_seq >0
               and invoice_status = 'valid'
               and invoice_type = 'sale'
               and business_id= ".$this->session->userdata('businessid')."  
               group by month(invoice_date), year(invoice_date)";
              
         $query = $this->db->query($sql);        
        
        return $query->result_array();
    }
    
    function resequence_day($tabledata, $today){
        
        $seq=1;
        
        //update all invoices removing seq numbers for selected day
        $this->db->set('invoice_seq', '0');
        $this->db->where("day(invoice_date)", "day('.$today.')", false);
        $this->db->where("month(invoice_date)", "month('.$today.')", false);
        $this->db->where("year(invoice_date)", "year('.$today.')", false);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->update('invoice');
        
        
        
        //get all invoices of the day
        $sql="select id_invoice, visit_id from invoice where 
            day(invoice_date)= day('".$today."') 
            and month(invoice_date)= month('".$today."') and year(invoice_date)= year('".$today."')
            order by id_invoice;";
        $query = $this->db->query($sql);
        $today_invoices =  $query->result_array();

        
        usort($tabledata, function($a, $b) {
            return $a['invoice_id'] <=> $b['invoice_id'];
        });
        
        //resequence days invoices        
        foreach($tabledata as $row){
            
            if($row["check"]=='true'){
                $this->db->set('invoice_seq', $seq);                 
            } else {
                $this->db->set('invoice_seq', '0');         
            }
            $this->db->where('business_id', $this->session->userdata('businessid'));
            $this->db->where('id_invoice', $row['invoice_id']);
            $this->db->update('invoice');
            
            //update the visit
            //update customer visit
            if($row["check"]=='true'){
                $this->db->set('invoice_seq', $seq);                 
            } else {
                $this->db->set('invoice_seq', '0');         
            }
            $this->db->where('id_customer_visits', $row['visit_id']);
            $this->db->update('customer_visits');            
            
            if($row["check"]=='true'){$seq++;}
        }
        
        
    }   
    
    
    function sequenced_report($month, $year){
        
        $sql = "SELECT 
                *, DATE_FORMAT(invoice_date, '%d-%m-%Y') AS invoice_date
            FROM
                `invoice`       
            WHERE
                `invoice`.`business_id` = '1'
                    and month(invoice.invoice_date)='".$month."'
                    and year(invoice.invoice_date)='".$year."'
                    AND `invoice`.`invoice_status` = 'valid'
                    AND ifnull(invoice.invoice_seq,0) > 0 
            ORDER BY date(invoice_date), invoice_seq";
        
        $query = $this->db->query($sql);
        $invoices =  $query->result_array();
        
        return $query->result_array();
    }
    
}