<?php

class Report_model extends CI_Model {

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

    function allsales($startdate, $enddate, $sh=false) {

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

        $this->db->select("date_format(visit_time, '%d-%m-%Y %H:%i') as 'visit', date_format(invoice_date,'%d-%m-%Y %H:%i') as 'Invoiced', id_invoice as invoice_id, invoice_type as 'Sale Type', sub_total as 'Sub Total', gross_amount as 'Gross', discount as 'Discount', tax_total as 'Taxes', net_amount as 'Net Amount', paid_amount as 'paid', invoice.advance_amount as 'advance', balance, discount_remarks, invoice.customer_name, invoice.reference_invoice_number as 'reference_number', invoice_status, cancelreason");
        //$this->db->join("customer_visits", "customer_visits.id_customer_visits = invoice.visit_id");
        //$this->db->join("visit_services", "customer_visits.id_customer_visits = visit_services.customer_visit_id");
        $this->db->where('invoice_date >=', $startdate.' 00:00');
        $this->db->where('invoice_date <=', $enddate.' 23:59');
        
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('invoice.invoice_seq > ', 0);
        }
        
        //$this->db->where('invoice_status', 'valid');
        //$this->db->where('reference_invoice_number <>', 'bad debts');
        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        //$this->db->group_by('id_invoice');
        $query = $this->db->get('invoice');
        //echo $query; exit();
        return $query->result_array();
    }

    function monthly_sales($startdate, $enddate, $sh=false) {

//    
//        $this->db->select("date_format(invoice_date,'%M') as 'Month', date_format(invoice_date,'%Y') as 'Year', round(sum(sub_total),2) as 'Sub Total', "
//                . "round(sum(gross_amount),2) as 'Gross', round(sum(discount),2) as 'Discount', round(sum(tax_total),2) as 'Taxes', round(sum(net_amount),2) as 'Net Amount', round(sum(paid_amount),2) as 'paid', round(sum(balance),2) as 'balance'");
//        $this->db->join("months","months.month = month(invoice_date)", "left");
//        $this->db->where('invoice_date >=', $startdate." 00:00");
//        $this->db->where('invoice_date <=', $enddate." 23:59");
//        $this->db->where('invoice_status', 'valid');
//        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
//            $this->db->where('invoice.invoice_seq > ', 0);
//        }
//      
//        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
//        $this->db->group_by('1,2');
//
//        $query = $this->db->get('invoice');
//
//        return $query->result_array();
        
        
        $sql="Select 
            date_format(invoice_date,'%M') as 'Month', date_format(invoice_date,'%Y') as 'Year', round(sum(advance_adjusted),2) as 'AdvanceAdj', 
                round(sum(gross_total),2) as 'Gross', round(sum(total_discount),2) as 'Discount', round(sum(tax_total),2) as 'Taxes', 
                round(sum(total_payable),2) as 'Net Amount', round(sum(paid_amount),2) as 'paid', round(sum(balance),2) as 'balance'
                from
            (SELECT id_invoice, invoice_number, invoice_type, payment_mode, 
                invoice_date, invoice.created_by, customer_id, invoice.business_id,
                customer_name, customer_cell,
                    Case When invoice.invoice_type='service'
                        Then sum(invoice_details.price) 
			Else sum(invoice_products.price*invoice_qty) End
				as 'gross_total', 
                    Case When invoice.invoice_type='service'
			Then sum(invoice_details.discount) 
			Else sum(invoice_products.discount) End
				as 'service_discount',
                invoice.discount as 'invoice_discount',
			Case When invoice.invoice_type='service'	
				Then sum(invoice_details.discount)+invoice.discount
				Else sum(invoice_products.discount)+invoice.discount End
				as total_discount,
                sub_total, invoice.advance_amount as advance_adjusted,
                other_charges, tax_total, cc_charge,
                CASE WHEN ifnull(invoice.reference_invoice_number,'') = '' THEN  (total_payable+cc_charge)-advance_amount  
                ELSE (paid_amount + balance)
                END as 'total_payable',
                invoice.paid_cash + invoice.paid_card + invoice.paid_voucher + invoice.paid_check as paid_amount,
                invoice.balance, ";
//                CASE WHEN ifnull(invoice.reference_invoice_number,'') <> '' THEN 'Recovery'
//                ELSE ''
//                END as 'recovery', reference_invoice_number,
        $sql.=" paid_cash, paid_card, paid_voucher, paid_check, cctip, retained_amount, retained_amount_used
                from invoice
                left join invoice_details on invoice_details.invoice_id = invoice.id_invoice 
				left join invoice_products on invoice_products.invoice_id = invoice.id_invoice                 
                where invoice_date >= '".$startdate." 00:00"."'
                and invoice_date <= '".$enddate." 23:59"."'
                and invoice.business_id=".$this->session->userdata('businessid')."
                and invoice_status= 'valid' 
                and ifnull(invoice.reference_invoice_number,'')='' 
                ";
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $sql.=" and invoice_seq >  0 ";
        } 
        $sql.=" group by id_invoice) as a group by 1,2";
        $query=$this->db->query($sql);
        
        
        return $query->result_array();
        
    }

    function monthly_advances($startdate, $enddate, $sh=false) {

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

        $this->db->select("date_format(visit_advance.advance_date,'%M') as 'Month', date_format(visit_advance.advance_date,'%Y') as 'Year', ifnull(sum(visit_advance.advance_amount),0) as 'TotalAdvance'");
       
        $this->db->join("customer_visits", "customer_visits.id_customer_visits = visit_advance.customer_visit_id");
        
        $this->db->where('visit_advance.advance_date >=', $startdate." 00:00");
        $this->db->where('visit_advance.advance_date <=', $enddate." 23:59");
        $this->db->where('customer_visits.visit_status !=', 'canceled');
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('customer_visits.invoice_seq > ', 0);
        }
        //$this->db->where('reference_invoice_number <>', 'bad debts');
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $this->db->group_by('1,2');

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

        return $query->result_array();
    }
    
    function monthly_vouchers($startdate, $enddate, $sh=false) {

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

         $this->db->select("date_format(order_vouchers.voucher_date,'%M') as 'Month', date_format(order_vouchers.voucher_date,'%Y') as 'Year', ifnull(sum(order_vouchers.amount),0) as 'TotalVoucher'");
       
        
        
        $this->db->where('order_vouchers.voucher_date >=', $startdate." 00:00");
        $this->db->where('order_vouchers.voucher_date <=', $enddate." 23:59");
        
       
        $this->db->where('order_vouchers.business_id', $this->session->userdata('businessid'));
        $this->db->group_by('1,2');

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

        return $query->result_array();
    }
    
    function monthly_recoveries($startdate, $enddate, $sh=false) {
        
        $sql="select date_format(invoice.invoice_date,'%M') as 'Month', date_format(invoice.invoice_date,'%Y') as 'Year',
            ifnull(sum(invoice.paid_cash + invoice.paid_card + invoice.paid_voucher + invoice.paid_check),0) as paid_amount
            from invoice
            where invoice_date >= '".$startdate." 00:00"."'
                and invoice_date <= '".$enddate." 23:59"."'
                and invoice.business_id=".$this->session->userdata('businessid')."
                and invoice_status= 'valid' 
                and ifnull(invoice.reference_invoice_number,'') <> '' 
            ";
        $query=$this->db->query($sql);
        
        return $query->result_array();
    }
    
    function product_usage_details($product_id, $startdate, $enddate, $sh=false) {

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

        $this->db->select("inv.id_invoice, bp.category, service_name,  customer_name, product_name, product_qty, product_unit, date_format(invoice_date, '%d-%m-%Y') as 'Date'");
        $this->db->join('invoice_visit_products ivp', 'inv.id_invoice = ivp.invoice_id');
        $this->db->join('business_products bp', 'ivp.product_id = bp.id_business_products');
        $this->db->join('business_brands bb', 'bp.brand_id = bb.id_business_brands');
        $this->db->where('inv.invoice_date >=', $startdate." 00:00");
        $this->db->where('inv.invoice_date <=', $enddate." 23:59");
        $this->db->where('ivp.product_id', $product_id);
        $this->db->where('inv.invoice_status', 'valid');
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('invoice.invoice_seq > ', 0);
        }
        $this->db->where('inv.business_id', $this->session->userdata('businessid'));
        $this->db->where('inv.invoice_type=', 'service');
        $this->db->group_by('ivp.invoice_id');
        $query = $this->db->get('invoice inv');
        return $query->result_array();
    }

    function product_usage_summary($startdate, $enddate, $sh=false) {

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

//        $this->db->select("inv.id_invoice, ivp.product_name, ivp.product_id, count(ivp.product_name) as product_count, sum(ivp.product_qty) as total_qty, ivp.product_unit, bp.unit_type as 'Container Type', bb.business_brand_name, bp.qty_per_unit as Container Qty, (sum(ivp.product_qty) / bp.qty_per_unit) as 'Container Used'");
//        $this->db->join('invoice_visit_products ivp', 'inv.id_invoice = ivp.invoice_id');
//        $this->db->join('business_products bp', 'ivp.product_id = bp.id_business_products');
//        $this->db->join('business_brands bb', 'bp.brand_id = bb.id_business_brands');
//        $this->db->where('inv.invoice_date >=', $startdate);
//        $this->db->where('inv.invoice_date <=', $enddate);
//        $this->db->where('inv.invoice_status', 'valid');
//        $this->db->where('inv.business_id', $this->session->userdata('businessid'));
//        $this->db->where('inv.invoice_type=', 'service');
//        $this->db->group_by('inv.id_invoice, ivp.product_name, ivp.product_id,ivp.product_unit, bp.unit_type , bb.business_brand_name, bp.qty_per_unit ');
//        $query = $this->db->get('invoice inv');
        
        
         $this->db->select("ivp.product_name, ivp.product_id, count(ivp.product_name) as product_count, sum(ivp.product_qty) as total_qty, "
                 . "ivp.product_unit, bp.category, bp.unit_type as 'Container Type', bb.business_brand_name, "
                 . "bp.qty_per_unit as Container Qty, "
                 . "(sum(ivp.product_qty) / bp.qty_per_unit) as 'Container Used'");
        $this->db->join('invoice_visit_products ivp', 'inv.id_invoice = ivp.invoice_id');
        $this->db->join('business_products bp', 'ivp.product_id = bp.id_business_products');
        $this->db->join('business_brands bb', 'bp.brand_id = bb.id_business_brands');
        $this->db->where('inv.invoice_date >=', $startdate." 00:00");
        $this->db->where('inv.invoice_date <=', $enddate." 23:59");
        $this->db->where('inv.invoice_status', 'valid');
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('inv.invoice_seq > ', 0);
        }
        $this->db->where('inv.business_id', $this->session->userdata('businessid'));
        $this->db->where('ifnull(inv.reference_invoice_number,"")=','');
        $this->db->where('inv.invoice_type=', 'service');
        $this->db->group_by('ivp.product_name, ivp.product_id, bb.business_brand_name');
        $query = $this->db->get('invoice inv');
        
        return $query->result_array();
    }

    function category_sales($startdate, $enddate, $sh=false) {
        

        
        $sql = "select  a.service_type, a.service_category, sum(a.price) price, round(sum(a.discount),2) discount, 
            round(sum(invoice.discount),2) invoicediscount,
        round(sum(a.discounted_price),2) discounted_price, sum(a.paid) paid, count(distinct(invoice_id)) services,
        round(sum(invoice.tax_total),2) as tax, round(sum(invoice.cc_charge),2) as cc_charge, round(sum(total_payable),2) total_payable
        from invoice 
        join(
            SELECT invoice_id, service_type, service_category, 
		price as price, discount as discount, 
		discounted_price as discounted_price, paid as paid
		FROM invoice_details
                where convert(invoice_detail_date, date)>='" . $startdate." 00:00" . "' 
                and convert(invoice_detail_date, date)<='" . $enddate." 23:59" . "' 
            ) as a on a.invoice_id = invoice.id_invoice
            where invoice.business_id = " . $this->session->userdata('businessid') . "
            and invoice.invoice_status ='valid' ";
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $sql .= " and invoice.invoice_seq > 0 ";
        }
        $sql .= "    and ifnull(reference_invoice_number,'') = ''
            group by service_type, service_category";
        
        
        
        $query = $this->db->query($sql);

        return $query->result_array();
        
    }
    
    function service_sales($startdate, $enddate, $sh=false) {



//        $sql = "select count(a.invoice_id) as service_count, service_type, service_category, service_name,  sum(a.payable) payable, sum(a.discount) discount, sum(a.paid) paid, sum(a.price) price 
//        from invoice i join
//        (
//        select invoice_id, service_type, 
//        service_category, service_name, sum(price) as 'price',
//        sum(discounted_price) as 'payable', sum(discount) as 'discount', sum(paid) as 'paid'
//        from invoice_details ss 
//        where convert(invoice_detail_date, date)>='" . $startdate." 00:00" . "' 
//        and convert(invoice_detail_date, date)<='" . $enddate." 23:59" . "' 
//        group by invoice_id, service_type, service_category, service_name 
//        ) as a
//        on a.invoice_id=i.id_invoice
//        where i.invoice_status='valid' and ifnull(i.reference_invoice_number,'')='' and 
//        i.business_id = " . $this->session->userdata('businessid') . " ";
        
        
        $sql="SELECT invoice_details.service_type, invoice_details.service_category, invoice_details.service_name, 
            invoice.business_id, count(invoice_details.service_category) service_count,
            sum(invoice_details.price+ invoice_details.service_addition) 'price', sum(advance_amount) advance_adj,
            sum(invoice_details.discount) service_discount,
            round(sum((100*invoice.discount)/invoice.sub_total),2) as invoice_discount_perc,
            round(sum(((invoice_details.price+ invoice_details.service_addition-invoice_details.discount)*((100*invoice.discount)/invoice.sub_total))/100 ),2) invoice_discount,
            round(sum(invoice_details.discount)+sum(((invoice_details.price+ invoice_details.service_addition-invoice_details.discount)*((100*invoice.discount)/invoice.sub_total))/100 ),2) as total_discount,
            sum(invoice_details.price+ invoice_details.service_addition)-round(sum(invoice_details.discount)+sum(((invoice_details.price+ invoice_details.service_addition-invoice_details.discount)*((100*invoice.discount)/invoice.sub_total))/100 ),2)
            as discounted_price,
            sum(invoice_details.discounted_price) as org_discounted_price,
            sum(other_charges) other_charges, 
            sum(invoice_details.service_addition) service_addition, 
            sum(tax_total) tax_total, sum(cc_charge) cc_charge,
            CASE WHEN ifnull(invoice.reference_invoice_number,'') = ''	THEN  (sum(total_payable)+sum(cc_charge))-sum(advance_amount)  
            ELSE (sum(paid_amount) + sum(balance))
            END as 'total_payable', 
            sum(total_payable) org_total_payable,
            sum(invoice_details.paid) as paid_amount,
            sum(invoice.total_payable) as org_total_payable,
            sum(invoice.balance),
            sum(paid_cash), sum(paid_card), sum(paid_voucher), sum(paid_check), sum(cctip),
            sum(invoice.discount) as org_invoice_discount, invoice_details.service_id
            from invoice
            join invoice_details on invoice_details.invoice_id = invoice.id_invoice
            where invoice_date >= '" . $startdate." 00:00" . "'  
            and invoice_date <= '" . $enddate." 23:59" . "' 
            and invoice.business_id= " . $this->session->userdata('businessid') . " 
            and invoice_status= 'valid'
            and invoice_type='service' 
            and ifnull(reference_invoice_number,'') = '' ";
        
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $sql .= " and invoice.invoice_seq > 0 ";
        }
        
        $sql .= " group by service_type, service_category, service_name";
       
    //    echo $sql; exit();
        $query = $this->db->query($sql);

        return $query->result_array();
    }

    function service_sales_dept($startdate, $enddate, $sh=false) {
        
        $sql="SELECT service_department, invoice_details.service_type, invoice_details.service_category, invoice_details.service_name, 
            invoice.business_id, count(invoice_details.service_category) service_count,
            sum(invoice_details.price+ invoice_details.service_addition) 'price', sum(advance_amount) advance_adj,
            sum(invoice_details.discount) service_discount,
            round(sum((100*invoice.discount)/invoice.sub_total),2) as invoice_discount_perc,
            round(sum(((invoice_details.price+ invoice_details.service_addition-invoice_details.discount)*((100*invoice.discount)/invoice.sub_total))/100 ),2) invoice_discount,
            round(sum(invoice_details.discount)+sum(((invoice_details.price+ invoice_details.service_addition-invoice_details.discount)*((100*invoice.discount)/invoice.sub_total))/100 ),2) as total_discount,
            sum(invoice_details.price+ invoice_details.service_addition)-round(sum(invoice_details.discount)+sum(((invoice_details.price+ invoice_details.service_addition-invoice_details.discount)*((100*invoice.discount)/invoice.sub_total))/100 ),2)
            as discounted_price,
            sum(invoice_details.discounted_price) as org_discounted_price,
            sum(other_charges) other_charges, 
            sum(invoice_details.service_addition) service_addition, 
            sum(tax_total) tax_total, sum(cc_charge) cc_charge,
            CASE WHEN ifnull(invoice.reference_invoice_number,'') = ''	THEN  (sum(total_payable)+sum(cc_charge))-sum(advance_amount)  
            ELSE (sum(paid_amount) + sum(balance))
            END as 'total_payable', 
            sum(total_payable) org_total_payable,
            sum(invoice_details.paid) as paid_amount,
            sum(invoice.total_payable) as org_total_payable,
            sum(invoice.balance),
            sum(paid_cash), sum(paid_card), sum(paid_voucher), sum(paid_check), sum(cctip),
            sum(invoice.discount) as org_invoice_discount, invoice_details.service_id
            from invoice
            join invoice_details on invoice_details.invoice_id = invoice.id_invoice
            JOIN business_services on id_business_services=invoice_details.service_id
            where invoice_date >= '" . $startdate." 00:00" . "'  
            and invoice_date <= '" . $enddate." 23:59" . "' 
            and invoice.business_id= " . $this->session->userdata('businessid') . " 
            and invoice_status= 'valid'
            and invoice_type='service' 
            and ifnull(reference_invoice_number,'') = '' ";
        
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $sql .= " and invoice.invoice_seq > 0 ";
        }
        
        $sql .= " group by service_department, service_type, service_category, service_name";
       
        //echo $sql; exit();
        $query = $this->db->query($sql);

        return $query->result_array();
    }
    
    function service_sale_details($startdate, $enddate, $sh=false) {
  
        
        $sql="SELECT id_invoice, id_invoice_details, invoice_number,invoice_type,  
        date_format(visit_time,'%d-%m-%Y %H:%s:%i') as visited, 
        date_format(invoice_date,'%d-%m-%Y') invoiced, 
            invoice_details.service_type, invoice_details.service_category, invoice_details.service_name,
            staff_id, replace(staff_name, '.','') as staff,
            customer_id, invoice.business_id,
            customer_name, customer_cell,
            round(invoice_details.price + invoice_details.service_addition, 2) 'gross_total',
            round(advance_amount,2) advance_amount,
            round(invoice.paid_amount+advance_amount,2) as paid,
            round((100*ifnull(invoice.discount,0))/invoice.sub_total,2) as invoice_discount_percentage,
            round(ifnull(invoice_details.discount,0), 2) service_discount,
            ifnull(round(((ifnull(invoice_details.price,0) + ifnull(invoice_details.service_addition,0) - ifnull(invoice_details.discount,0))*(100* ifnull(invoice.discount,0))/invoice.sub_total)/100 ,2) , 0) as invoice_discount, 
            IFNULL(ROUND(IFNULL(invoice_details.discount, 0) + IFNULL(ROUND(((IFNULL(invoice_details.price, 0) + IFNULL(invoice_details.service_addition, 0) - IFNULL(invoice_details.discount, 0)) * (100 * IFNULL(invoice.discount, 0)) / invoice.sub_total) / 100, 2), 0) , 2), 0) AS total_discount,
            ifnull(round( invoice_details.price + ifnull(invoice_details.service_addition,0) - (ifnull(invoice_details.discount,0) + (((invoice_details.price+ ifnull(invoice_details.service_addition,0) - ifnull(invoice_details.discount,0) )*(100 * ifnull(invoice.discount,0))/invoice.sub_total)/100)) ,2) ,0)
            as discounted_price,
            round(ifnull(invoice_details.service_addition,0),2) as service_addition,
            round(other_charges,2) as other_charges, 
            round(tax_total,2) as tax_total, 
            round(cc_charge,2) as cc_charge,
            CASE WHEN ifnull(invoice.reference_invoice_number,'') = ''	THEN round( (total_payable+cc_charge)-advance_amount  ,2)
            ELSE (round( paid_amount + balance ,2))
            END as 'total_payable', 
            round(invoice.paid_cash + invoice.paid_card + invoice.paid_voucher + invoice.paid_check,2) as paid_amount,
            round(invoice.balance,2),
            CASE WHEN ifnull(invoice.reference_invoice_number,'') <> ''	THEN 'Recovery'
            ELSE ''
            END as 'recovery',
            round(paid_cash,2) paid_cash, paid_card, paid_voucher, paid_check, cctip, 
            reference_invoice_number as reference_number,
            ref_number, additional_staff, invoice_details.service_id
            from invoice
            join invoice_details on invoice_details.invoice_id = invoice.id_invoice
            join business_services on business_services.id_business_services = invoice_details.service_id
            join invoice_staff on invoice_details.id_invoice_details = invoice_staff.invoice_detail_id
            -- join(
            --         select invoice_id, count(id_invoice_details) service_count from invoice_details
            --         group by invoice_id
            -- ) as a on a.invoice_id=invoice.id_invoice
            where date(invoice_date) >= '".$startdate."'
            and date(invoice_date) <= '".$enddate."'
            and invoice.business_id=".$this->session->userdata('businessid')." 
            and invoice_status= 'valid'
            and invoice_type='service' 
            and ifnull(reference_invoice_number,'') = '' 
            ";
            if(null!==$this->input->post('service_type')&&$this->input->post('service_type')!=="All"){
                $sql.=" and invoice_details.service_type like '%". str_replace(' ', '%', $this->input->post('service_type'))."%' ";
            }    
            if(null!==$this->input->post('service_category') && $this->input->post('service_category')!==""){
                if($this->input->post('service_category')!=="All"){
                    $sql.=" and invoice_details.service_category like '%". str_replace(' ', '%', $this->input->post('service_category')) ."%' ";
                }
            } 
            if(null!==$this->input->post('id_business_services') && $this->input->post('id_business_services')>0){
                $sql.=" and invoice_details.service_id=".$this->input->post('id_business_services')." "; 
            }
            if(null!==$this->input->post('staff_id') && $this->input->post('staff_id')>0){
                $sql.=" and staff_name='". $this->input->post('staff_name')."' "; 
            }
        
            if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                $sql .=" and invoice_seq > 0 ";
            }
          // echo $sql; exit();
            
        $query = $this->db->query($sql);
        return $query->result_array();
        
    }

    function staff_performance($startdate, $enddate, $sh=false , $groupon='', $staffid=0) {

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

        $this->db->select("staff_name,"
                . " date_format(invoice_date, '%d-%m-%Y') as 'Date', count(service_name) as service_count, sum(invoice_staff.price) as price,"
                . " sum(invoice_staff.discount+invoice_staff.invoice_discount) as discount_sum, sum(invoice_staff.final_price) as price_sum, "
                . "sum(invoice_staff.paid) as paid");
        if($groupon==''){
            $this->db->select("service_type, service_category, service_name");
        } else {
            $this->db->select($groupon);
        }
        $this->db->join('invoice_staff', 'invoice.id_invoice = invoice_staff.invoice_id');
        $this->db->where('date(invoice_date) >=', $startdate);
        $this->db->where('date(invoice_date) <=', $enddate);
        $this->db->where('invoice_status', 'valid');
         if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('invoice_seq > ', 0);
        }
        
        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        //$this->db->where('reference_invoice_number <>', 'bad debts');
        $this->db->where('ifnull(invoice.reference_invoice_number,"")=""');
        $this->db->where('invoice_type', 'service');
        if($staffid > 0){
            $this->db->where('invoice_staff.staff_id', $staffid);
        }
        if($groupon==''){
            $this->db->order_by('staff_name', 'service_type', 'service_category', 'service_name');
        }else {
            $this->db->order_by($groupon);
        }
        if($groupon==''){
            $this->db->group_by('service_type');
            $this->db->group_by('service_category');
            $this->db->group_by('service_name');
            $this->db->group_by('staff_name');
        }else {
            $this->db->group_by($groupon);
        }
        $query = $this->db->get('invoice');
       
        return $query->result_array();
    }

    function product_sales($startdate, $enddate, $sh=false) {

        
        $sql="SELECT invoice_products.brand_name, 
            CONCAT(invoice_products.product_name, ' ', business_products.qty_per_unit, ' ', business_products.measure_unit) as product_name,
            invoice_products.category, 
            invoice.business_id, sum(invoice_products.invoice_qty) invoice_qty,
            round(avg(invoice_products.price + (invoice_products.service_addition/invoice_qty)),2) 'Price', sum(invoice_qty) as 'Quantity', 
            round(sum((invoice_products.price + (invoice_products.service_addition/invoice_qty))*invoice_qty),2) as total_price,
            sum(advance_amount) advance_adj,
            sum(invoice_products.discount) product_discount,
            round(sum((100*invoice.discount)/invoice.sub_total),2) as invoice_discount_perc,
            round(sum(((((invoice_products.price + invoice_products.service_addition)*invoice_products.invoice_qty)-invoice_products.discount)*((100*invoice.discount)/invoice.sub_total))/100 ),2) invoice_discount,
            sum(invoice_products.discount)+round(sum(((((invoice_products.price+invoice_products.service_addition)*invoice_products.invoice_qty)-invoice_products.discount)*((100*invoice.discount)/invoice.sub_total))/100 ),2)
            as total_discount,
            sum((invoice_products.price+invoice_products.service_addition)*invoice_qty)-(sum(invoice_products.discount)+round(sum(((((invoice_products.price+invoice_products.service_addition)*invoice_products.invoice_qty)-invoice_products.discount)*((100*invoice.discount)/invoice.sub_total))/100 ),2))
            as discounted_price,
            sum(other_charges) other_charges, 
            sum(tax_total) tax_total, sum(cc_charge) cc_charge,
            sum(total_payable) org_total_payable,
            sum(invoice.paid_amount) as paid_amount,
            sum(invoice.total_payable) as org_total_payable,
            sum(invoice.balance),
            sum(paid_cash), sum(paid_card), sum(paid_voucher), sum(paid_check), sum(cctip)
            FROM invoice
            join invoice_products on invoice_products.invoice_id = invoice.id_invoice
            join business_products on business_products.id_business_products= invoice_products.product_id            
            where date(invoice_date) >= '" . $startdate."' 
            and date(invoice_date) <= '" . $enddate."' 
            and invoice.business_id=" . $this->session->userdata('businessid') . " 
            and invoice_status= 'valid'
            and invoice_type='sale'";
            if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                $sql.=" and invoice_seq >  0 ";
            }
            $sql.=" group by invoice_products.product_id, brand_name, product_name, category";
       
            
         
            
        $query = $this->db->query($sql);

        return $query->result_array();
    }

    function product_sale_details($startdate, $enddate, $sh=false) {
        
        $sql="SELECT id_invoice, ifnull(account_voucher_detail.debit, 0) as cog_sold, 
            ifnull(product_batch.batch_amount, 0) as purchase_price, invoice_products.product_id, invoice_products.brand_name 'Brand', 
            invoice_products.product_name 'Product', ifnull(invoice_products.category,'') 'Category',
            date_format(invoice_date, '%d-%m-%Y') as 'Date', invoice.customer_name as 'Customer', staff_name as 'Sold By',
            invoice.business_id, ifnull(invoice_products.invoice_qty, 0) Quantity,
            ifnull(round(invoice_products.price+ (invoice_products.service_addition/invoice_products.invoice_qty),2),0) as 'price', 
            ifnull(round((invoice_products.price+(invoice_products.service_addition/invoice_products.invoice_qty))*invoice_products.invoice_qty,2),0) as 'total_price',
            ifnull(advance_amount, 0) advance_adj,
            ifnull(invoice_products.discount, 0) product_discount,
            ifnull(round((100*invoice.discount)/invoice.sub_total,2), 0) as invoice_discount_perc,
            ifnull(round(((((invoice_products.price+(invoice_products.service_addition/invoice_products.invoice_qty))*invoice_products.invoice_qty)-invoice_products.discount)*((100*invoice.discount)/invoice.sub_total))/100 ,2), 0) invoice_discount,
            ifnull(invoice_products.discount+ round(((((invoice_products.price+(invoice_products.service_addition/invoice_products.invoice_qty))*invoice_products.invoice_qty)-invoice_products.discount)*((100*invoice.discount)/invoice.sub_total))/100 ,2),0)
            as total_discount,
            ifnull((round(invoice_products.price+(invoice_products.service_addition/invoice_products.invoice_qty),2) * invoice_products.invoice_qty)-(invoice_products.discount + round(((((invoice_products.price+(invoice_products.service_addition/invoice_products.invoice_qty))*invoice_products.invoice_qty)-invoice_products.discount)*((100*invoice.discount)/invoice.sub_total))/100 ,2)), 0)
            as discounted_price,
            ifnull(other_charges, 0) other_charges, 
            ifnull(tax_total, 0) tax_total, cc_charge cc_charge,
            ifnull(total_payable,0) org_total_payable,
            ifnull(invoice.paid_amount, 0) as paid_amount,
            ifnull(invoice.total_payable,0) as org_total_payable,
            ifnull(invoice.balance,0) as balance,
            paid_cash, paid_card, paid_voucher, paid_check, cctip, business_stores.business_store
            FROM invoice
            join invoice_products on invoice_products.invoice_id = invoice.id_invoice
            join product_batch on product_batch.id_batch = invoice_products.batch_id            
            join business_stores on business_stores.id_business_stores = product_batch.store_id
             LEFT JOIN
                (
                select invoice_id, sum(debit) as debit from
                        account_vouchers         
                                JOIN
                        account_voucher_detail ON account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
                                where account_vouchers.voucher_type=3 
                                AND account_vouchers.voucher_status = 'Active'
                                AND date(voucher_date) >= '" . $startdate . "' 
                                AND date(voucher_date) <= '" . $enddate . "' 
                    group by invoice_id
                ) as account_voucher_detail on account_voucher_detail.invoice_id= invoice.id_invoice
            where date(invoice_date) >= '" . $startdate . "' 
            and date(invoice_date) <= '" . $enddate . "' 
            and invoice.business_id=".$this->session->userdata('businessid'). " ";
                if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                    $sql .= " and invoice.invoice_seq > 0 ";
                }    
        $sql .= " and invoice_status= 'valid'
            and invoice_type='sale'
            and ifnull(reference_invoice_number,'') = ''
            order by id_invoice";
        
       //echo $sql; exit();
       
        $query = $this->db->query($sql);
        return $query->result_array();
    }

    function invoices($startdate, $enddate, $sh=false) {


        $ac_head=[];
        
        $sql1="SELECT account_head_id FROM account_event_mapping
                where account_event_id = 1 and entity_name = 'grosstotal_service' and business_id=".$this->session->userdata('businessid')." ;";
        
        $query1=$this->db->query($sql1);
        $result1= $query1->row();
        $ac_head[0] = $result1->account_head_id;
        
        
        $sql2="SELECT account_head_id FROM account_event_mapping
                where account_event_id = 1 and entity_name = 'grosstotal_retail' and business_id=".$this->session->userdata('businessid')."  ;";
        
        $query2=$this->db->query($sql2);
        $result2= $query2->row();
        $ac_head[1] = $result2->account_head_id;
        
        $sql="SELECT id_invoice, invoice_number, invoice_type, payment_mode, instrument_number,
                date_format(invoice_date,'%d-%m-%Y %H:%i:%s') 'invoice_date', 
                invoice.created_by, customer_id, invoice.business_id, ifnull(invoice_extra,'') invoice_extra
                customer_name, customer_cell, 
                round(ifnull(invoice.service_addition,0),2) as service_addition, 
                    Case When ifnull(invoice.reference_invoice_number,'') = '' then
                        round(ifnull(invoice.total_payable,0),2)
                    Else    
                        0
                    End as actual_payable,
                round(ifnull(discount_reason,''),2) as discount_reason, 
                round(ifnull(saleincome,0),2) as gross_total,
                   Case 
                        When invoice.invoice_type='service' and ifnull(invoice.reference_invoice_number,'') = ''
                            Then round(sum(invoice_details.price),2)
                        When invoice.invoice_type='sale' and ifnull(invoice.reference_invoice_number,'') = '' 
                            Then round(sum(invoice_products.price*invoice_qty),2)
                        Else 0
                            End as 'gross_total1',
                    Case 
                        When invoice.invoice_type='service' and ifnull(invoice.reference_invoice_number,'') = ''
                            Then round(sum(invoice_details.discount) ,2)
                        When invoice.invoice_type='sale' and ifnull(invoice.reference_invoice_number,'') = '' 
                            Then round(sum(invoice_products.discount),2)
			Else 0 
                            End 'service_discount',
                    Case 
                        When ifnull(invoice.reference_invoice_number,'') = ''
                            Then round(invoice.discount ,2)
                        Else 0    
                            End as 'invoice_discount',
                    Case 
                        When invoice.invoice_type='service' and ifnull(invoice.reference_invoice_number,'') = ''	
                            Then round(sum(invoice_details.discount)+invoice.discount,2)
                        When invoice.invoice_type='sale' and ifnull(invoice.reference_invoice_number,'') = '' 
                            Then round(sum(invoice_products.discount)+invoice.discount,2)
			Else 0 
                            End as total_discount,
                sub_total, 
                    Case
                        When ifnull(invoice.reference_invoice_number,'') = ''
                            Then round(invoice.advance_amount,2) 
                        Else 0 
                            End as advance_adjusted,
                    Case
                        When ifnull(invoice.reference_invoice_number,'') = ''
                            Then round(retained_amount,2)
                        Else 0
                            End as retained_amount,
                    Case 
                        When ifnull(invoice.reference_invoice_number,'') = ''
                            Then round(retained_amount_used,2)
                        Else 0
                            End as retained_amount_used,
                    Case 
                        When ifnull(invoice.reference_invoice_number,'') = ''
                            Then round(other_charges,2)
                        Else 0
                            End as other_charges,
                
                    Case 
                        When ifnull(invoice.reference_invoice_number,'') = ''
                            Then round(tax_total,2)
                        Else 0
                            End as tax_total, cc_charge,
                CASE WHEN ifnull(invoice.reference_invoice_number,'') = '' THEN  round((total_payable+cc_charge)-advance_amount  ,2)
                ELSE round(paid_amount + balance,2)
                END as 'total_payable',
                round(invoice.paid_cash + invoice.paid_card + invoice.paid_voucher + invoice.paid_check,2) as paid_amount,
                round(invoice.balance,2),
                CASE WHEN ifnull(invoice.reference_invoice_number,'') <> '' THEN 'Recovery'
                ELSE ''
                END as 'recovery', reference_invoice_number,
                round(paid_cash,2), 
                round(paid_card,2), 
                round(paid_voucher,2), 
                round(paid_check,2), 
                round(ifnull(cctip,0),2) as cctip, 
                invoice.remarks, 
                imsfiscal_invoice_number as ims_ref
                from invoice
                join invoice_details on invoice_details.invoice_id = invoice.id_invoice 
		 join invoice_products on invoice_products.invoice_id = invoice.id_invoice
                                
                join (
                    select invoice_id, id_account_Vouchers, sum(credit) as saleincome from account_voucher_detail
                    join account_vouchers on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id
                    where account_head_id in (".$ac_head[0].",".$ac_head[1].")
                    and date(voucher_date) >= '".$startdate."'
                    and date(voucher_date) <= '".$enddate."'
                    and account_vouchers.voucher_status='Active'
                    and account_vouchers.business_id=".$this->session->userdata('businessid')."
                    group by id_account_vouchers
                    ) as a on a.invoice_id = id_invoice                

                where date(invoice_date) >= '".$startdate."'
                and date(invoice_date) <= '".$enddate."'
                and invoice.business_id=".$this->session->userdata('businessid')."
                and invoice_status= 'valid' ";
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $sql.=" and invoice_seq >  0 ";
        } 
        $sql.=" group by id_invoice";
        
        
        ////////////////////////////////////
        $sql_service="SELECT 
            id_invoice,
            invoice_number,
            invoice_type,
            ifnull(invoice_extra,'') invoice_extra,
            payment_mode,
            instrument_number,
            DATE_FORMAT(invoice_date, '%d-%m-%Y %H:%i:%s') 'invoice_date',
            invoice.created_by,
            customer_id,
            invoice.business_id,
            customer_name,
            customer_cell,
            IFNULL(invoice.service_addition, 0) AS service_addition,
            round(ifnull(invoice.service_addition,0),2) as service_addition, 
                Case When ifnull(invoice.reference_invoice_number,'') = '' then
                    round(ifnull(invoice.total_payable,0),2)
                Else    
                    0
                End as actual_payable,
            IFNULL(discount_reason, '') AS discount_reason,
            IFNULL(saleincome, 0) AS gross_total,
            CASE
                WHEN
                    invoice.invoice_type = 'service'
                        AND IFNULL(invoice.reference_invoice_number, '') = ''
                THEN
                    SUM(invoice_details.price)
                ELSE 0
            END AS 'gross_total1',
            CASE
                WHEN
                    invoice.invoice_type = 'service'
                        AND IFNULL(invoice.reference_invoice_number, '') = ''
                THEN
                    SUM(invoice_details.discount)       
                ELSE 0
            END 'service_discount',
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN invoice.discount
                ELSE 0
            END AS 'invoice_discount',
            CASE
                WHEN
                    invoice.invoice_type = 'service'
                        AND IFNULL(invoice.reference_invoice_number, '') = ''
                THEN
                    SUM(invoice_details.discount) + invoice.discount
                ELSE 0
            END AS total_discount,
            sub_total,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN invoice.advance_amount
                ELSE 0
            END AS advance_adjusted,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN retained_amount
                ELSE 0
            END AS retained_amount,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN retained_amount_used
                ELSE 0
            END AS retained_amount_used,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN other_charges
                ELSE 0
            END AS other_charges,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN tax_total
                ELSE 0
            END AS tax_total,
            cc_charge,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN (total_payable + cc_charge) - advance_amount
                ELSE (paid_amount + balance)
            END AS 'total_payable',
            invoice.paid_cash + invoice.paid_card + invoice.paid_voucher + invoice.paid_check AS paid_amount,
            invoice.balance,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') <> '' THEN 'Recovery'
                ELSE ''
            END AS 'recovery',
            saleincome,
            reference_invoice_number,
            paid_cash,
            paid_card,
            paid_voucher,
            paid_check,
            IFNULL(cctip, 0) AS cctip,
            invoice.remarks,
            imsfiscal_invoice_number AS ims_ref
        FROM
            invoice
                JOIN
            invoice_details ON invoice_details.invoice_id = invoice.id_invoice
                JOIN
            (SELECT 
                invoice_id, id_account_Vouchers, SUM(credit) AS saleincome
            FROM
                account_voucher_detail
            JOIN account_vouchers ON account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id
            JOIN invoice on invoice.id_invoice = account_vouchers.invoice_id
            WHERE 
                    DATE(invoice_date) >= '".$startdate."'
                    AND DATE(invoice_date) <= '".$enddate."'
                    AND account_vouchers.voucher_status = 'Active'
                    AND account_voucher_detail.account_head_id = ".$ac_head[0] . "
                    AND account_vouchers.business_id = ".$this->session->userdata('businessid')."
            GROUP BY id_account_vouchers) AS a ON a.invoice_id = id_invoice
        WHERE
            DATE(invoice_date) >= '".$startdate."'
                AND DATE(invoice_date) <= '".$enddate."'
                AND invoice.business_id = ".$this->session->userdata('businessid')."
                AND invoice_status = 'valid'
                AND invoice_type = 'service'";
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $sql_service.=" and invoice_seq >  0 ";
        } 
        $sql_service.=" GROUP BY id_invoice";
        
        
        $sql_retail ="SELECT 
            id_invoice,
            invoice_number,
            invoice_type,
            payment_mode,
            instrument_number,
            ifnull(invoice_extra,'') invoice_extra,
            DATE_FORMAT(invoice_date, '%d-%m-%Y %H:%i:%s') 'invoice_date',
            invoice.created_by,
            customer_id,
            invoice.business_id,
            customer_name,
            customer_cell,
            IFNULL(invoice.service_addition, 0) AS service_addition,
            round(ifnull(invoice.service_addition,0),2) as service_addition, 
                    Case When ifnull(invoice.reference_invoice_number,'') = '' then
                        round(ifnull(invoice.total_payable,0),2)
                    Else    
                        0
                    End as actual_payable,
            IFNULL(discount_reason, '') AS discount_reason,
            IFNULL(saleincome, 0) AS gross_total,
            CASE
                WHEN
                    invoice.invoice_type = 'sale'
                        AND IFNULL(invoice.reference_invoice_number, '') = ''
                THEN
                    SUM(invoice_products.price * invoice_qty)
                ELSE 0
            END AS 'gross_total1',
            CASE

                WHEN
                    invoice.invoice_type = 'sale'
                        AND IFNULL(invoice.reference_invoice_number, '') = ''
                THEN
                    SUM(invoice_products.discount)
                ELSE 0
            END 'service_discount',
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN invoice.discount
                ELSE 0
            END AS 'invoice_discount',
            CASE

                WHEN
                    invoice.invoice_type = 'sale'
                        AND IFNULL(invoice.reference_invoice_number, '') = ''
                THEN
                    SUM(invoice_products.discount) + invoice.discount
                ELSE 0
            END AS total_discount,
            sub_total,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN invoice.advance_amount
                ELSE 0
            END AS advance_adjusted,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN retained_amount
                ELSE 0
            END AS retained_amount,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN retained_amount_used
                ELSE 0
            END AS retained_amount_used,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN other_charges
                ELSE 0
            END AS other_charges,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN tax_total
                ELSE 0
            END AS tax_total,
            cc_charge,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') = '' THEN (total_payable) - advance_amount
                ELSE (paid_amount + balance)
            END AS 'total_payable',
            invoice.paid_cash + invoice.paid_card + invoice.paid_voucher + invoice.paid_check AS paid_amount,
            invoice.balance,
            CASE
                WHEN IFNULL(invoice.reference_invoice_number, '') <> '' THEN 'Recovery'
                ELSE ''
            END AS 'recovery',
            saleincome,
            reference_invoice_number,
            paid_cash,
            paid_card,
            paid_voucher,
            paid_check,
            IFNULL(cctip, 0) AS cctip,
            invoice.remarks,
            imsfiscal_invoice_number AS ims_ref
        FROM
            invoice
            JOIN
            invoice_products ON invoice_products.invoice_id = invoice.id_invoice
            JOIN
            (SELECT 
                invoice_id, id_account_Vouchers, SUM(credit) AS saleincome
            FROM
                account_voucher_detail
                JOIN account_vouchers ON account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id
                JOIN invoice on invoice.id_invoice = account_vouchers.invoice_id
            WHERE   DATE(invoice_date) >= '".$startdate."'
                    AND DATE(invoice_date) <= '".$enddate."'
                    AND account_vouchers.voucher_status = 'Active'
                    AND account_voucher_detail.account_head_id = ".$ac_head[1] . "
                    AND account_vouchers.business_id = ".$this->session->userdata('businessid')."
            GROUP BY id_account_vouchers) AS a ON a.invoice_id = id_invoice
        WHERE
            DATE(invoice_date) >= '".$startdate."'
                AND DATE(invoice_date) <= '".$enddate."'
                AND invoice.business_id = ".$this->session->userdata('businessid')."
                AND invoice_status = 'valid'
                AND invoice_type = 'sale'";
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $sql_retail.=" and invoice_seq >  0 ";
        }
        $sql_retail.=" GROUP BY id_invoice";
        
        
        // echo $sql_service; exit();
        
        $query_service = $this->db->query($sql_service);
        $query_retail = $this->db->query($sql_retail);
        $result = array_merge($query_service->result_array(), $query_retail->result_array());
        return $result;
        
        
//        $query=$this->db->query($sql);        
//        return $query->result_array();
//        
    }
    

    
    function recoveries($startdate, $enddate, $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->select('invoice.created_by as by, customers.customer_name as cname');
        $this->db->join('customers', 'customers.id_customers=invoice.customer_id');
        $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('invoice_date >=', $startdate." 00:00");
        $this->db->where('invoice_date <=', $enddate." 23:59");
        //$this->db->where('reference_invoice_number <>', 'bad debts');
        $this->db->where('ifnull(reference_invoice_number,"") <>', '');
        $this->db->where('invoice.invoice_status=', 'valid');
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('invoice_seq > ', 0);
        } 
        $query = $this->db->get('invoice');

        return $query->result_array();
    }

    function cancelled_invoices($startdate, $enddate, $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('invoice_date >=', $startdate." 00:00");
        $this->db->where('invoice_date <=', $enddate." 23:59");
       // $this->db->where('reference_invoice_number <>', 'bad debts');
        $this->db->where('invoice.invoice_status=', 'cancelled');
        $query = $this->db->get('invoice');

        return $query->result_array();
    }

    function commission_details($staff_id, $startdate, $enddate, $sh=false, $business_id=0) {
        
      //  $date = strtotime("+ 1 days", strtotime($enddate));
      //  $enddate = date("Y-m-d", $date);

        $this->db->select("reference_invoice_number, staff_fullname, invoice_staff.staff_id, invoice_staff.service_type, invoice_staff.service_category, invoice_staff.service_name, invoice_staff.additional_staff, bs.commission_perc staff_commission, bs.helper_perc helper_commission, invoice_staff.paid, round(invoice_staff.commission,2) as invoice_commission,  reference_invoice_number, "
                . "date_format(invoice_date,'%d-%m-%Y %H:%i') as staff_service_date, invoice_staff.invoice_id, invoice_details.invoice_discount, invoice_details.discounted_price, round(invoice_details.final_price,2) as final_price, date_format(invoice.invoice_date, '%d-%m-%Y %H:%i') as customer_visit_date");
        
        $this->db->join("invoice", " invoice.id_invoice = invoice_staff.invoice_id");
        $this->db->join("staff", "staff.id_staff = invoice_staff.staff_id");
        $this->db->join("invoice_details", "invoice_staff.invoice_detail_id= invoice_details.id_invoice_details");
        $this->db->join("business_services bs", " invoice_details.service_id = bs.id_business_services");
        $this->db->where("invoice_status='valid'");
        $this->db->where("invoice_type='service'");
        if($business_id==0){
            $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        }else{
            $this->db->where('invoice.business_id', $business_id);
        }
       // $this->db->where('reference_invoice_number <>', 'bad debts');
       // $this->db->where('ifnull(invoice.reference_invoice_number,"")=""');
        $this->db->where('invoice_date >=', $startdate." 00:00");
        $this->db->where('invoice_date <=', $enddate." 23:59");
        $this->db->where('invoice_staff.staff_id', $staff_id);
        //$this->db->group_by("staff_id");
        $query = $this->db->get('invoice_staff');
      
        return $query->result_array();
    }
    function retail_commission_details($staff_id, $startdate, $enddate, $sh=false, $business_id=0) {

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

        $this->db->select("reference_invoice_number, staff_fullname, staff_id, business_brand_name, 
                bp.product, bp.qty_per_unit, bp.measure_unit, invoice_products.invoice_qty,
                bp.commission commission,  ROUND(invoice_products.commission,2) as invoice_commission,
               invoice_products.paid, 
               date_format(invoice_date, '%d-%m-%Y %H:%i') as invoice_date, 
               invoice_id, invoice_products.discounted_price, 
               round((invoice_products.discounted_price * bp.commission)/100,2) as staff_commission", false);
        $this->db->join("business_products bp", "invoice_products.product_id = bp.id_business_products ");
        $this->db->join("business_brands bb", "bb.id_business_brands = bp.brand_id");
        $this->db->join("invoice", "invoice.id_invoice = invoice_products.invoice_id");
        $this->db->join("staff", "staff.id_staff = invoice_products.staff_id");
        
        $this->db->where("invoice_status='valid'");
        if($business_id==0){
            $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        }else{
            $this->db->where('invoice.business_id', $business_id);
        }
       // $this->db->where('reference_invoice_number <>', 'bad debts');
       // $this->db->where('ifnull(invoice.reference_invoice_number,"")=""');
        $this->db->where('invoice_date >=', $startdate." 00:00");
        $this->db->where('invoice_date <=', $enddate." 23:59");
        $this->db->where('staff_id', $staff_id);
        //$this->db->group_by("staff_id");
        $query = $this->db->get('invoice_products');
       // echo $query; exit();
        
        return $query->result_array();
    }
    
    function commissions($startdate, $enddate, $sh=false) {

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


         //echo $sql;
        
        $sql = "SELECT 
                    staff.id_staff staff_id,
                    staff.staff_fullname staff_name,
                    DATE_FORMAT(invoice_date, '%m'),
                    DATE_FORMAT(invoice_date, '%M') AS 'Month',
                    DATE_FORMAT(invoice_date, '%Y') AS 'Year',
                    staff.staff_image,
                    COUNT(id_invoice_staff) AS 'Total Services',
                    FORMAT(SUM(invoice_staff.paid), 2) AS 'Total',
                    SUM(
                    CASE WHEN IFNULL(reference_invoice_number, '') != '' THEN invoice_staff.paid
                    ELSE 0
                    END ) as 'Recovery',
                    FORMAT(IFNULL(SUM(invoice_staff.paid) -
                    SUM(
                    CASE WHEN IFNULL(reference_invoice_number, '') != '' THEN invoice_staff.paid
                    ELSE 0
                    END )   
                    ,0),2) AS 'Amount',
                    Format(IFNULL(SUM(invoice_details.final_price), 0),2) final_price,    
                    AVG(bs.commission_perc) commission_perc,
                    FORMAT(IFNULL(SUM(invoice_staff.paid),0) * AVG(bs.commission_perc) / 100,2) 'Commission',
                    ROUND(IFNULL(SUM(invoice_staff.commission),0), 2) as 'invoice_commission'
                FROM
                    invoice_staff
                        JOIN
                    invoice_details ON invoice_details.id_invoice_details = invoice_staff.invoice_detail_id
                        JOIN
                    business_services bs ON bs.id_business_services = invoice_details.service_id
                        JOIN
                    invoice ON invoice.id_invoice = invoice_staff.invoice_id
                        JOIN
                    staff ON staff.id_staff = invoice_staff.staff_id
                WHERE
                    date(invoice_date) >= '".$startdate."'
                        AND date(invoice_date) <= '".$enddate."'
                        AND invoice_type = 'service'
                        AND invoice_status = 'valid'
                        AND invoice.business_id = ".$this->session->userdata('businessid')."
                GROUP BY staff.id_staff , staff.staff_fullname , DATE_FORMAT(invoice_date, '%M') , DATE_FORMAT(invoice_date, '%Y')
                ORDER BY 3 , 8 DESC;";
                
        $query = $this->db->query($sql);
        
        
        return $query->result_array();
    }

    function retailcommissions($startdate, $enddate, $sh=false) {

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


        $sql="SELECT staff.id_staff staff_id, staff.staff_fullname staff_name, 
            date_format(invoice_date, '%m'), 
            date_format(invoice_date, '%M') as 'Month', 
            date_format(invoice_date, '%Y') as 'Year', 
            staff.staff_image, sum(invoice_qty) as 'Total Products', format(sum(paid), 2) as 'Amount', 
            ifnull(a.Recovery,0) 'Recovery', format(ifnull(sum(paid) + ifnull(a.total,0),0),2) as 'Total', 
            ifnull(sum(paid) + ifnull(a.total,0),0), bp.commission commission_perc, 
            format(ifnull(sum(paid) + ifnull(a.total,0),0) * avg(bp.commission)/100,2) 'Commission' ,
            round(ifnull(sum(invoice_products.commission),0),2) as invoice_commission
            FROM invoice_products 
            join business_products bp on bp.id_business_products = invoice_products.product_id 
            JOIN invoice ON invoice.id_invoice = invoice_products.invoice_id 
            JOIN staff ON staff.id_staff = invoice_products.staff_id
            left join ( 
                    SELECT id_staff, format(sum(ifnull(paid,0)), 2) as 'Recovery', 
                    sum(ifnull(paid,0)) as 'total', avg(bp.commission) commission_perc, 
                    sum(invoice_qty) as 'rec_count', date_format(invoice_date, '%m') Month, 
                    date_format(invoice_date, '%Y') Year 
                    FROM invoice_products 
                    join business_products bp on bp.id_business_products = invoice_products.product_id 
                    JOIN `invoice` ON `invoice`.`id_invoice` = invoice_products.invoice_id  
                    JOIN staff ON staff.id_staff = invoice_products.staff_id
                    WHERE invoice_date >= '". $startdate." 00:00"."' AND invoice_date <= '".$enddate." 23:59"."' 
                    AND ifnull(reference_invoice_number,'') != '' 
                    AND `invoice_type` = 'sale' AND `invoice_status` = 'valid' 
                    AND invoice.business_id= ".$this->session->userdata('businessid')."
                    AND staff.business_id= ".$this->session->userdata('businessid')."
                    GROUP BY id_staff, date_format(invoice_date, '%m'), date_format(invoice_date, '%Y') 
            ) as a on a.id_staff = invoice_products.staff_id 
            and a.Month = month(invoice_date) 
            and a.Year = year(invoice_date) 
            WHERE invoice_date >= '". $startdate." 00:00"."' AND invoice_date <= '".$enddate." 23:59"."' 
            AND ifnull(reference_invoice_number,'') = '' 
            AND invoice_type = 'sale' AND invoice_status = 'valid' 
            AND invoice.business_id= ".$this->session->userdata('businessid')." AND staff.business_id= ".$this->session->userdata('businessid')."
            GROUP BY staff.id_staff, staff.staff_fullname, 
            date_format(invoice_date, '%M'), date_format(invoice_date, '%Y') 
            ORDER BY 3,8 desc";
         //echo $sql;
                
        $query = $this->db->query($sql);
        
        
        return $query->result_array();
    }
    
    function taxes($startdate, $enddate, $sh=false) {
      //  $date = strtotime("+ 1 days", strtotime($enddate));
      //  $enddate = date("Y-m-d", $date);

        $this->db->select("date_format(invoice_date, '%M') as 'Month', date_format(invoice_date, '%Y') as 'Year', invoice_tax_name as 'Tax Type', sum(invoice_tax) as 'Total'");
        $this->db->join("invoice", " invoice.id_invoice = invoice_taxes.invoice_id");
        $this->db->where("invoice_status='valid'");
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('invoice_seq > ', 0);
        } 
        $this->db->where('invoice_taxes.business_id', $this->session->userdata('businessid'));
        $this->db->where('invoice_date >=', $startdate." 00:00");
        $this->db->where('invoice_date <=', $enddate." 23:59");
        $this->db->group_by("month(invoice_date), year(invoice_date), invoice_tax_name");
        $query = $this->db->get('invoice_taxes');

        //echo $query; exit();
        
        return $query->result_array();
    }

    function attendance($startdate, $enddate, $sh=false) {
      //  $date = strtotime("+ 1 days", strtotime($enddate));
      //  $enddate = date("Y-m-d", $date);
        $sql="
                select sa.id_staff_attendance,sa.business_id,sa.staff_id,
                st.staff_fullname,date_format(sa.time_in,'%h:%i:%s') as time_show, 
                date_format(sa.time_out,'%h:%i:%s') as time_show_out,
                date_format(sa.time_in,'%Y-%m-%e') as time_in 
                from staff_attendance sa 
                join business b on b.id_business = sa.business_id 
                join staff st on st.id_staff = sa.staff_id 
                where sa.business_id = '" . $this->session->userdata('businessid') . "' 
                and sa.time_in between '$startdate' 
                and '$enddate' 
               
                order by sa.id_staff_attendance asc
                ";
        // echo $sql; exit();
        $query = $this->db->query($sql);
      
        return $query->result_array();
    }

    function attendance_month_view($startdate, $enddate, $sh=false) {
        $year = date('Y');
        //$monthdays = date();
        $query = $this->db->query("SELECT sa.staff_id, st.staff_fullname,date_format(sa.time_in,'%b') as month,count(date_format(sa.time_in,'%M')) as present, DAY(LAST_DAY(sa.time_in)) as monthdays FROM staff_attendance sa join staff st on st.id_staff = sa.staff_id where sa.time_in like '$year%' group by sa.staff_id,month,st.staff_fullname");
        return $query->result_array();
    }

    function discount($startdate, $enddate, $sh=false) {
      //  $date = strtotime("+ 1 days", strtotime($enddate));
      //  $enddate = date("Y-m-d", $date);
        $sql = "Select
                invoice_type, customer_name, 
                invoice.created_by, concat(discount_remarks, ' ', remarks) as 'discount_remarks', 
                date_format(invoice_date, '%d-%m-%Y') as 'Date', invoice_number, invoice_id, 
                service_type, 
                service_category, 
                service_name, 
                case when invoice_details.discount > 0 then invoice_details.discount_type
                Else invoice.discount_reason End as discount_type, 
                round(invoice_details.price,2) as price, 
                (100*invoice.discount)/invoice.sub_total as invoice_discount_percentage,
                round(invoice_details.discount,2) as service_discount,
                round(((invoice_details.price+invoice_details.service_addition-invoice_details.discount)*(100*invoice.discount)/invoice.sub_total)/100,2) as invoice_discount, 
                round(invoice_details.discount+ (((invoice_details.price+invoice_details.service_addition-invoice_details.discount)*(100*invoice.discount)/invoice.sub_total)/100),2) as total_discount,
                round(invoice_details.price+invoice_details.service_addition - (invoice_details.discount+ (((invoice_details.price+invoice_details.service_addition-invoice_details.discount)*(100*invoice.discount)/invoice.sub_total)/100)),2)  as discounted_price,
                invoice_details.service_addition
                FROM invoice_details 
                join invoice on invoice_details.invoice_id = invoice.id_invoice                
                where (invoice.discount > 0 or invoice_details.discount>0)
                and ifnull(invoice.reference_invoice_number, '') = '' 
                and date(invoice_date) >= '".$startdate."' and date(invoice_date) <= '".$enddate."'
                and invoice.business_id =  '" . $this->session->userdata('businessid') . "'  
                and invoice_status = 'valid' order by invoice.id_invoice
                ";
        
        //echo $sql; exit();
        $query = $this->db->query($sql);
       
        return $query->result_array();
    }

    function voucher($startdate, $enddate, $sh=false) {
      //  $date = strtotime("+ 1 days", strtotime($enddate));
      //  $enddate = date("Y-m-d", $date);
        $this->db->select("c.customer_name,v.id_order_vouchers,v.voucher_number,v.type,v.service_names,v.amount,date_format(v.voucher_date,'%d-%m-%Y') as date,date_format(v.valid_until,'%Y-%m-%d') as valid_date,v.voucher_status, v.remaining_amount, v.payment_mode, v.paid_cash, v.paid_card, v.paid_check ");
        $this->db->join('customers c', 'c.id_customers = v.customer_id');
        $this->db->where('v.voucher_date >=', $startdate." 00:00");
        $this->db->where('v.voucher_date <=', $enddate." 23:59");
        $this->db->where('v.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('order_vouchers v');
        return $query->result_array();
    }

    function bad_debts($startdate, $enddate, $sh=false) {
      //  $date = strtotime("+ 1 days", strtotime($enddate));
      //  $enddate = date("Y-m-d", $date);
        
//        $this->db->select("id_invoice, invoice_number,invoice_type, paid_amount, balance, customer_name as customer, date_format(invoice_date,'%D') as 'Day', date_format(invoice_date,'%M') as 'Month', date_format(invoice_date,'%d-%m-%Y') as 'Date', invoice_type as 'Sale Type', sub_total as 'Sub Total', gross_amount as 'Gross', discount as 'Discount', tax_total as 'Taxes', net_amount as 'Net Amount'");
//        $this->db->where('invoice_date >=', $startdate." 00:00");
//        $this->db->where('invoice_date <=', $enddate." 23:59");
//        $this->db->where('invoice_status', 'valid');
//        $this->db->where('balance >', 0);
//        $this->db->where('is_recovery', 'No');
//        $this->db->where('ifnull(reference_invoice_number,"")', '');
//        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));

        $sql="SELECT id_invoice, invoice_number, invoice_type, paid_amount, balance, 
            customer_name as customer, date_format(invoice_date, '%D') as 'Day', 
            date_format(invoice_date, '%M') as 'Month', date_format(invoice_date, '%d-%m-%Y') as 'Date', 
            invoice_type as 'Sale Type', sub_total as 'Sub Total', gross_amount as 'Gross', discount as 'Discount', 
            tax_total as 'Taxes', net_amount as 'Net Amount' 
            FROM invoice 
            WHERE invoice_date >= '".$startdate." 00:00' AND invoice_date <= '".$startdate." 23:59' 
            AND invoice_status = 'valid' 
            AND invoice_number not in (
                    select reference_invoice_number from invoice
                    where `invoice_date` >= '".$startdate." 00:00'
                    and invoice_status='valid'
            ) AND balance >0 AND is_recovery = 'No' 
            AND `invoice`.`business_id` = ".$this->session->userdata('businessid');
        
       // echo $sql;
        $query = $this->db->query($sql);
        
        //echo $query;
        return $query->result_array();
    }

    function stock_status($startdate, $enddate, $sh=false) {
      //  $date = strtotime("+ 1 days", strtotime($enddate));
      //  $enddate = date("Y-m-d", $date);

        $this->db->select('*');
        $this->db->join('business_brands', 'business_brands.id_business_brands = business_products.brand_id');
        $this->db->where('business_product_active', 'Yes');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $product = $this->db->get('business_products');
        $product = $product->result_array();

        $last_array = array();
        foreach ($product as $key => $value) {
            $this->db->select('sum(grn_qty_received) as Purchased');
            $this->db->join('goods_received_note', 'goods_received_note.grn_id = grn_details.grn_id');
            $this->db->where('grn_product_id', $value['id_business_products']);
            $this->db->where('grn_created_date >=', $startdate." 00:00");
            $this->db->where('grn_created_date <=', $enddate." 23:59");
            $query = $this->db->get('grn_details');
            $query = $query->row();

            $this->db->select('sum(invoice_qty) as Sold');
            $this->db->join('invoice','invoice.id_invoice = invoice_products.invoice_id');
            $this->db->where('product_name', $value['product']);
            $this->db->where('invoice_product_date >=', $startdate." 00:00");
            $this->db->where('invoice_product_date <=', $enddate." 23:59");
            $this->db->where('invoice_status =', "valid");
            $query1 = $this->db->get('invoice_products');
            $query1 = $query1->row();

            $last_array[] = array(
                'ID' => $value['id_business_products'],
                'brand' => $value['business_brand_name'],
                'product' => $value['product'],
                'instock' => $value['in_stock'],
                'inhouse' => $value['inhouse_stock'],
                'purchased' => $query->Purchased,
                'soldQty' => $query1->Sold
            );
        }
        return $last_array;
    }

    function expenses($startdate, $enddate, $sh=false) {

//        $this->db->select("*, date_format(voucher_date, '%d-%m-%Y') as 'Date'");
//        $this->db->where('voucher_date >=', $startdate);
//        $this->db->where('voucher_date <=', $enddate);
//        $this->db->where('voucher_status', 'Active');
//        $this->db->where('business_id', $this->session->userdata('businessid'));
//        $query = $this->db->get('account_vouchers');
//        return $query->result();
        
        $this->db->select('*, GROUP_CONCAT(concat(" ",ah.account_head)) as account_head, sum(debit) as expenses, DATE_FORMAT(av.created_on, "%d-%m-%Y") "Date", DATE_FORMAT(av.voucher_date, "%d-%m-%Y") "VDate"');
        $this->db->join('account_voucher_detail avd','av.id_account_vouchers = account_voucher_id');
        $this->db->join('account_heads ah', 'ah.id_account_heads = avd.account_head_id');
        $this->db->join('account_sub_control asctr', 'asctr.id_account_sub_control = ah.account_sub_control_id');
        $this->db->join('account_control ac', 'ac.id_account_control = asctr.account_control_id');
        $this->db->join('account_main am', 'am.id_account_main = ac.account_main_id');
        
        $this->db->where('av.business_id', $this->session->userdata('businessid'));
        $this->db->where('av.voucher_date >= ', $startdate);
        $this->db->where('av.voucher_date <= ', $enddate);
        //$this->db->where('am.account_main', 'Expenses');
        $this->db->where('ifnull(av.purchase_order_id,0) ', 0);
        
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('ah.account_head', 'Office Expense');
        }
        
        
        $this->db->where('av.voucher_type', 1);
        $this->db->where('av.voucher_status =', 'Active');
        $this->db->group_by('av.id_account_vouchers');
        $this->db->order_by('av.created_on', 'desc');
        $query = $this->db->get('account_vouchers av');
       //echo $query; exit();
         return $query->result();
    }

    
    function get_dispatch_details($startdate, $enddate, $sh=false){
        
        $sql="SELECT staff_fullname, ifnull(dv.cog,0) as cog_used,
                date_format(dispatch_notes.dispatch_date, '%d-%m-%Y') as 'Date', id_business_products,
                concat(business_brands.business_brand_name, ' ',business_products.product, ' ',ifnull(business_products.category,'')) as Product, 
                dispatch_notes.dispatch_qty as Qty, ifnull(dispatch_notes.dispatch_measure,0) as dispatch_measure, 
                ifnull(dispatch_notes.measure_unit,0) measure_unit, ifnull(business_products.qty_per_unit,0) as qty_per_unit,
                ifnull(dispatch_notes.dispatch_comment,'') dispatch_comment,
                round(product_batch.batch_amount,2) batch_amount,
                dispatch_notes.created_by as Created_by, 
                dispatch_notes.unit_type as UnitType, id_dispatch_note, dispatch_notes.visit_id,
                ifnull(customers.customer_name,'') as 'customer_name', ifnull(visit_services.service_name,'') as 'service_name', ifnull(visit_services.service_id,'') as 'service_id'
        FROM dispatch_notes        
        join business_products on business_products.id_business_products = dispatch_notes.product_id
        join business_brands on business_brands.id_business_brands = business_products.brand_id
        join product_batch on product_batch.id_batch=dispatch_notes.batch_id
        LEFT join staff on staff.id_staff = dispatch_notes.dispatch_to_staff
        left join customer_visits on customer_visits.id_customer_visits = dispatch_notes.visit_id
        left join visit_services on visit_services.id_visit_services = dispatch_notes.visit_service_id 
        AND visit_service_status='Active' 
        left join customers on customers.id_customers = customer_visits.customer_id
        left join (select account_vouchers.dispatch_id, sum(credit) as cog from account_vouchers 
        join account_voucher_detail on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id
        where ifnull(dispatch_id,'')!='' group by account_vouchers.dispatch_id) as dv on dv.dispatch_id=dispatch_notes.id_dispatch_note   
        where dispatch_date >='". $startdate." 00:00' and dispatch_date <='". $enddate." 23:59' and dispatch_notes.status='Active' and dispatch_notes.business_id = ".$this->session->userdata('businessid')." 
            group by id_dispatch_note
        order by id_dispatch_note desc";
        
        
        //echo $sql; exit();
        $query = $this->db->query($sql);
       
        return $query->result_array();
        
    }
    
    function get_dispatch_report($startdate, $enddate, $sh=false) {
      //  $date = strtotime("+ 1 days", strtotime($enddate));
      //  $enddate = date("Y-m-d", $date);
        $sql = "staff_fullname, count(dn.product_id) as ProductCount, 
                date_format(dn.dispatch_date, '%d-%m-%Y') as 'Date', id_business_products,
                concat(bb.business_brand_name, ' ',bp.product, ' ',ifnull(bp.category,'')) as Product, 
                sum(dn.dispatch_qty) as Qty, ifnull(sum(dn.dispatch_measure),0) as dispatch_measure, 
                ifnull(dn.measure_unit,0) measure_unit, ifnull(bp.qty_per_unit,0) as qty_per_unit, ifnull(dn.dispatch_comment,'') dispatch_comment,
                round(pb.batch_amount,2) batch_amount,
                dn.created_by as Created_by, 
                dn.unit_type as UnitType, id_dispatch_note";
        $this->db->select($sql, FALSE);
        $this->db->join('product_batch pb', 'pb.id_batch = dn.batch_id');
        $this->db->join('business_products bp', 'bp.id_business_products = dn.product_id');
        $this->db->join('business_brands bb', 'bb.id_business_brands = bp.brand_id');
        $this->db->join('staff', 'staff.id_staff = dn.dispatch_to_staff');
        //$this->db->join('account_vouchers', 'account_vouchers.dispatch_id = dn.id_dispatch_note and account_vouchers.voucher_status="Active"', 'left');
        //$this->db->join('account_voucher_detail', 'account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id', 'left');
        $this->db->where('dn.dispatch_date >=', $startdate." 00:00");
        $this->db->where('dn.dispatch_date <=', $enddate." 23:59");
        $this->db->where('dn.status', 'Active');
        $this->db->where('dn.business_id', $this->session->userdata('businessid'));
        $this->db->group_by('id_dispatch_note'); 
        $this->db->group_by('staff_fullname'); 
        $this->db->group_by('Date');
        $this->db->group_by('product');
        $this->db->order_by('date', 'DESC');
        $query = $this->db->get('dispatch_notes dn');
       
        return $query->result();
    }
    
    function customer_profile($startdate, $enddate, $sh=false){

        $sql1="SELECT account_head_id FROM account_event_mapping
                where account_event_id = 1 and entity_name = 'loyalty_amount' 
                and business_id=".$this->session->userdata('businessid')." ;";
        $query=$this->db->query($sql1);
        $result = $query->row();
        $account_head = $result->account_head_id;

        $sql="SELECT customers.id_customers, customers.customer_name, customers.customer_cell, ifnull(customers.customer_card,'') card, customers.customer_email, customers.customer_address, 
                date_format(customer_birthday,'%d-%m-%Y') customer_birthday, 
                date_format(customer_anniversary,'%d-%m-%Y') customer_anniversary, 
                customer_alert, customer_allergies, ifnull(i,0) invoices, 
                ifnull(purchases,0) Purchases, ifnull(discount,0) Discounts, ifnull(balance,0) balance ,
                ifnull(earned,0) earned, ifnull(used,0) used,
                ifnull(vouchers.loyaltypoints,0) loyalty_points
                FROM customers 
                left join (
                        select customer_id, count(id_invoice) i, sum(ifnull(balance,0)) balance, sum(ifnull(paid_amount,0)) purchases, 
                        sum(ifnull(discount,0)) discount                        
                        from invoice 
                        where  invoice_status='valid'                         
                        group by customer_id 
                ) as bal on bal.customer_id=customers.id_customers 
                 LEFT JOIN
                (SELECT id_account_vouchers, 
                    business_partner_id as customer_id ,
                    ifnull(SUM(credit),0) as earned,
                    ifnull(SUM(debit),0) as used,
                    ifnull(SUM(credit) - SUM(debit),0) as loyaltypoints
                    from account_vouchers 
                    join account_voucher_detail on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id
                    where account_vouchers.business_partner=1 and account_vouchers.voucher_status='Active'
                    and account_head_id=".$account_head." 
                    group by id_account_vouchers, account_vouchers.business_partner_id) as vouchers
                on vouchers.customer_id = customers.id_customers";

       // echo $sql; exit();
        $query = $this->db->query($sql);
        return $query->result_array();
        
    }
    
    function new_customers($startdate, $enddate, $sh=false){
         $sql = "select *, 
        date_format(customer_anniversary, '%d-%m-%Y %h:%i') as 'anv', 
        date_format(created_on, '%d-%m-%Y %h:%i') as 'created', 
        month(created_on) as 'm'
        from customers
        join invoice on invoice.customer_id=customers.id_customers
        join business on business.id_business = customers.business_id ";
        $sql .= " where date(invoice_date) >= '". $startdate."' and invoice.business_id = ".$this->session->userdata('businessid')." ";
        
        $sql .=" and invoice.customer_id not in (select customer_id from invoice where date(invoice_date) < '". $startdate."' and invoice.invoice_status = 'valid' and invoice.business_id=".$this->session->userdata('businessid').")";
        
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                // $this->db->where('invoice.invoice_seq >', 0);
                 $sql.=" and invoice.invoice_seq > 0 ";
            } 
        
        $sql .= " group by id_customers order by month(invoice_date) desc";
        //$this->db->order_by('month(invoice_date)','Desc');
        //$query = $this->db->get('customers');
        
        //echo $sql;
        
        $query = $this->db->query($sql);
        return $query->result();
        
        
        return $query->result();
    }
    
    function new_customer_invoices($startdate, $enddate, $sh=false){
         $sql="
            select id_customers, id_invoice,invoice_type, customers.customer_name, 
            date_format(customers.created_on,'%d-%m-%Y') created_on,
            date_format(invoice_date,'%d-%m-%Y') invoice_date, invoice_details.service_category,
            invoice_details.service_name, invoice_details.paid, invoice_staff.staff_name
            from invoice 
            join invoice_details on invoice_details.invoice_id = invoice.id_invoice
            join invoice_staff on invoice_staff.invoice_detail_id = invoice_details.id_invoice_details
            join customers on customers.id_customers = invoice.customer_id 
            where invoice.customer_id not in
                    (
                    SELECT customer_id
                    FROM invoice
                    WHERE date(invoice_date) < '".$startdate."'
                    AND `business_id` = '".$this->session->userdata('businessid') ."' 
                    )           
            AND invoice.business_id = '".$this->session->userdata('businessid') ."' 
            order by 1,2
            ";
         //echo $sql;
            $query = $this->db->query($sql);
            return $query->result_array();
        
    }
    
    function returning_customers($startdate, $enddate, $sh=false){
        
        $sql = "select *, 
        date_format(customer_anniversary, '%d-%m-%Y %h:%i') as 'anv', 
        date_format(created_on, '%d-%m-%Y %h:%i') as 'created', 
        month(created_on) as 'm'
        from invoice
        join customers on invoice.customer_id=customers.id_customers
        join business on business.id_business = customers.business_id ";
        $sql .= " where date(invoice_date) >= '". $startdate."' and date(invoice_date) <= '". $enddate."' and invoice.business_id = ".$this->session->userdata('businessid')." ";
        
        $sql .=" and customer_id in (select customer_id from invoice where date(invoice_date) < '". $startdate."' and invoice.invoice_status = 'valid' and invoice.business_id = ".$this->session->userdata('businessid')." )";
        
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){                
                 $sql.=" and invoice.invoice_seq > 0 ";
            } 
        $sql .= " order by month(invoice_date) desc";

        $query = $this->db->query($sql);
        return $query->result();
    
    }
    
    function getDatesFromRange($start, $end, $format = 'Y-m-d') { 
      
        // Declare an empty array 
        $array = array(); 

        // Variable that store the date interval 
        // of period 1 day 
        $interval = new DateInterval('P1D'); 

        $realEnd = new DateTime($end); 
        $realEnd->add($interval); 

        $period = new DatePeriod(new DateTime($start), $interval, $realEnd); 

        // Use loop to store date into array 
        foreach($period as $date) {                  
            $array[] = $date->format($format);  
        } 

        // Return the array elements 
        return $array; 
    } 
    
   
    
    function payment_breakup($startdate, $enddate, $invoicetype='all', $sh=false){
        
        $invoicecash = "select
                        sum(ifnull(paid_cash,0))                        
                        cash                       
            From invoice 
            where business_id=".$this->session->userdata('businessid')." 
            and date(invoice_date) >='".$startdate."'
            and date(invoice_date) <'".$enddate."'
                and invoice_status = 'valid' 
            ";
            if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                $invoicecash .=  " and invoice_seq > 0 ";
            } 
        
        $invoicecard = "
                       select 
                        sum(ifnull(paid_card,0))
            card
            
            From invoice 
            where business_id=".$this->session->userdata('businessid')." 
            and date(invoice_date) >='".$startdate."'
            and date(invoice_date) <'".$enddate."'
                and invoice_status = 'valid' 
            ";
            if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                $invoicecard .=  " and invoice_seq > 0 ";
            }     
        $invoicecheck = "
                       select
            SUM(CASE WHEN trim(left(ifnull(instrument_number,''), 6)) != 'Online' THEN ifnull(paid_check,0) ELSE 0 END) 'check'            
            From invoice 
            where business_id=".$this->session->userdata('businessid')." 
            and date(invoice_date) >='".$startdate."'
            and date(invoice_date) <'".$enddate."'
                and invoice_status = 'valid' 
            ";
            if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                $invoicecheck .=  " and invoice_seq > 0 ";
            } 
        $invoiceonline = "
                select
            SUM(CASE WHEN left(instrument_number, 6) = 'Online' THEN ifnull(paid_check,0) ELSE 0 END) as 'Online'            
            From invoice 
            where business_id=".$this->session->userdata('businessid')." 
            and date(invoice_date) >='".$startdate."'
            and date(invoice_date) <'".$enddate."'
                and invoice_status = 'valid' ";
            if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                $invoiceonline .=  " and invoice_seq > 0 ";
            } 
        
        $vouchercash= "select sum(ifnull(paid_cash,0)) vcash
                    FROM order_vouchers
                    where business_id=".$this->session->userdata('businessid')."	
                    and date(voucher_date) >='".$startdate."'
                    and date(voucher_date) <'".$enddate."' 
                    ";
        $vouchercard= "select sum(ifnull(paid_card,0))  vcard
                    FROM order_vouchers
                    where business_id=".$this->session->userdata('businessid')."	
                    and date(voucher_date) >='".$startdate."'
                    and date(voucher_date) <'".$enddate."' 
                    GROUP BY date_format(date_format(voucher_date, '%Y-%m-%d'), '%Y-%m-%d')";
        $vouchercheck= "select sum(CASE WHEN left(ifnull(instrument_number,''),6) != 'Online' THEN ifnull(paid_check,0) ELSE 0 END) vcheck 
                    FROM order_vouchers
                    where business_id=".$this->session->userdata('businessid')."	
                    and date(voucher_date) >='".$startdate."'
                    and date(voucher_date) <'".$enddate."' 
                    GROUP BY date_format(voucher_date, '%Y-%m-%d')";
         $voucheronline= "select sum(CASE WHEN left(ifnull(instrument_number,''),6) = 'Online' THEN ifnull(paid_check,0) ELSE 0 END) vonline 
                    FROM order_vouchers
                    where business_id=".$this->session->userdata('businessid')."	
                    and date(voucher_date) >='".$startdate."'
                    and date(voucher_date) <'".$enddate."' 
                    GROUP BY date_format(voucher_date, '%Y-%m-%d')";
        
        $advancecash = "select sum(ifnull(visit_advance.advance_amount,0))  acash
                    FROM visit_advance join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
                    where business_id=".$this->session->userdata('businessid')." 
                    and visit_advance.advance_mode = 'cash'	
                    and customer_visits.visit_status!='canceled'
                    and date(visit_advance.advance_date) >='".$startdate."'
                    and date(visit_advance.advance_date) <'".$enddate."' 
                    GROUP BY date_format(visit_advance.advance_date, '%Y-%m-%d')";
        
        $advancecard="select sum(ifnull(visit_advance.advance_amount,0)) + sum(ifnull(visit_advance.advance_cc_charge,0)) acard
            FROM visit_advance join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
            where business_id=".$this->session->userdata('businessid')." 
            and visit_advance.advance_mode = 'card' 
            and customer_visits.visit_status!='canceled'
            and date(visit_advance.advance_date) >='".$startdate."'
            and date(visit_advance.advance_date) <'".$enddate."' 
            GROUP BY date_format(visit_advance.advance_date, '%Y-%m-%d')";
        
        $advancecheck="select sum(CASE WHEN left(ifnull(visit_advance.advance_inst,''),6) != 'Online' THEN ifnull(visit_advance.advance_amount,0) ELSE 0 END) acheck
                    FROM visit_advance join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
                    where business_id=".$this->session->userdata('businessid')."
                    and visit_advance.advance_mode = 'check'
                    and customer_visits.visit_status!='canceled'
                    and date(visit_advance.advance_date) >='".$startdate."'
                    and date(visit_advance.advance_date) <'".$enddate."' 
                    GROUP BY date_format(visit_advance.advance_date, '%Y-%m-%d') ";
        
        $advanceonline="select sum(CASE WHEN left(ifnull(visit_advance.advance_inst,''),6) = 'Online' THEN ifnull(visit_advance.advance_amount,0) ELSE 0 END) acheck
                    FROM visit_advance join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
                    where business_id=".$this->session->userdata('businessid')."
                    and visit_advance.advance_mode = 'check'
                    and customer_visits.visit_status!='canceled'
                    and date(visit_advance.advance_date) >='".$startdate."'
                    and date(visit_advance.advance_date) <'".$enddate."' 
                    GROUP BY date_format(visit_advance.advance_date, '%Y-%m-%d') ";        
        
        $retainedcash="SELECT SUM(ifnull(retained_amount,0)) as 'rcash' 
                    FROM invoice WHERE payment_mode in ('Cash','Mixed') and paid_cash>0 AND date(invoice_date) >= '".$startdate."'
                    AND date(invoice_date) < '".$enddate."' AND business_id = ".$this->session->userdata('businessid')." AND invoice_status = 'valid'
                   GROUP BY date_format(invoice_date, '%Y-%m-%d') 
                 ";
//        
        $retainedcard="SELECT SUM(IFNULL(retained_amount,0)) as 'rcard' 
                    FROM invoice WHERE payment_mode = 'Card' AND date(invoice_date) >= '".$startdate."'
                    AND date(invoice_date) < '".$enddate."' AND business_id = ".$this->session->userdata('businessid')." AND invoice_status = 'valid'GROUP BY date_format(invoice_date, '%Y-%m-%d') 
                 ";
//        
        $retainedcheck="SELECT SUM(CASE WHEN LEFT(instrument_number,6) != 'Online' THEN ifnull(retained_amount,0) ELSE 0 END)  as 'rcheck' 
                    FROM invoice WHERE payment_mode = 'Check' AND date(invoice_date) >= '".$startdate."'
                    AND date(invoice_date) < '".$enddate."' AND business_id = ".$this->session->userdata('businessid')." AND invoice_status = 'valid'GROUP BY date_format(invoice_date, '%Y-%m-%d') 
                 ";
        
        $retainedonline="SELECT SUM(CASE WHEN LEFT(instrument_number,6) = 'Online' THEN ifnull(retained_amount,0) ELSE 0 END) as 'ronline' 
                    FROM invoice WHERE payment_mode = 'Check' AND date(invoice_date) >= '".$startdate."'
                    AND date(invoice_date) < '".$enddate."' AND business_id = ".$this->session->userdata('businessid')." AND invoice_status = 'valid'GROUP BY date_format(invoice_date, '%Y-%m-%d') 
                 ";
        
        $this->db->select("date_format('".$startdate."','%d-%m-%Y') as 'workdate', SUM(ifnull(paid_cash,0)) AS totalCash, "
                . "($invoicecash) AS cash, "
                . "($invoicecard) AS card,"
                . "($invoicecheck) AS bank, "
                . "($invoiceonline) AS online,"
                . "($vouchercash) AS vcash, "
                . "($vouchercard) AS vcard, "
                . "($vouchercheck) AS vcheck, "
                . "($voucheronline) AS vonline, "
                . "($advancecash) AS acash, "
                . "($advancecard) AS acard, "
                . "($advancecheck) AS acheck, "
                . "($advanceonline) AS aonline, "
                . "($retainedcash) AS rcash, "
                . "($retainedcard) AS rcard, "
                . "($retainedcheck) AS rcheck, "
                . "($retainedonline) AS ronline"
                . "", false);
        $this->db->where("business_id", $this->session->userdata('businessid'));
        $this->db->where("invoice_status", 'valid');
        $this->db->where("date(invoice_date)>=",$startdate);
        $this->db->where("date(invoice_date)<=",$enddate);
       
        if($invoicetype =="service"){
            $this->db->where("invoice_type",'service');
        } else if($invoicetype=="sale"){
            $this->db->where("invoice_type",'sale');            
        }   

        //$this->db->group_by("date_format(invoice_date, '%Y-%m-%d')");
        
         $query = $this->db->get("invoice");
        // echo $query; exit();
        return $query->row();
        
        
         $sql="
         
            SELECT date_format('".$startdate."', '%Y-%m-%d') workdate, 
            sum(ifnull(paid_cash,0)) + ifnull(vcash,0) + ifnull(acash,0) + sum(
            case When payment_mode='Cash' then ifnull(retained_amount,0) 
        	else 0 End)  
            - sum(ifnull(cctip,0))   
            cash, 
          	sum(ifnull(paid_card,0)) + ifnull(vcard,0) + ifnull(acard,0) + sum(
                case When payment_mode='Card' then ifnull(retained_amount,0) 
            	else 0 End)    
            card, 
            sum(ifnull(paid_check,0)) + ifnull(vcheck,0) + ifnull(acheck,0) 'check' ,
            ifnull(acash,0) acash, ifnull(acard,0) acard, ifnull(acheck,0) acheck, ifnull(vcash,0) vcash, ifnull(vcard,0) vcard, ifnull(vcheck,0) vcheck,
            sum(ifnull(paid_cash,0)) - sum(ifnull(cctip,0))  as 'cash_only',
            sum(ifnull(paid_card,0))  as 'card_only',
            sum(ifnull(paid_check,0))  as 'check_only'
            FROM invoice
            left join (
                    select date_format(voucher_date, '%Y-%m-%d') vdate, sum(paid_cash) vcash, sum(paid_card) vcard, sum(paid_check) vcheck 
                    FROM order_vouchers
                    where business_id=".$this->session->userdata('businessid')."	
                    and date(voucher_date) >='".$startdate."'
                    and date(voucher_date) <='".$enddate."' 
                    GROUP BY date(voucher_date)) 
            ) as v on vdate = date(invoice.invoice_date)
            left join (
                    select date_format(visit_advance.advance_date, '%Y-%m-%d') cashdate, sum(visit_advance.advance_amount) acash
                    FROM visit_advance join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
                    where business_id=".$this->session->userdata('businessid')." 
                    and visit_advance.advance_mode = 'cash'	
                    and customer_visits.visit_status!='canceled'
                    and date(visit_advance.advance_date) >='".$startdate."'
                    and date(visit_advance.advance_date) <='".$enddate."' 
                    GROUP BY date(visit_advance.advance_date)     
            ) as acash on cashdate = date(invoice_date)
            left join (
                    select date_format(visit_advance.advance_date, '%Y-%m-%d') carddate, sum(visit_advance.advance_amount) acard
                    FROM visit_advance join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
                    where business_id=".$this->session->userdata('businessid')." 
                    and visit_advance.advance_mode = 'card' 
                    and customer_visits.visit_status!='canceled'
                    and date(visit_advance.advance_date) >='".$startdate."'
                    and date(visit_advance.advance_date) <='".$enddate."' 
                    GROUP BY date(visit_advance.advance_date)     
            ) as acard on carddate = date(invoice_date)
            left join (
                    select date_format(visit_advance.advance_date, '%Y-%m-%d') checkdate, sum(visit_advance.advance_amount) acheck
                    FROM visit_advance join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
                    where business_id=".$this->session->userdata('businessid')."
                    and visit_advance.advance_mode = 'check'
                    and customer_visits.visit_status!='canceled'
                    and date(visit_advance.advance_date) >='".$startdate."'
                    and date(visit_advance.advance_date) <='".$enddate."' 
                    GROUP BY date(visit_advance.advance_date) 
            ) as acheck on checkdate = date(invoice_date)
            
            
                ;";
        
        echo $sql; exit();
            $query = $this->db->query($sql);
            return $query->row();
        
    }
    
    function cash_register($today, $tomorrow){
         
       
        $business_id = $this->session->userdata('businessid');
        
        $sub_query1 = ""
                . "SELECT SUM(ifnull(balance,0)) FROM invoice "
                . "WHERE "
                . "invoice_date > '$today' AND invoice_date < '$tomorrow' AND reference_invoice_number = '' And "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        $sub_query2 = ""
                . "SELECT SUM(ifnull(paid_amount,0)) FROM invoice "
                . "WHERE reference_invoice_number != '' AND "
                . "invoice_date > '$today' AND invoice_date < '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        $sub_query3 = ""
                . "SELECT SUM(ifnull(total_payable,0)) FROM invoice "
                . "WHERE invoice_type = 'service'   AND reference_invoice_number = '' And "
                . "invoice_date > '$today' AND invoice_date < '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        $sub_query4 = ""
                . "SELECT SUM(ifnull(total_payable,0)) FROM invoice "
                . "WHERE invoice_type = 'sale' AND reference_invoice_number = '' AND "
                . "invoice_date > '$today' AND invoice_date < '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
       

        //Cash changing paid_amount to paid_cash
        $sub_query5 = ""
                ."select sum(ifnull(casha,0) + ifnull(cashb,0) + ifnull(cashc,0)   + ifnull(cashd,0)) as 'Cash' from (
                    SELECT SUM(ifnull(paid_cash,0)) as 'casha' 
                    FROM invoice WHERE payment_mode in ('Cash','Mixed') AND invoice_date > '".$today."'
                    AND invoice_date < '".$tomorrow."' AND business_id = ".$business_id." AND invoice_status = 'valid' 
                    ) a, (
                    select sum(ifnull(visit_advance.advance_amount,0)) as 'cashb' From visit_advance
                    join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id 
                    WHERE visit_status <> 'canceled' AND visit_advance.advance_date >= '".$today."'
                    AND visit_advance.advance_date < '".$tomorrow."' And visit_advance.advance_mode='cash'                    
                    AND business_id = ".$business_id.") b, (
                    SELECT SUM(ifnull(retained_amount,0)) as 'cashc' 
                    FROM invoice WHERE payment_mode = 'Cash' AND invoice_date > '".$today."'
                    AND invoice_date < '".$tomorrow."' AND paid_cash>0 AND business_id = ".$business_id." AND invoice_status = 'valid'
                    ) c, (
                    SELECT sum(returnamount) as 'cashd' FROM invoice 
                    where paid_cash > 0 and date(invoice_date) = '".$today."' and business_id=".$business_id." 
                    and invoice_status='valid') d
                    ";

        //Card changing paid_amount to paid_card
        $sub_query6 = ""
                ."select sum(ifnull(carda,0) + ifnull(cardb,0) + ifnull(cardc,0)) as 'Card' from (
                    SELECT sum(ifnull(paid_card,0)) as 'carda' 
                    FROM invoice WHERE payment_mode in ('Card','Mixed') AND invoice_date > '".$today."'
                    AND invoice_date < '".$tomorrow."' AND business_id = ".$business_id." AND invoice_status = 'valid' 
                    ) a, (
                    select sum(ifnull(visit_advance.advance_amount, 0)) as 'cardb' From visit_advance
                    join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
                    WHERE visit_status <> 'canceled' AND visit_advance.advance_date >= '".$today."'
                    AND visit_advance.advance_date < '".$tomorrow."' And visit_advance.advance_mode='card'                    
                    AND business_id = ".$business_id.") b, (
                    SELECT sum(ifnull(retained_amount,0)) as 'cardc' 
                    FROM invoice WHERE payment_mode = 'Card' AND invoice_date > '".$today."'
                    AND invoice_date < '".$tomorrow."' AND business_id = ".$business_id." AND invoice_status = 'valid'     
                    ) c
                    ";
       
        //Check changing paid_amount to paid_check
        $sub_query7 = ""
                ."select sum(ifnull(checka,0) + ifnull(checkb,0) + ifnull(checkc,0)) as 'Check' from (
                    SELECT sum(ifnull(paid_check,0)) as 'checka' 
                    FROM invoice WHERE payment_mode = 'Check' AND invoice_date > '".$today."'
                    AND invoice_date < '".$tomorrow."' AND business_id = ".$business_id." AND invoice_status = 'valid' 
                    ) a, (
                    select sum(ifnull(visit_advance.advance_amount,0)) as 'checkb' From visit_advance
                    join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
                    WHERE visit_status <> 'canceled' AND visit_advance.advance_date >= '".$today."'
                    AND visit_advance.advance_date < '".$tomorrow."' And visit_advance.advance_mode='check'                    
                    AND business_id = ".$business_id.") b, (
                    SELECT sum(ifnull(retained_amount,0)) as 'checkc' 
                    FROM invoice WHERE payment_mode = 'Check' AND invoice_date > '".$today."'
                    AND invoice_date < '".$tomorrow."' AND business_id = ".$business_id." AND invoice_status = 'valid'     
                    ) c
                    ";
        //advance adjusted
        $sub_query8 = ""
                . "SELECT SUM(ifnull(advance_amount,0)) FROM invoice "
                . "WHERE "
                . "invoice_date > '$today' AND invoice_date < '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //Todays Sale
        $sub_query9 = ""
                . "SELECT SUM(ifnull(gross_amount,0)) FROM invoice "
                . "WHERE reference_invoice_number = ''  AND "
                . "invoice_date > '$today' AND invoice_date < '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //totalVouchers changing paid_amount to paid_voucher
        $sub_query10 = ""
                . "SELECT SUM(ifnull(paid_voucher,0)) FROM invoice "
                . "WHERE payment_mode = 'Voucher' AND "
                . "invoice_date > '$today' AND invoice_date < '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        
        //totalAdvance from visit_advance
        $sub_query11 = ""
                . "SELECT SUM(visit_advance.advance_amount) FROM visit_advance join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id "
                
                . "WHERE (visit_status <> 'canceled' or visit_status <> 'cancelled') AND "
                . "visit_advance.advance_date >= '$today' AND visit_advance.advance_date < '$tomorrow' AND "
                . "customer_visits.business_id = $business_id and ifnull(customer_id,0) > 0";
        
        //retained amount
        $sub_query12 = "" 
                . "SELECT SUM(ifnull(retained_amount,0)) FROM invoice "
                . "WHERE invoice_date > '$today' AND invoice_date < '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //cctip amount
        $sub_query13 = "" 
                . "SELECT SUM(ifnull(cctip,0)) FROM invoice "
                . "WHERE invoice_date > '$today' AND invoice_date < '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //cccharge amount
        $sub_query14 = "" 
                . "SELECT SUM(ifnull(cc_charge,0)) FROM invoice "
                . "WHERE invoice_date > '$today' AND invoice_date < '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        //other charges amount
        $sub_query15 = "" 
                . "SELECT SUM(ifnull(other_charges,0)) FROM invoice "
                . "WHERE invoice_date > '$today' AND invoice_date < '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        //tax amount
        $sub_query16 = "" 
                . "SELECT SUM(ifnull(tax_total,0)) FROM invoice "
                . "WHERE invoice_date > '$today' AND invoice_date < '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";    
        $sub_query21="SELECT sum(returnamount) as 'returncash' FROM invoice 
                    where date(invoice_date) = '".$today."' and business_id=".$business_id." 
                    and invoice_status='valid'";
        $mode=array();
        $mode[0]='Cash'; $mode[1]='Mixed';
        
        $this->db->select("SUM(ifnull(paid_cash,0)) AS totalCash, date_format('".$today."','%d-%m-%Y') as 'passeddate', "
                . "($sub_query1) AS totalBalance, "
                . "($sub_query2) AS totalRecovery, "
                . "($sub_query3) AS totalService, "
                . "($sub_query4) AS totalRetail, "
                . "($sub_query5) AS Cash, "
                . "($sub_query6) AS Card, "
                . "($sub_query7) AS Checks, "
                . "($sub_query8) AS AdvAdj, "    
                . "($sub_query9) AS totalSale, "
                . "($sub_query10) AS totalVoucher, " 
                . "($sub_query11) AS totalAdvance, "
                . "($sub_query12) AS totalRetained, "
                . "($sub_query13) AS cctip, "
                . "($sub_query14) AS cccharge, "
                . "($sub_query15) AS other_charges, "
                . "($sub_query16) AS tax_total, "
                . "($sub_query21) AS totalReturnCash "
                . "", false);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('invoice_date >', $today);
        $this->db->where('invoice_date <', $tomorrow);
        $this->db->where('invoice_status', 'valid');
        $this->db->where_in('payment_mode', $mode);
        
        $query = $this->db->get('invoice');
        // echo $query;
        // exit();
       
        return $query->row();
        
    }
    
    function get_cash_voucher($today, $tomorrow){
        

        $business_id = $this->session->userdata('businessid');
        
        $sub_query1 = ""
                . "SELECT SUM(ifnull(amount,0)) amount FROM order_vouchers "
                . "WHERE payment_mode = 'Cash'  AND "
                . "voucher_date > '$today' AND voucher_date < '$tomorrow' AND "
                . "business_id = $business_id";
        
        $sub_query2 = ""
                . "SELECT SUM(ifnull(amount,0)) amount FROM order_vouchers "
                . "WHERE payment_mode = 'Card' AND "
                . "voucher_date > '$today' AND voucher_date < '$tomorrow' AND "
                . "business_id = $business_id";
        
        $sub_query3 = ""
                . "SELECT SUM(ifnull(amount,0)) amount FROM order_vouchers "
                . "WHERE payment_mode = 'Check' AND "
                . "voucher_date > '$today' AND voucher_date < '$tomorrow' AND "
                . "business_id = $business_id";
        
        $this->db->select("SUM(ifnull(amount,0)) AS totalVoucherAmount, "
                . "($sub_query1) AS Cash, "
                . "($sub_query2) AS Card, "
                . "($sub_query3) AS Checks "
                . "", false);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('voucher_date >', $today);
        $this->db->where('voucher_date <', $tomorrow);
        
        $query = $this->db->get('order_vouchers');
        return $query->row();
        
    }
    
    function get_today_expenses($today, $tomorrow){
        if(!isset($today) || empty($today)){
            $today = date('Y-m-d');
        }

        $event_mappings = $this->accounting_model->get_mapped_accounts(1);
        foreach($event_mappings as $event_mapping){
            if($event_mapping['entity_name']=='paid_cash'){
                $sql="SELECT ifnull(sum(credit),0) as today_expenses 
                FROM `account_vouchers` 
                JOIN `account_voucher_detail` ON `account_vouchers`.`id_account_vouchers` = `account_voucher_detail`.`account_voucher_id` 
                JOIN account_voucher_type on account_voucher_type.id_account_voucher_type = account_vouchers.voucher_type 
                WHERE `account_vouchers`.`business_id` = '".$this->session->userdata('businessid')."' 
                AND `account_vouchers`.`voucher_date` = '".$today."'  
                AND `account_vouchers`.`voucher_status` = 'Active' 
                AND account_vouchers.voucher_type = 1
                AND account_head_id = ".$event_mapping['account_head_id'].";";
            }
        }
        
        $query = $this->db->query($sql);
        
        return $query->row();
        
//        $sql="SELECT sum(ifnull(debit,0)) as today_expenses 
//                FROM `account_vouchers` 
//                JOIN `account_voucher_detail` 
//                ON `account_vouchers`.`id_account_vouchers` = `account_voucher_detail`.`account_voucher_id` 
//                JOIN `account_heads` ON `account_voucher_detail`.`account_head_id`=`account_heads`.`id_account_heads` 
//                WHERE `account_vouchers`.`business_id` = '".$this->session->userdata('businessid')."' 
//                AND `account_vouchers`.`voucher_date` = '".$today."' 
//                AND `account_vouchers`.`voucher_status` = 'Active' 
//                AND `account_vouchers`.`voucher_type` = 1 
//                AND `account_heads`.`account_sub_control_id` = 15 
//                AND `account_vouchers`.`payment_mode` = 'Cash'
//                AND id_account_vouchers not in (
//                        SELECT  id_account_vouchers
//                        FROM `account_vouchers` 
//                        JOIN `account_voucher_detail` 
//                        ON `account_vouchers`.`id_account_vouchers` = `account_voucher_detail`.`account_voucher_id` 
//                        JOIN `account_heads` ON `account_voucher_detail`.`account_head_id`=`account_heads`.`id_account_heads`
//                        WHERE `account_vouchers`.`business_id` =  '".$this->session->userdata('businessid')."' 
//                        AND `account_vouchers`.`voucher_date` = '".$today."' 
//                        AND `account_vouchers`.`voucher_status` = 'Active' 
//                        AND `account_vouchers`.`voucher_type` = 1                         
//                        and lower(account_head) ='cash in hand' 
//                        AND `account_vouchers`.`payment_mode` = 'Cash'
//                ) 
//                ";
//        $query = $this->db->query($sql);
//        return $query->row();
    }
    
    function get_cash_register($today, $tomorrow){
                       
        $this->db->select('ifnull(sum((ifnull(x5000,0) * 5000) + (ifnull(x1000,0) * 1000) + (ifnull(x500,0) * 500) + (ifnull(x100,0) * 100) + (ifnull(x75,0) * 75) + (ifnull(x50,0) * 50) + (ifnull(x20,0) * 20) +(ifnull(x10,0) * 10)+(ifnull(x5,0) * 5)+(ifnull(x1,0) * 1)),0) as "cash", ifnull(difference,0) as "diff", register_status, ifnull(cash_addition,0) as cash_addition, ifnull(till_amounts,0) as till_amounts ', false);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('cash_register_date =', $today);
        $query = $this->db->get('cash_register');
        //echo $query; exit();
        return $query->row();
        
    }
    
    function get_yesterday_till_amount($today, $tomorrow){
        
        $yesterday="DATE_ADD('".$today."', INTERVAL -1 DAY)";
        
        $sql="SELECT sum(ifnull(till_amounts, 0)) as 'till_amounts', 
        date_format('".$today."', '%d-%m-%Y') as 'passeddate' 
        FROM cash_register 
        WHERE business_id = ".$this->session->userdata('businessid')." 
        AND cash_register_date = DATE_ADD('".$today."', INTERVAL -1 DAY)";
       
        $query = $this->db->query($sql);
       
        return $query->row();
        
    }
    
    function gettomorrowfromserver($passeddate){
        $today = $passeddate; //->format('Y-m-d');
        
        $sql = "select DATE_ADD('".$today."', INTERVAL 1 DAY) as 'tomorrow'";
        $query = $this->db->query($sql);
        $result=$query->result();
        foreach ($result as $row){
            $tomorrow=$row->tomorrow;
        }
       
        return $tomorrow;
    }
    
    function cancelled_visits($startdate, $enddate, $sh=false) {

      //  $date = strtotime("+ 1 days", strtotime($enddate));
      //  $enddate = date("Y-m-d", $date);
                
        $sql="select *, date_format(visit_service_start, \"%d-%m-%Y %H:%i:%s\") date from visit_services
        join customer_visits on visit_services.customer_visit_id = customer_visits.id_customer_visits 
        join customers on customers.id_customers = customer_visits.customer_id 
        join business_services bs on bs.id_business_services = visit_services.service_id
        join service_category sc on sc.id_service_category = bs.service_category_id
        where convert(visit_service_start, date) >=  '".$startdate." 00:00"."' AND convert(visit_service_start, date) <= '".$enddate." 23:59"."'      
        and visit_status = 'canceled' and visit_service_status='Active' 
        and customer_visits.business_id=".$this->session->userdata('businessid');
        
        
        $sql="select staff_name, id_customer_visits, customer_name, customer_cell, date_format(customer_visit_date,'%d-%m-%Y') customer_visit_date, 
            date_format(visit_service_start,'%d-%m-%Y %H:%i:%s') visit_service_start, service_id, service_category,
             visit_services.service_name, service_rate, cancelreason, reminder_sms, reminder_call, reminder_email, service_desc, canceled_by
            from customer_visits 
            join customers on customers.id_customers = customer_visits.customer_id
            join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits
            and visit_service_status='Active' 
            join visit_service_staffs on visit_service_staffs.visit_service_id = visit_services.id_visit_services 
            and visit_service_staff_status='Active'
            join business_services on business_services.id_business_services = visit_services.service_id
            join service_category on service_category.id_service_category = business_services.service_category_id
            where visit_status = 'canceled'
            and convert(visit_service_start, date) >=  '".$startdate." 00:00"."' AND convert(visit_service_start, date) <= '".$enddate." 23:59"."'
            and customer_visits.business_id = ".$this->session->userdata('businessid')."
            order by staff_name, id_customer_visits";
        
        $query = $this->db->query($sql);
        return $query->result_array();
    }

    function open_visits($startdate, $enddate, $sh=false) {

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

//        $sql="select *, date_format(visit_service_start, \"%d-%m-%Y %H:%i:%s\") date from visit_services
//        join customer_visits on visit_services.customer_visit_id = customer_visits.id_customer_visits 
//        join customers on customers.id_customers = customer_visits.customer_id 
//        join business_services bs on bs.id_business_services = visit_services.service_id
//        join service_category sc on sc.id_service_category = bs.service_category_id
//        where convert(visit_service_start, date) >=  '".$startdate." 00:00"."' AND convert(visit_service_start, date) <= '".$enddate." 23:59"."'      
//        and visit_status = 'open' 
//        and customer_visits.business_id=".$this->session->userdata('businessid')." group by id_customer_visits";
        
        
        $sql= "select 
                id_customer_visits, date_format(customer_visit_date, '%d-%m-%Y') as date,
                customer_id , customer_name, customer_cell, date_format(visit_service_start, '%d-%m-%Y %H:%i:%s') visit_service_start,
                service_type.service_type, service_category.service_category, service_name, service_flag, reminder_sms, reminder_call, reminder_email, staff_name
                from customer_visits 
                join customers on customers.id_customers = customer_visits.customer_id
                join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits
                and visit_service_status='Active' 
                join visit_service_staffs on visit_service_staffs.visit_service_id = visit_services.id_visit_services                
                and date(visit_service_start) >=  '".$startdate."' AND date(visit_service_start) <= '".$enddate."'
                join service_category on service_category.id_service_category=visit_services.id_service_category
                join  service_type on service_type.id_service_types = service_category.service_type_id
                where visit_status='open' and service_flag='servicetype' 
                and customer_visits.business_id=".$this->session->userdata('businessid')." ";
            
        if(null!==$this->input->post('id_service_type') && $this->input->post('id_service_type')>0){
            $sql.=" and service_category.service_type_id = ".$this->input->post('id_service_type'); 
        }        
        if(null!==$this->input->post('id_service_category') && $this->input->post('id_service_category')>0){
            $sql.=" and service_category.id_service_category = ".$this->input->post('id_service_category'); 
        } 
        if(null!==$this->input->post('id_business_services') && $this->input->post('id_business_services')>0){
            $sql.=" and visit_services.service_id = ".$this->input->post('id_business_services'); 
        }
        if(null!==$this->input->post('staff_id') && $this->input->post('staff_id')>0){
            $sql.=" and visit_service_staffs.staff_id = ".$this->input->post('staff_id'); 
        }
        $sql.= " group by id_visit_services order by 1,6;";
                
        $query = $this->db->query($sql);
        $data1= $query->result_array();
        
        $sql1 = "        select 
                id_customer_visits, date_format(customer_visit_date, '%d-%m-%Y') as date,
                customer_id , customer_name, customer_cell, date_format(visit_service_start,'%d-%m-%Y %H:%i:%s') visit_service_start,
                package_type.service_type as 'service_type', package_category.service_category collate utf8_general_ci as 'service_category', visit_services.service_name, service_flag,
                reminder_sms, reminder_call, reminder_email, staff_name
                from customer_visits 
                join customers on customers.id_customers = customer_visits.customer_id
                join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits
                and visit_service_status='Active' 
                join visit_service_staffs on visit_service_staffs.visit_service_id = visit_services.id_visit_services
                and date(visit_service_start) >=  '".$startdate."' AND date(visit_service_start) <= '".$enddate."'
                join package_category on package_category.id_package_category = visit_services.id_service_category
                join package_type on package_type.id_package_type = package_category.package_type_id
                where visit_status='open' and service_flag='packagetype'
                and customer_visits.business_id=".$this->session->userdata('businessid')." ";
            
        if(null!==$this->input->post('id_service_type') && $this->input->post('id_service_type')>0){
            $sql1.=" and package_category.package_type_id = ".$this->input->post('id_service_type'); 
        }        
        if(null!==$this->input->post('id_service_category') && $this->input->post('id_service_category')>0){
            $sql1.=" and package_category.id_package_category = ".$this->input->post('id_service_category'); 
        }
        if(null!==$this->input->post('id_business_services') && $this->input->post('id_business_services')>0){
            $sql1.=" and visit_services.service_id = ".$this->input->post('id_business_services'); 
        }
        if(null!==$this->input->post('staff_id') && $this->input->post('staff_id')>0){
            $sql1.=" and visit_service_staffs.staff_id = ".$this->input->post('staff_id'); 
        }
        $sql1.= " group by id_visit_services order by 1,6;";
                
        $query = $this->db->query($sql1);
        $data2=$query->result_array();
        //echo $sql; exit();
        $data = array_merge($data1, $data2);
        return $data;
        
    }
    
    function advance_collected($startdate, $enddate, $sh=false) {

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

//        $sql="select *, date_format(visit_service_start, \"%d-%m-%Y %H:%i:%s\") date from visit_services
//        join customer_visits on visit_services.customer_visit_id = customer_visits.id_customer_visits 
//        join customers on customers.id_customers = customer_visits.customer_id 
//        join business_services bs on bs.id_business_services = visit_services.service_id
//        join service_category sc on sc.id_service_category = bs.service_category_id
//        where convert(visit_service_start, date) >=  '".$startdate."' AND convert(visit_service_start, date) <= '".$enddate."'      
//        and visit_status = 'open' 
//        and customer_visits.business_id=".$this->session->userdata('businessid')." group by id_customer_visits";
//        
        
       $sql="SELECT id_visit_advance, service_flag, id_customer_visits, date_format(va.advance_date, '%d-%m-%Y %H:%i:%s') advance_date, customer_name, service_type, service_category, date_format(visit_service_start, '%d-%m-%Y %H:%i:%s') visitdate, va.advance_amount, va.advance_mode, va.advance_inst, customer_cell, visit_status 
        FROM visit_advance va
        join customer_visits cv on va.customer_visit_id = cv.id_customer_visits 
        join visit_services vs on vs.customer_visit_id = cv.id_customer_visits 
        and vs.visit_service_status='Active' 
        join customers on customers.id_customers = cv.customer_id 
        join business_services bs on bs.id_business_services = vs.service_id 
        join package_services ps on ps.service_id = vs.service_id 
        join package_category pc on pc.id_package_category = ps.package_category_id and pc.id_package_category = vs.id_service_category
        join package_type pt on pt.id_package_type = pc.package_type_id 
        where va.advance_date >= '".$startdate.' 00:00'."' AND convert(va.advance_date, date) <= '".$enddate.' 23:59'."'    
        and visit_status <> 'canceled' and service_flag='packagetype' 
        and cv.business_id=".$this->session->userdata('businessid')." group by id_visit_advance 
       union
       SELECT id_visit_advance,service_flag, id_customer_visits, 
        date_format(va.advance_date, '%d-%m-%Y %H:%i:%s') advance_date, customer_name, 
        service_type, service_category, date_format(visit_service_start, '%d-%m-%Y %H:%i:%s') visitdate, 
        va.advance_amount, va.advance_mode, va.advance_inst, customer_cell, visit_status 
        FROM visit_advance va  
        join customer_visits cv on va.customer_visit_id = cv.id_customer_visits 
        join visit_services vs on vs.customer_visit_id = cv.id_customer_visits 
        and vs.visit_service_status='Active' 
        join customers on customers.id_customers = cv.customer_id 
        join business_services bs on bs.id_business_services = vs.service_id 
        join service_category sc on sc.id_service_category = bs.service_category_id 
        join service_type st on st.id_service_types = sc.service_type_id 
        where va.advance_date >= '".$startdate.' 00:00'."' AND convert(va.advance_date, date) <= '".$enddate.' 23:59'."'    
        and visit_status <> 'canceled'
        and service_flag='servicetype' 
        and cv.business_id=".$this->session->userdata('businessid')." group by id_visit_advance
        ";       
      
        $query = $this->db->query($sql);
        return $query->result_array();
    }

    function staff_retail_sale_summary($startdate, $enddate, $sh=false){
        

        
        $sql="SELECT staff.id_staff, staff.staff_fullname staff_name, 
            staff.staff_image, 
            sum(invoice_qty) as 'Quantity', 
            count(invoice_products.product_name) 'Products',
            format(sum(paid), 2) as 'Amount', 
            ifnull(a.Recovery,0) 'Recovery', 
            format(ifnull(sum(paid) + ifnull(a.total,0),0),2) as 'Total',
            ifnull(sum(paid) + ifnull(a.total,0),0),
            sum(ifnull(paid,0))*0.01 'Commission' 
            FROM invoice_products 
            JOIN invoice ON invoice.id_invoice = invoice_products.invoice_id 
            JOIN staff ON staff.staff_fullname = invoice_products.staff_name
            left join (
                    SELECT staff.id_staff, staff_name, format(sum(ifnull(paid,0)), 2) as 'Recovery', sum(ifnull(paid,0)) as 'total',
                    sum(invoice_qty) as 'rec_count'
                    FROM invoice_products
                    JOIN invoice ON invoice.id_invoice = invoice_products.invoice_id 
                    JOIN staff ON staff.staff_fullname = invoice_products.staff_name
                    WHERE invoice_date >= '".$startdate." 00:00' AND invoice_date <= '".$enddate." 23:59' 
                    AND ifnull(reference_invoice_number,'') != '' 
                    AND invoice_type = 'sale' 
                    AND invoice_status = 'valid' ";
                    if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                        $sql.=" and invoice_seq > 0 ";
                    }
                    $sql.=" AND invoice.business_id= ".$this->session->userdata('businessid')."
                    AND staff.business_id= ".$this->session->userdata('businessid')."
                    GROUP BY id_staff, staff_name, staff_image
            ) as a on a.staff_name = staff.staff_fullname
            WHERE invoice_date >= '".$startdate.' 00:00'."' AND invoice_date <= '".$enddate.' 23:59'."' 
            AND ifnull(reference_invoice_number,'') = '' 
            AND invoice_type = 'sale' 
            AND invoice_status = 'valid' ";
        
            if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                $sql.=" and invoice_seq > 0 ";
            }        

            $sql.=" AND invoice.business_id= ".$this->session->userdata('businessid')."
            AND staff.business_id= ".$this->session->userdata('businessid')."
            GROUP BY staff.id_staff, staff.staff_fullname, staff.staff_image
            ORDER BY 6 desc";
        
        $query = $this->db->query($sql);
        return $query->result_array();
        
    }

    function receivables($startdate, $enddate, $sh=false){
        
        $sql="select customer_visits.id_customer_visits, customers.customer_name, 'service' customer_cell, date_format(visit_services.visit_service_start, '%d-%m-%Y') mDate, 
            sum(business_services.service_rate) price, a.advance,
            sum(business_services.service_rate) - a.advance as receivables
            from customer_visits 
            join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits
            and visit_service_status='Active' 
            join customers on customers.id_customers=customer_visits.customer_id
            join business_services on business_services.id_business_services = visit_services.service_id
            join (
                select visit_advance.customer_visit_id, sum(ifnull(advance_amount,0)) advance from visit_advance 
                group by customer_visit_id
            ) a on a.customer_visit_id = customer_visits.id_customer_visits
            where customer_visits.visit_status='open' and customer_visits.business_id= ".$this->session->userdata('businessid')."
			and visit_services.service_flag='servicetype'
            and convert(visit_services.visit_service_start, date) >= '".$startdate.' 00:00'."'
            and convert(visit_services.visit_service_start, date) <= '".$enddate.' 23:59'."'
            group by customer_visits.id_customer_visits

            union
            select customer_visits.id_customer_visits, customers.customer_name, 'package' customer_cell, date_format(visit_services.visit_service_start, '%d-%m-%Y') mDate, 
            sum(business_services.service_rate) price, a.advance,
            sum(business_services.service_rate) - a.advance as receivables
            from customer_visits 
            join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits
            and visit_service_status='Active' 
            join customers on customers.id_customers=customer_visits.customer_id
            join package_services as business_services on business_services.service_id = visit_services.service_id and business_services.package_category_id =visit_services.id_service_category
            join (
                select visit_advance.customer_visit_id, sum(ifnull(advance_amount,0)) advance from visit_advance 
                group by customer_visit_id
            ) a on a.customer_visit_id = customer_visits.id_customer_visits
            where customer_visits.visit_status='open' and customer_visits.business_id= ".$this->session->userdata('businessid')."
			and visit_services.service_flag='packagetype'
            and convert(visit_services.visit_service_start, date) >= '".$startdate.' 00:00'."'
            and convert(visit_services.visit_service_start, date) <= '".$enddate.' 23:59'."'
            group by customer_visits.id_customer_visits";
      
        $query = $this->db->query($sql);
        return $query->result_array();
        
    }

    function recoveryinvoices($startdate, $enddate, $sh=false){
        
        
        $this->db->select('*,DATE_FORMAT(invoice_date, "%d-%m-%Y") as invoice_date, DATE_FORMAT(visit_time, "%d-%m-%Y %h:%i") as visit_time, DATE_FORMAT(visit_time, "%Y-%m-%d") as sked_date');
        $this->db->join('business','business.id_business = invoice.business_id');
        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->where('invoice.balance >', 0);
        $this->db->where('invoice.is_recovery', 'Yes');
        $this->db->where('invoice.invoice_status=', 'valid');
      //  $this->db->where('invoice_date >= ', $startdate.' 00:00');
      //  $this->db->where('invoice_date <= ', $enddate.' 23:59'); 
        $query = $this->db->get('invoice');
        
        return $query->result_array();
    }
    
    function loyaltyredemption($startdate, $enddate, $customerid=null, $business_id=null){

        
        $sql1="SELECT account_head_id FROM account_event_mapping
                where account_event_id = 1 and entity_name = 'loyalty_amount' 
                and business_id=".$this->session->userdata('businessid')." ;";
        $query=$this->db->query($sql1);
        $result = $query->row();
        $account_head = $result->account_head_id;
        if(LOYALTY_VOUCHER==true){
             $sql="SELECT customers.id_customers, customers.customer_name, customers.customer_cell, ifnull(customers.customer_card,'') card, 
                customers.customer_email, customers.customer_address, 
                date_format(customer_birthday,'%d-%m-%Y') customer_birthday, 
                date_format(customer_anniversary,'%d-%m-%Y') customer_anniversary, 
                invoice.remarks,
                ifnull(discount,0) Discounts,                
                ifnull(vouchers.earned,0) earned, ifnull(vouchers.used,0) used,
                ifnull(vouchers.loyaltypoints,0) loyalty_points,
                invoice.created_by, invoice.id_invoice, invoice.invoice_type,
                date_format(invoice_date,'%d-%m-%Y') as invoice_date
                FROM customers                
                join invoice on customer_id=customers.id_customers 
                 LEFT JOIN
                (SELECT id_account_vouchers, invoice_id,
                    business_partner_id as customer_id ,
                    ifnull(SUM(credit),0) as earned,
                    ifnull(SUM(debit),0) as used,
                    ifnull(SUM(credit) - SUM(debit),0) as loyaltypoints
                    from account_vouchers 
                    join account_voucher_detail on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id
                    where account_vouchers.business_partner=1 and account_vouchers.voucher_status='Active'
                    and account_head_id=".$account_head." 
                    group by id_account_vouchers, account_vouchers.business_partner_id) as vouchers
                on vouchers.customer_id = customers.id_customers and invoice.id_invoice = vouchers.invoice_id
                where  invoice_status='valid' and id_customers=".$customerid."
                and date(invoice_date)>='$startdate' and date(invoice_date) <= '".$enddate."'
                ";
                $query = $this->db->query($sql);
                return $query->result_array();

        }else{

            $sql="SELECT customers.customer_name, customers.customer_cell, ifnull(customers.customer_card,'') card, 
                    customers.customer_email, customers.customer_address, 
                    date_format(customer_birthday,'%d-%m-%Y') customer_birthday, 
                    date_format(customer_anniversary,'%d-%m-%Y') customer_anniversary, 
                    invoice.remarks as remarks, 
                    invoice.created_by as created_by,  
                    ifnull(paid_amount,0) Purchases, ifnull(discount,0) Discounts, ifnull(balance,0) balance ,
                    ifnull(loyalty_earned,0) earned, ifnull(loyalty_used,0) used,
                    invoice.id_invoice as id_invoice, date_format(invoice_date,'%d-%m-%Y') invoice_date, 
                    invoice_type
                    FROM customers 
                    join invoice on invoice.customer_id = customers.id_customers
                    where invoice.invoice_status='valid' and id_customers=".$customerid;
            
            $query = $this->db->query($sql);
            return $query->result_array();
        }
    }
    
    function sharedcustomers($startdate, $enddate, $business_id=null){
        
        
        $this->db->select('*, loyalty_used, DATE_FORMAT(invoice_date, "%d-%m-%Y") as invoice_date, DATE_FORMAT(visit_time, "%d-%m-%Y %h:%i") as visit_time, DATE_FORMAT(visit_time, "%Y-%m-%d") as sked_date');
        $this->db->join('customers','customers.id_customers = invoice.customer_id');
        $this->db->join('business','business.id_business = customers.business_id', 'left');
        
        
        $this->db->where('invoice.invoice_status=', 'valid');
        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->where('customers.business_id !=', $this->session->userdata('businessid'));
        if($business_id != null && $business_id>0){
            $this->db->where('customers.business_id =',$business_id); 
        }
        $this->db->where('invoice_date >= ', $startdate.' 00:00');
        $this->db->where('invoice_date <= ', $enddate.' 23:59'); 
        $query = $this->db->get('invoice');
        //echo $query; exit();
        return $query->result_array();
    }
    
    
    
    function careofcustomers($startdate, $enddate, $business_id=null){
        
        
        $this->db->select("*, date_format(customer_anniversary, '%d-%m-%Y %h:%i') as 'anv', date_format(created_on, '%d-%m-%Y %h:%i') as 'created', month(created_on) as 'm'");
        //$this->db->where('created_on >=', $startdate." 00:00");
        //$this->db->where('created_on <=', $enddate." 23:59");
        $this->db->where('ifnull(customer_careof,"") !=','');
        //$this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->order_by('month(created_on)','Desc');
        $query = $this->db->get('customers');
        return $query->result();
    }
    
    
    function requested($startdate, $enddate, $business_id=null, $sh=false){
        
        $this->db->select('id_invoice, invoice_number, invoice_type, customer_name, staff_name, invoice_details.service_category, invoice_details.service_name,'
                . ' invoice_details.price, round(((100*invoice.discount)/invoice.sub_total) ,2) as invoice_discount_percentage,
             invoice_details.discount service_discount,
            round(((invoice_details.price-invoice_details.discount)*(100*invoice.discount)/invoice.sub_total)/100,2) as invoice_discount, 
            round(invoice_details.discount+ (((invoice_details.price-invoice_details.discount)*(100*invoice.discount)/invoice.sub_total)/100), 2) as total_discount,
            round(invoice_details.price - (invoice_details.discount+ (((invoice_details.price-invoice_details.discount)*(100*invoice.discount)/invoice.sub_total)/100)),2)
            as discounted_price, DATE_FORMAT(invoice_date, "%d-%m-%Y") as invoice_date', false);
        $this->db->join('invoice_staff', 'invoice_staff.invoice_id = invoice.id_invoice');
        $this->db->join('invoice_details', 'invoice_staff.invoice_detail_id = invoice_details.id_invoice_details');
        //$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('invoice_date >=', $startdate." 00:00");
        $this->db->where('invoice_date <=', $enddate." 23:59");
        $this->db->where('invoice.invoice_status=', 'valid');
        
         if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('invoice_seq > ', 0);
        }
        $this->db->where('invoice_staff.requested=', 'Yes');
        
        $query = $this->db->get('invoice');
        return $query->result_array();
    }
    function repeated_customers($startdate, $enddate, $sh=false){
        
        /*Repeated Customers needs more work*/
        $sql="SELECT *, date_format(invoice_date,'%d-%m-%Y %H:%i:%s') invoice_date, date_format(visit_time,'%d-%m-%Y %H:%i:%s') visit_date,'Clients of January 2019' as 'Month' 
                FROM invoice
                where invoice_date >= '".$startdate." 00:00:00' and invoice_date <='".$enddate." 23:59:59'
                and invoice.business_id=".$this->session->userdata('businessid')."  
                and customer_id in 
                (
                        select customer_id from invoice 
                        where invoice_date > '".$startdate." 00:00:00'
                        and invoice.business_id = ".$this->session->userdata('businessid')."
                )
                order by customer_id, invoice_date;";
        
        $query = $this->db->query($sql);
        return $query->result_array();
        
    }
    
    
    function non_returning_customers($startdate, $enddate, $days, $servicecategory){
        $sql="select distinct customers.customer_name, customers.customer_cell,
            invoice.invoice_date as date, invoice_details.service_name, invoice_details.staff 
            FROM invoice join customers on customers.id_customers = invoice.customer_id 
            join business on business.id_business = invoice.business_id 
            join invoice_details on invoice_details.invoice_id = invoice.id_invoice 
            where DATEDIFF(now(), visit_time) <= ". $days ." and upper(service_category) = '".$servicecategory."' 
            and invoice.invoice_status = 'valid' 
            and invoice.business_id=".$this->session->userdata('businessid')."  
            and customers.id_customers not in (
                select id_customers 
                FROM invoice join customers on customers.id_customers = invoice.customer_id 
                join invoice_details on invoice_details.invoice_id = invoice.id_invoice 
                where DATEDIFF(now(), visit_time) > ". $days ." and upper(service_category) = '".$servicecategory."' 
                and invoice.invoice_status = 'valid' and invoice.business_id=".$this->session->userdata('businessid').")
            order by 1, 2";
        
        $query = $this->db->query($sql);
        return $query->result_array();
        
    }
    
    function staff_utilization($startdate, $enddate){
       
            
        $sql="SELECT staff_id, staff_fullname, customer_id, customer_name, service_name, visit_service_start, 
            visit_service_end,
            SEC_TO_TIME(
                    sum(Time_To_Sec(
                            CONCAT(   
                               MOD(HOUR(TIMEDIFF(date_format(visit_service_start, '%H:%i:%s'), date_format(visit_service_end, '%H:%i:%s'))), 24), ':',
                               MINUTE(TIMEDIFF(date_format(visit_service_start, '%H:%i:%s'), date_format(visit_service_end, '%H:%i:%s')))
                            )
                    ))
            )
            AS TimeDiff           
            from visit_services
            join visit_service_staffs on visit_service_staffs.visit_service_id= visit_services.id_visit_services
            join staff on staff.id_staff = visit_service_staffs.staff_id
            join invoice on invoice.visit_id = visit_services.customer_visit_id
            Where date_format(visit_service_start, '%Y-%m-%d') = date_format('".$startdate."', '%Y-%m-%d')             
            and staff.business_id= ".$this->session->userdata('businessid')." 
                and invoice.invoice_status = 'valid' and visit_service_status='Active' 
            group by staff_id, staff_fullname, customer_id, customer_name, service_name
            order by 1,2,3,4 desc";
      
        $query = $this->db->query($sql);
        return $query->result_array();
    }
    
    
    function staff_utilization_summary($startdate, $enddate){
        $sql = "SELECT staff_id, staff_fullname, '".$startdate."' as 'from', '".$enddate."' as 'to',
            SEC_TO_TIME(
                    sum(Time_To_Sec(
                             CONCAT(   
                               MOD(HOUR(TIMEDIFF(date_format(visit_service_start, '%H:%i:%s'), date_format(visit_service_end, '%H:%i:%s'))), 24), ':',
                               MINUTE(TIMEDIFF(date_format(visit_service_start, '%H:%i:%s'), date_format(visit_service_end, '%H:%i:%s')))
                            )
                    ))
            )
            AS utilized        ,
            DATEDIFF('".$enddate."', '".$startdate."') + 1 AS dutyhours
            from visit_services
            join visit_service_staffs on visit_service_staffs.visit_service_id= visit_services.id_visit_services
            join staff on staff.id_staff = visit_service_staffs.staff_id
            join invoice on invoice.visit_id = visit_services.customer_visit_id
            Where  invoice.invoice_status = 'valid'  and visit_service_status='Active' and
		date(visit_service_start) >= '".$startdate."'        
		and date(visit_service_start) <= '".$enddate."'      
            and staff.business_id= ".$this->session->userdata('businessid')." 
            group by staff_id, staff_fullname
            order by 1,2 desc";
        
        $query = $this->db->query($sql);
        return $query->result_array();
    }
    
    function retained_amount($startdate, $enddate, $type){
       $sql = " select id_invoice, customers.customer_name, customers.customer_cell, payment_mode, 
                reference_invoice_number,
                retained_amount, date_format(invoice_date,'%d-%m-%Y %h:%i') as invoice_date, 
                invoice.created_by, retained_amount_used, invoice_type
                from invoice
                join customers on customers.id_customers = invoice.customer_id
                where ";
        if($type=='retained'){
            $sql .= " retained_amount > 0";
        } else {
            $sql .= " retained_amount_used > 0";
        }
        $sql .= " and invoice_status = 'valid'
                and invoice_date >= '".$startdate." 00:00:00'
                and invoice_date <= '".$enddate." 23:59:59'
                    and invoice.business_id = ".$this->session->userdata('businessid')."
                order by invoice_date desc";
       
        $query = $this->db->query($sql);
        
        return $query->result_array();
        
               
    }
    
    function staffblocking_summary($startdate, $enddate, $staffid){
        $sql="SELECT id_staff, staff_name, 
            block_event_name, count(id_block_events) as blockings,

            SEC_TO_TIME( 
                    SUM( 
                            TIME_TO_SEC( 
            timediff(substr(block_staff_time.end_time, position('T' in block_staff_time.end_time) +1,8), substr(block_staff_time.start_time, position('T' in block_staff_time.start_time) +1,8)) 
                            ) 
                    )
             ) AS total_block_time  

            FROM block_staff_time
            join block_events on block_events.id_block_events = block_staff_time.block_event_id
            join staff on staff.id_staff = block_staff_time.staff_id
            Where staff.business_id = ".$this->session->userdata('businessid')." 
            and block_staff_time.start_time >= '".$startdate." 00:00:00'
            and block_staff_time.start_time<= '".$enddate." 23:59:59' 
            and staff.staff_scheduler='On'
             ";
            if($staffid>0){
                 $sql.="  and id_staff = ".$staffid;
            }

            $sql.=" group by id_staff, id_block_events
            order by id_staff, id_block_events";
        
              
        $query = $this->db->query($sql);
            
        
        return $query->result_array();
    }
    
    function staffblocking($startdate, $enddate, $staffid){
        
        $sql="SELECT id_staff, staff_name, block_event_name, date_format(start_time,'%d-%m-%Y') day, block_staff_time.remarks,
            substr(start_time, position('T' in start_time) +1,8) start_time,
            substr(block_staff_time.end_time, position('T' in block_staff_time.end_time) +1,8) end_time,
            timediff(substr(block_staff_time.end_time, position('T' in block_staff_time.end_time) +1,8), substr(block_staff_time.start_time, position('T' in block_staff_time.start_time) +1,8)) timediff 
            FROM block_staff_time
            join block_events on block_events.id_block_events = block_staff_time.block_event_id
            join staff on staff.id_staff = block_staff_time.staff_id
            Where staff.business_id = ".$this->session->userdata('businessid')." 
            and block_staff_time.start_time >= '".$startdate." 00:00:00'
            and block_staff_time.start_time<= '".$enddate." 23:59:59' 
            and staff.staff_scheduler='On' ";
        if($staffid>0){
          $sql.="  and id_staff = ".$staffid;
        }
        $query = $this->db->query($sql);
            
        
        return $query->result_array();
        
    }
    
    function onlineappointments($startdate, $enddate){
        
        $sql="SELECT id_customer_visits, customers.customer_name, customers.customer_cell, 
            date(customer_visits.customer_visit_date) 'booked_on', 
            customer_visits.visit_status, 
            date_format(visit_services.visit_service_start, '%d-%m-%Y %H:%i') 'appointment_time',
            visit_services.service_name, visit_service_staffs.staff_name 'assigned_to'
            FROM `customer_visits`
            join customers on customers.id_customers = customer_visits.customer_id
            join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits
            and visit_service_status='Active' 
            join visit_service_staffs on visit_service_staffs.visit_service_id = visit_services.id_visit_services
            and visit_service_staff_status='Active' 
            where customer_visits.created_by = 'Online'              
            and customer_visits.business_id = ".$this->session->userdata('businessid')." 
            and date(customer_visits.customer_visit_date) >= '".$startdate."'
            and date(customer_visits.customer_visit_date) <= '".$enddate."' 
            and ifnull(visit_services.visit_service_start, '') != ''    
            group by customer_id, date(customer_visit_date)";
        
        $query = $this->db->query($sql);
        return $query->result_array();
        
    }

    function crossselling_report($startdate, $enddate){
        
        $sql = "SELECT id_visit_services, invoice_id, invoice_details.final_price, 
                customers.customer_name, id_customer_visits, date_format(visit_service_start, '%d-%m-%Y') as visit_date, visit_services.crosssell as cross_sold_by, 
                visit_service_staffs.staff_name as 'serviced_by', visit_services.service_id, visit_services.service_name, visit_services.service_flag, 
                visit_services.id_service_category, 
                s_category, s_rate, s_type, visit_services.id_service_type
                FROM visit_services
                JOIN customer_visits on customer_visits.id_customer_visits = visit_services.customer_visit_id
                JOIN visit_service_staffs on id_visit_services = visit_service_id AND visit_service_staffs.additional_staff='No'
                JOIN invoice_details on visit_services.id_visit_services = invoice_details.visit_service_id
                JOIN customers on id_customers = customer_visits.customer_id
                WHERE ifnull(visit_services.crosssell,'none') !='none'
                AND customer_visits.visit_status = 'invoiced'
                AND visit_services.visit_service_status='Active'
                AND date(customer_visits.customer_visit_date) >= '".$startdate."'
                AND date(customer_visits.customer_visit_date) <= '".$enddate."' 
                AND customer_visits.business_id = ".$this->session->userdata('businessid').";";

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

    function bank_payments($startdate, $enddate){
        $sql = "select id_invoice, invoice_type, date_format(invoice_date,'%d-%m-%Y') as invoice_date, customer_name, customer_cell, invoice.paid_amount, invoice_status,
                case when instrument_number like 'Online%' then 'Online' Else payment_mode END as payment_mode, invoice.instrument_number from invoice
                where invoice.payment_mode='check' and invoice_status='valid'
                and business_id = ".$this->session->userdata('businessid')."
                and date(invoice_date)>='".$startdate."' and date(invoice_date)<='".$enddate."';";

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

    }

    function operator_report($start, $end, $roleid){

        $sql = "select customer_visits.id_customer_visits, customer_visits.created_by visit_created_by, date_format(customer_visits.created_on, '%d-%m-%Y') visit_created_on, 
        id_invoice, customers.customer_name, customers.customer_cell, invoice.created_by invoice_created_by, date_format(invoice.invoice_date, '%d-%m-%Y') as invoice_created_on, invoice_details.service_type, invoice_details.service_category, invoice.paid_amount
        from customer_visits   
        join customers on customer_visits.customer_id=customers.id_customers
        join invoice on customer_visits.id_customer_visits = invoice.visit_id
        join invoice_details on invoice.id_invoice=invoice_details.invoice_id
        join users on users.user_name = customer_visits.created_by
        join user_roles on users.id_users = user_roles.user_id
        join roles on roles.id_roles = user_roles.role_id
        where date(invoice.invoice_date) >= '".$start."' and date(invoice.invoice_date) <= '".$end."'  
        and roles.id_roles = ".$roleid."
        ORDER BY `customer_visits`.`id_customer_visits`, invoice.id_invoice ASC;";

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

    }

    function cancelled_advances($startdate, $enddate){
        $sql = "SELECT visit_advance.* , account_vouchers.voucher_status, account_vouchers.cancelled_by, 
        account_vouchers.cancelled_on, customer_visits.visit_status
        FROM visit_advance
        join account_vouchers on account_vouchers.visit_advance_id = visit_advance.id_visit_advance
        join customer_visits on customer_visits.id_customer_visits=visit_advance.customer_visit_id
        where date(visit_advance.advance_date)>='".$startdate."' 
        and date(visit_advance.advance_date)<='".$enddate."' 
        and customer_visits.business_id = ".$this->session->userdata('businessid')."
        and  account_vouchers.voucher_status!='Active';";


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

    }

    function dispatches_against_requests($startdate, $enddate){

        $sql = "select dispatch_notes.*, business_products.product, a.* from dispatch_notes
                join business_products on business_products.id_business_products=dispatch_notes.product_id
                join
                (select dispatch_request.id_dispatch_request, dispatch_request.dispatch_request_date, dispatch_request.service_id, dispatch_request.created_on as req_created_on, dispatch_request.created_by as req_created_by, dispatch_request.dispatch_request_status as request_status, dispatch_request.product_id req_product_id, dispatch_request.product_name as req_product_name, dispatch_request.product_qty req_qty, dispatch_request.product_unit req_unit,  id_customer_visits, visit_services.service_name, customer_visits.visit_status, customers.customer_name, customer_visits.created_by as visit_created_by, date_format(visit_services.visit_service_start,'%d-%m-%Y %H:%i') as service_start from dispatch_request
                join customer_visits on customer_visits.id_customer_visits=dispatch_request.customer_visit_id
                join customers on customers.id_customers=customer_visits.customer_id
                join visit_services on visit_services.id_visit_services = dispatch_request.visit_service_id
                Where customer_visits.business_id = ".$this->session->userdata('businessid')." and date(dispatch_request_date) >= '".$startdate."'  and date(dispatch_request_date) < '".$enddate."') as a
                ON a.id_dispatch_request = dispatch_notes.request_id;";
                
        $query = $this->db->query($sql);
        return $query->result_array();

    }
    
}
