<?php

class Staff_model extends CI_Model {

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

    function get_deduction_policies(){
        $this->db->select("*");
        $query = $this->db->get('deduction_policy');
        
        return $query->result_array();
    }
    
    function get_present_staff() {
        $today = date('Y-m-d');
        $tomorrow = date('Y-m-d H:i:s', strtotime('tomorrow'));

        $this->db->select("*, DATE_FORMAT(time_in,'%h:%i %p') as 'timein'");
        $this->db->join('staff', 'staff.id_staff = staff_attendance.staff_id');
        $this->db->where('staff.staff_active =', 'Y');
        $this->db->where("ifnull(staff_attendance.time_out,'')=''");
        $this->db->where('staff_attendance.time_in >', $today);
        $this->db->where('staff_attendance.time_in <', $tomorrow);
        $this->db->where('staff_attendance.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('staff_attendance');
        
        
        return $query->result_array();
    }

    function get_available_staff() {
        $today = date('Y-m-d');
        $tomorrow = date('Y-m-d H:i:s', strtotime('tomorrow'));

        $this->db->select("*, DATE_FORMAT(time_in,'%h:%i %p') as 'timein'");
        $this->db->join('staff', 'staff.id_staff = staff_attendance.staff_id');
        $this->db->where("ifnull(staff_attendance.time_out,'')=''");
        $this->db->where('staff_attendance.time_in >', $today);
        $this->db->where('staff_attendance.time_in <', $tomorrow);
        $this->db->where('staff_attendance.business_id', $this->session->userdata('businessid'));
        $this->db->where('staff_attendance.staff_available', '');
        $query = $this->db->get('staff_attendance');

        
        return $query->result_array();
    }

    function get_absent_staff() {

        $today = date('Y-m-d');
        $ids = [];
        $this->db->select('staff_id');
        $this->db->where('time_in >', $today);
        $this->db->where("ifnull(time_out,'')=''");
        $this->db->where('staff_attendance.business_id', $this->session->userdata('businessid'));
        $query1 = $this->db->get('staff_attendance');

        foreach ($query1->result() as $row) {
            array_push($ids, $row->staff_id);
        }

        $this->db->select('*');
        if (sizeof($ids) > 0) {
            $this->db->where_not_in("id_staff", $ids);
            $this->db->where('staff.staff_active =', 'Y');
        }
        $query = $this->db->get('staff');

        
        return $query->result_array();
    }

    function check_staff_status() {

        $today = date('Y-m-d');
        $tomorrow = date('Y-m-d H:i:s', strtotime('tomorrow'));
        $statff_id = $this->input->post('id', TRUE);

        $this->db->select("time_out");
       // $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('staff_id', $statff_id);
        $this->db->where('time_in >', $today);
        $this->db->where('time_in <', $tomorrow);
        $this->db->where('staff_available', '');

        $query = $this->db->get('staff_attendance');
        
        
        return $query->row();
    }

    function update_timein($mytime=null) {
        //echo $mytime; exit();
        
        if(null !== $this->input->post('mdate')){
            
            $mySQLDate = date('Y-m-d H:i:s');
            $mySQLTime = date('H:i:s');
            
            $data = array(
                'business_id' => $this->session->userdata('businessid'),
                'staff_id' => $this->input->post('id', TRUE),
                'time_in' => $this->input->post('mdate').' '.$mySQLTime
            );

            $this->db->insert('staff_attendance', $data);
            
            
        } else {
        
            if($mytime!==null)  {
                $mySQLDate = $mytime;
                $m = explode(" ", $mySQLDate);
                $mySQLTime=$m[1];

                $this->db->select('*');
                $this->db->where('staff_id', $this->input->post('id', TRUE));
                $this->db->where('date(time_in)', "'".$m[0]."'", false);
                $query = $this->db->get('staff_attendance');

                $exists = $query->row();        

                if(isset($exists->time_in) && $exists->time_in !==null){

                    $this->db->where('id_staff_attendance', $this->input->post('id_attendance'));
                    $this->db->set('time_in', $mySQLDate);
                    $this->db->update('staff_attendance');

                } else {


                    $data = array(
                        'business_id' => $this->session->userdata('businessid'),
                        'staff_id' => $this->input->post('id', TRUE),
                        'time_in' => $mySQLDate
                    );

                    $this->db->insert('staff_attendance', $data);
                }

            } else {

                $mySQLDate = date('Y-m-d H:i:s');
                $mySQLTime = date('H:i:s');

                $data = array(
                    'business_id' => $this->session->userdata('businessid'),
                    'staff_id' => $this->input->post('id', TRUE),
                    'time_in' => $mySQLDate
                );

                $this->db->insert('staff_attendance', $data);
            }

        }
        
        return $mySQLTime;
    }

    function update_timeout($mytime=null) {
       //exit();
        if(null !== $this->input->post('mdate')){
            
             $mySQLDate = date('Y-m-d H:i:s');
                $mySQLTime = date('H:i:s');

                $data = array(
                    'time_out' => $this->input->post('mdate').' '.$mySQLTime
                );

                $this->db->set($data);
                $this->db->where('id_staff_attendance', $this->input->post('id_attendance'));
                //$this->db->where('staff_id', $this->input->post('id', TRUE));
                $this->db->where("ifnull(time_out,'')=''");

                $this->db->update('staff_attendance');
            
            
        } else {
        
            if($mytime!==null)  {
                $mySQLDate = $mytime;
                $m = explode(" ", $mySQLDate);
                $mySQLTime=$m[1];

                $this->db->select('*');
                $this->db->where('staff_id', $this->input->post('id', TRUE));
                $this->db->where('date(time_in)', "'".$m[0]."'", false);
                $query = $this->db->get('staff_attendance');

                $exists = $query->row();        

                if(isset($exists->time_out) && $exists->time_out !==null){

                    $this->db->where('id_staff_attendance', $this->input->post('id_attendance'));
                    $this->db->set('time_out', $mySQLDate);
                    $this->db->update('staff_attendance');
                } else {


                    $data = array(
                        'business_id' => $this->session->userdata('businessid'),
                        'staff_id' => $this->input->post('id', TRUE),
                        'time_out' => $mySQLDate
                    );

                    $this->db->insert('staff_attendance', $data);
                }
            }else{

                $mySQLDate = date('Y-m-d H:i:s');
                $mySQLTime = date('H:i:s');

                $data = array(
                    'time_out' => $mySQLDate
                );

                $this->db->set($data);
                $this->db->where('id_staff_attendance', $this->input->post('id_attendance'));
                //$this->db->where('staff_id', $this->input->post('id', TRUE));
                $this->db->where("ifnull(time_out,'')=''");

                $this->db->update('staff_attendance');
            }
        }
        
        return $mySQLTime;
        
    }

    function all_staff() {
        
        $this->db->select("*");
        $this->db->join("business","business.id_business = staff.business_id");
        
        if($this->session->userdata("ho")=='No'){
            $this->db->where("staff.business_id", $this->session->userdata('businessid'));
        }
        
        $this->db->order_by('staff_order', 'Asc');
        $query = $this->db->get('staff');
        
        return $query->result_array();
    }
    
    function business_staff($business_id) {
        
        $this->db->select("*");
        $this->db->where("staff.business_id", $business_id);
        $this->db->where("staff.staff_active", 'Y');
         $this->db->order_by('staff_fullname', 'ASC');
        $query = $this->db->get('staff');
        
        
        return $query->result_array();
    }
    
     function business_staff_cls($business_id) {
        
        $this->db->select("*");
        $this->db->where("staff.business_id", $business_id);
        $this->db->where("staff.staff_active", 'Y');
        $this->db->order_by('staff_fullname', 'ASC');
        $query = $this->db->get('staff');
        
        
        return $query->result();
    }
    
    
    public function get_scheduler_staff(){
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('staff_scheduler', 'On');
                
        $this->db->order_by('staff_fullname', 'ASC');
        $query = $this->db->get('staff');

        return $query->result();
    }
    
    function get_active_scheduler_staff($business_id) {
        
      
        //echo $today;
        $this->db->select("*");
        $this->db->where("staff.business_id", $business_id);
        $this->db->where("staff.staff_active", 'Y');
        $this->db->where("staff.staff_scheduler", 'On');
        // if(defined('HIDE_OFFDAY')){if(HIDE_OFFDAY==true){   
        //     $today = date('D');          
        //     $this->db->where("staff.week_day_off NOT LIKE", "'%".$today."%'", false);
        // }}

        $query = $this->db->get('staff');
       // echo $query; exit();
        return $query->result_array();
    }

    function all_staff_list(){
        
        if($this->session->userdata('common_products')=='Yes'){
            $where = "(staff.business_id=". $this->session->userdata('businessid') ." OR staff.staff_shared = 'Yes') ";
        }else{
            $where="staff.business_id = ".$this->session->userdata('businessid');
        }
        
        $this->db->select("*");
        $this->db->where($where);
        $this->db->order_by('staff_active, staff_fullname', 'Asc');
        $query = $this->db->get('staff');
        
        
        return $query->result_array();
    }
    
    function add_staff() {
       // exit();
        
        $week_offs = $this->input->post('week_day_off', TRUE);
        $week_day_off ='';
        
        if($this->input->post('week_day_off', TRUE) != ''){
            foreach($week_offs as $wo){
                $week_day_off.= $wo.', ';
            }
        }
        
        $data = array(
            'business_id' => $this->session->userdata('businessid'),
            'staff_firstname' => $this->input->post('staff_firstname', TRUE),
            'staff_lastname' => $this->input->post('staff_lastname', TRUE),
            'staff_fullname' => $this->input->post('staff_fullname', TRUE),
            'staff_cell' => $this->input->post('staff_cell', TRUE),
            'staff_phone1' => $this->input->post('staff_phone1', TRUE),
            'staff_phone2' => $this->input->post('staff_phone2', TRUE),
            'staff_address' => $this->input->post('staff_address', TRUE),
            'staff_eid' => $this->input->post('staff_eid', TRUE),
            'staff_email' => $this->input->post('staff_email', TRUE),
            'staff_salary' => $this->input->post('staff_salary', TRUE),
            'salary_type' => $this->input->post('salary_type', TRUE),
            'staff_work_min' => $this->input->post('staff_work_min', TRUE),
            'week_day_off' => $week_day_off,
            'staff_annual_leaves' => $this->input->post('staff_annual_leaves', TRUE),            
            'commission_mode'=> $this->input->post('commission_mode', TRUE),
            'deduction_policy'=> $this->input->post('deduction_policy', TRUE),
            'staff_commission_perc'=> $this->input->post('staff_commission_perc', TRUE),
            'commission_target'=> $this->input->post('commission_target', TRUE),
            'provident_fund_rate'=> $this->input->post('provident_fund_rate', TRUE),
            'salary_monthly_tax'=> $this->input->post('salary_monthly_tax', TRUE),
            'floor_id'=> $this->input->post('floor_id', TRUE),
            'floor'=> $this->input->post('floor', TRUE),
            'next_of_kin_name'=> $this->input->post('next_of_kin_name', TRUE),
            'next_of_kin_number'=> $this->input->post('next_of_kin_number', TRUE),
            'date_of_birth'=> $this->input->post('date_of_birth', TRUE),
            'contract_validity'=> $this->input->post('contract_validity', TRUE)

        );
        // print_r($data);die;
        $this->db->insert('staff', $data);
        
        $staffid= $this->db->insert_id();
        
         // Unescape the string values in the JSON array
        $tableData = stripcslashes($this->input->post('TableData'));        
        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        // now $tableData can be accessed like a PHP array
        
        foreach($tableData as $row){
            
            $data = array(
                'staff_id'  => $staffid,
                'allowance_id' => $row['allowance_id'],
                'allowance_amount' => $row['allowance_amount']  ,
                'staff_allowance_status' => 'Active',
                'created_by' => $this->session->userdata('username')
            );
            
            $this->db->insert('staff_allowance', $data);
            
        }
        return $staffid;
    }

    function update_staff() {
        //exit();
        
        if($this->input->post('business_id') != null){
           $business_id = $this->input->post('business_id');
        }else{
            $business_id = $this->session->userdata('businessid');
        }
        
        $week_offs = $this->input->post('week_day_off', TRUE);
        $week_day_off ='';
        
        if(null != $week_offs){
            foreach($week_offs as $wo){
                $week_day_off.= $wo.', ';
            }
        }
        
        $data = array(
            'business_id' => $business_id,
            'staff_firstname' => $this->input->post('staff_firstname', TRUE),
            'staff_lastname' => $this->input->post('staff_lastname', TRUE),
            'staff_fullname' => $this->input->post('staff_fullname', TRUE),
            'staff_cell' => $this->input->post('staff_cell', TRUE),
            'staff_phone1' => $this->input->post('staff_phone1', TRUE),
            'staff_phone2' => $this->input->post('staff_phone2', TRUE),
            'staff_address' => $this->input->post('staff_address', TRUE),
            'staff_eid' => $this->input->post('staff_eid', TRUE),
            'staff_email' => $this->input->post('staff_email', TRUE),
            'staff_salary' => $this->input->post('staff_salary', TRUE),
            'salary_type' => $this->input->post('salary_type', TRUE),
            'staff_work_min' => $this->input->post('staff_work_min', TRUE),
            
            'week_day_off' => $week_day_off,
            'staff_annual_leaves' => $this->input->post('staff_annual_leaves', TRUE),    
            'commission_mode'=> $this->input->post('commission_mode', TRUE),
            'deduction_policy'=> $this->input->post('deduction_policy', TRUE),
            'staff_commission_perc'=> $this->input->post('staff_commission_perc', TRUE),
            'commission_target'=> $this->input->post('commission_target', TRUE),
            'provident_fund_rate'=> $this->input->post('provident_fund_rate', TRUE),
            'salary_monthly_tax'=> $this->input->post('salary_monthly_tax', TRUE),
            'staff_designation'=> $this->input->post('staff_designation', TRUE),
            'staff_department'=> $this->input->post('staff_department', TRUE),
            'staff_cnic'=> $this->input->post('staff_cnic', TRUE),
            'staff_date_of_joining'=> $this->input->post('staff_date_of_joining', TRUE),
            'staff_bank_account'=> $this->input->post('staff_bank_account', TRUE),
            'staff_bank_account_title'=> $this->input->post('staff_bank_account_title', TRUE),
            'staff_bank'=> $this->input->post('staff_bank', TRUE),
            'day_start_time'=> $this->input->post('start_time', TRUE),
            'day_end_time'=> $this->input->post('end_time', TRUE),
            'floor_id'=> $this->input->post('floor_id', TRUE),
            'floor'=> $this->input->post('floor', TRUE),

            'next_of_kin_name'=> $this->input->post('next_of_kin_name', TRUE),
            'next_of_kin_number'=> $this->input->post('next_of_kin_number', TRUE),
            'date_of_birth'=> $this->input->post('date_of_birth', TRUE),
            'contract_validity'=> $this->input->post('contract_validity', TRUE)
            
        );
        
        //print_r($data);die;
        $this->db->set($data);
        $this->db->where('id_staff', $this->input->post('id_staff', TRUE));
        $this->db->update('staff');
        
        
        //Deactivate all allowances for this staff
        $this->db->set('staff_allowance_status','InActive');
        $this->db->set('cancelled_by', $this->session->userdata('username'));
        $this->db->set('cancelled_on', date('Y-m-d H:i:s'));
        $this->db->where('staff_id', $this->input->post('id_staff', TRUE));
        $this->db->update('staff_allowance');
        
        // Unescape the string values in the JSON array
        $tableData = stripcslashes($this->input->post('TableData'));        
        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        // now $tableData can be accessed like a PHP array
        
        foreach($tableData as $row){
            $data = array(
                'staff_id'  => $this->input->post('id_staff', TRUE),
                'allowance_id' => $row['allowance_id'],
                'allowance_amount' => $row['allowance_amount'],
                'staff_allowance_status' => 'Active'
            );
            $this->db->insert('staff_allowance', $data);
        }
        
        
        return $this->input->post('id_staff', TRUE);
    }

    function update_staff_scheduler() {
                
        $data = array(
            'staff_scheduler' => $this->input->post('staff_scheduler', TRUE)
        );
        
        $this->db->set($data);
        $this->db->where('id_staff', $this->input->post('id_staff', TRUE));
        $this->db->update('staff');
        
        
        return $this->input->post('id_staff', TRUE);
    }
    
     function update_staff_shared() {
                
        $data = array(
            'staff_shared' => $this->input->post('staff_shared', TRUE)
        );
        
        $this->db->set($data);
        $this->db->where('id_staff', $this->input->post('id_staff', TRUE));
        $this->db->update('staff');
        
        
        return $this->input->post('id_staff', TRUE);
    }
    
    function staff_status() {
        $data = array(
            'staff_active' => $this->input->post('staffactive', TRUE),
            'staff_comment' => $this->input->post('staff_comment', TRUE)
        );
        $this->db->set($data);
        $this->db->where('id_staff', $this->input->post('id_staff_status', TRUE));
        $this->db->update('staff');
        
        
        return $this->input->post('id_staff_status', TRUE);
    }

    function image_staff($image = NULL) {
        $data = array(
            'staff_image' => $image ? $image : NULL
        );
        //print_r($data);die;
        $this->db->set($data);
        $this->db->where('id_staff', $this->input->post('id_image_staff', TRUE));
        $this->db->update('staff');
        
        
        return $this->input->post('id_image_staff', TRUE);
    }

    function update_order_function($id, $orderid) {

        $data = array(
            'staff_order' => $orderid
        );
        $this->db->where('staff.id_staff', $id);
        $this->db->where('staff.business_id', $this->session->userdata('businessid'));
        $this->db->update('staff', $data);
        
        
        return $id;
    }

    function changelistorder1() {
        $staff_orderid = $this->input->post('staff_order', TRUE);
        $staff_orderid = explode(',', $staff_orderid);
        $count = 1;
        print_r($staff_orderid);
        die;
        $data = array();
        for ($i = 0; $i <= sizeof($staff_orderid); $i++) {

            $data[] = array(
                'staff_order' => $count,
                'staff_id' => $staff_orderid[$i]
            );

//            $this->db->where('staff.id_staff', $staff_orderid[$i]);
//            $this->db->where('staff.business_id', $this->session->userdata('businessid'));
//            $this->db->update('staff', $data);
            $count++;
        }
        print_r($data);
        die;

        return TRUE;
    }

    function changelistorder() {
        $staff_orderid = $this->input->post('staff_order', TRUE);
        $staff_orderid = explode(',', $staff_orderid);
        
        $updateArray = array();

        for ($x = 0; $x < sizeof($staff_orderid); $x++) {

            $updateArray[] = array(
                'id_staff' => $staff_orderid[$x],
                'staff_order' => $x+1
            );
        }
        $this->db->update_batch('staff', $updateArray, 'id_staff');
        
        
        return TRUE;
    }
    
    function edit_staff(){
        $this->db->select('*');
        
        if($this->session->userdata("ho")=='No'){
            $this->db->where('s.business_id', $this->session->userdata('businessid'));
        }
        
        $this->db->where('s.id_staff', $this->input->post('id_staff'));
        $query = $this->db->get('staff s');

       // echo $query;
        return $query->row();
    }
    
    
    function staff_allowances(){
        $condition = "allowances.id_allowances = staff_allowance.allowance_id AND staff_allowance.staff_allowance_status = 'Active' AND staff_allowance.staff_id = ".$this->input->post('id_staff');
            
        $this->db->select('id_allowances, allowance_name, entity_name, id_staff_allowance, staff_id, staff_allowance_status
        , ifnull(allowance_amount,0) as allowance_amount');
        $this->db->join('staff_allowance', $condition, 'left');    
        $this->db->where('allowances.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('allowances');
        
        return $query->result();
    }
    
    function get_active_staff(){
        $where="(s.business_id =". $this->session->userdata('businessid')." OR s.staff_shared='Yes')";
        
        $this->db->select('*');
        $this->db->where($where);
        $this->db->where('s.staff_active', 'Y');
        $this->db->order_by('staff_fullname');
        $query = $this->db->get('staff s');

        
        
        return $query->result_array();
        
    }
    
    function calculate_commissions($month){
        
        $this->db->select("staff_fullname staff_name, staff_id, date_format(staff_service_date, '%M') as 'Month', 
                    date_format(staff_service_date, '%Y') as 'Year', sum(staff_commission) as 'Commission', 
                    count(service_name) as 'Total Services'");
        $this->db->join("invoice", " invoice.id_invoice = staff_services.invoice_id");
        $this->db->join("staff", "staff.id_staff = staff_services.staff_id");
        $this->db->where("invoice_status='valid'");
        $this->db->where('reference_invoice_number <>', 'bad debts');
        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->where('month(staff_service_date)=', $month);
        $this->db->where('ifnull(staff_name,"") <>', '');
        $this->db->group_by("staff_fullname, staff_id,
            date_format(staff_service_date, '%M'),
            date_format(staff_service_date, '%Y') ");
        $query = $this->db->get('staff_services');

        
        return $query->result_array();
    }
    
    public function check_salary_record($staff_id, $month, $year){
        
        $this->db->select("*");
        $this->db->where("staff_id", $staff_id);
        $this->db->where("payment_month", $month);
        $this->db->where("payment_year", $year);
        $this->db->where("payment_type", "Salary");
        $query = $this->db->get("staff_payments");
        
        
        return $query->result_array();
    }
    public function check_commission_record($staff_id, $month, $year){
        
        $this->db->select("*");
            $this->db->where("staff_id", $staff_id);
            $this->db->where("payment_month", $month);
            $this->db->where("payment_year", $year);
            $this->db->where("payment_type", "Commission");
            $query = $this->db->get("staff_payments");
            
            
             return $query->result_array();
    }


    public function update_salaries($data){
                
        $this->db->insert('staff_payments', $data);
        
        return $this->db->insert_id();
        
    }
    
   
    
    public function add_payment(){
        
        $data = array(
            'created_by' => $this->session->userdata('businessid'),
            'staff_id' => $this->input->post('staff_id'),
            'staff_name' => $this->input->post('staff_name'),
            'payment_amount' => $this->input->post('payment_amount'),
            'payment_type' => $this->input->post('payment_type'),
            'payment_mode' =>  $this->input->post('payment_mode'),
            'payment_remarks' => $this->input->post('payment_remarks'),
            'payment_date' => $this->input->post('payment_date'),
            'payment_month' => $this->input->post('payment_month'),
            'payment_year' => $this->input->post('payment_year'),
            'bank_account_id'=> $this->input->post('bank_account_id'),
            'deduction_amount'=>$this->input->post('deduction_amount')
        );

        $this->db->insert('staff_payments', $data);
        
        
        return $this->db->insert_id();
        
    }
    
    public function staff_salary($staffid){
        
//        $sql="SELECT *, date_format(payment_date, '%d-%m-%Y') as 'payment_date'
//            FROM staff_payments 
//            WHERE staff_id = '".$staffid."' 
//            AND (payment_type = 'Salary' OR `payment_type` like '%Deduction%')
//            ORDER BY payment_date";
        
        $this->db->select('*');
        $this->db->where('account_event_mapping.account_event_id', 25);
        $this->db->where('account_event_mapping.entity_name <> ','loan_amount');
        $query1 = $this->db->get('account_event_mapping');
        
        $result= $query1->result_array();
        $ah=[];
        foreach($result as $row){
            $ah[]=$row['account_head_id'];
        }
        
        $sql="select av.id_account_vouchers id, date_format(voucher_date, '%d-%m-%Y') as 'payment_date', date_format(voucher_date,'%M') payment_month, 
            year(voucher_date) 'payment_year',
            av.payment_mode, '' as 'deduction_amount',
            sum(avd.debit) as payment_amount, sum(avd.credit) as deduction_amount, av.description as 'payment_remarks', payment_remarks as 'note_remarks', payment_type, payment_month, deduction_amount
            from account_vouchers av
            join account_voucher_detail avd on av.id_account_vouchers = avd.account_voucher_id
            left join staff_payments on staff_payments.idstaff_payments = av.staffpayment_id
            where av.business_partner_id=".$staffid ." 
            and avd.account_head_id in (".implode(',',$ah).")
            and av.voucher_status = 'Active'
            group by av.id_account_vouchers order by voucher_date desc";
        
        $query=$this->db->query($sql);
          
        return $query->result_array();
      
        
    }
    
    public function staff_commission($staffid){
        
        $this->db->select('*');
        $this->db->where('account_event_mapping.account_event_id', 25);
        $this->db->where('entity_name =','loan_amount');
        $query1 = $this->db->get('account_event_mapping');
        
        $result= $query1->result_array();
        $ah=[];
        foreach($result as $row){
            $ah[]=$row['account_head_id'];
        }
        
        $sql="select av.id_account_vouchers id, date_format(voucher_date, '%d-%m-%Y') as 'payment_date', date_format(voucher_date,'%M') payment_month, 
            year(voucher_date) 'payment_year',
            av.payment_mode, '' as 'deduction_amount',
            avd.debit as payment_amount, av.description as 'payment_remarks', payment_remarks as 'note_remarks', payment_type, payment_month, deduction_amount
            from account_vouchers av
            join account_voucher_detail avd on av.id_account_vouchers = avd.account_voucher_id
            left join staff_payments on staff_payments.idstaff_payments = av.staffpayment_id
            where av.business_partner_id=".$staffid ." 
            and avd.account_head_id in (".implode(',',$ah).")  
                and av.voucher_status = 'Active'
            group by av.id_account_vouchers order by voucher_date desc";
        
        $query=$this->db->query($sql);
        
        
        
        return $query->result_array();
        
    }
    
    public function staff_otherpayments($staffid){
        
        $payment_types = array('Salary', 'Commission', 'Loan');
        
        $this->db->select("*, date_format(payment_date,'%d-%m-%Y') as 'payment_date'");
        $this->db->where("staff_id =",$staffid);
        $this->db->where_not_in("payment_type", $payment_types);
        //$this->db->where("payment_mode =","Addition");
        $this->db->order_by("payment_date");
        $query = $this->db->get("staff_payments");
        
        
        
        return $query->result_array();
        
    }
    
    public function staff_loan($staffid, $loanaccount){
        
        
        
        
         $sql="select av.id_account_vouchers id, date_format(voucher_date, '%d-%m-%Y') as 'payment_date', date_format(voucher_date,'%M') payment_month, 
            year(voucher_date) 'payment_year',
            av.payment_mode, '' as 'deduction_amount',
            avd.debit as payment_amount, av.description as 'payment_remarks', payment_remarks as 'note_remarks', payment_type, payment_month, deduction_amount
            from account_vouchers av
            join account_voucher_detail avd on av.id_account_vouchers = avd.account_voucher_id
            left join staff_payments on staff_payments.idstaff_payments = av.staffpayment_id
            where av.business_partner_id=".$staffid ." 
            and avd.account_head_id=".$loanaccount."    
            and av.voucher_status = 'Active'
            group by av.id_account_vouchers order by voucher_date desc";
        
        $query=$this->db->query($sql);
        
        
        return $query->result_array();
        
    }

    public function staff_loantaken($staffid){
        
        $this->db->select("ifnull(sum(payment_amount),0) as 'amount'");
        $this->db->where("staff_id =",$staffid);
        $this->db->where("payment_type =","Loan");
        $this->db->where("payment_amount >",0);
        $this->db->order_by("payment_date");
        $query = $this->db->get("staff_payments");
        
        
        
        return $query->result_array();
        
    }
    
    public function staff_loanreturned($staffid){
        
        $this->db->select("ifnull(sum(payment_amount),0) as 'amount'");
        $this->db->where("staff_id =",$staffid);
        $this->db->where("payment_type =","Loan");
        $this->db->where("payment_amount <",0);
        $this->db->order_by("payment_date");
        $query = $this->db->get("staff_payments");
        
        
        
        return $query->result_array();
        
    }
    
    public function staff_loanpending($staffid){
        
        $this->db->select("ifnull(sum(payment_amount),0) as 'amount'");
        $this->db->where("staff_id =",$staffid);
        $this->db->where("payment_type =","Loan");
        $this->db->order_by("payment_date");
        $query = $this->db->get("staff_payments");
        
        
        
        return $query->result_array();
        
    }
    
    
    function staff_details( $staff_id){
        $this->db->select('*');
        $this->db->where('s.business_id', $this->session->userdata('businessid'));
        $this->db->where('s.id_staff', $staff_id);
        $query = $this->db->get('staff s');
        
        return $query->result_array();
       
    }
    
    
    function searchpayments($staffid, $month, $year, $voucherid=0){

        $this->db->select('*');
        $this->db->where('account_event_mapping.account_event_id', 26);
        $this->db->where('account_event_mapping.entity_name <> ','loan_amount');
        $query1 = $this->db->get('account_event_mapping');
        
        
        $result= $query1->result_array();
        $ah=[];
        $account_heads="0";
        foreach($result as $row){
            $ah[] = $row['account_head_id'];
            $account_heads= $account_heads . ', '. $row['account_head_id'];
        }
        
        
        $sql="select s.id_staff, date_format(voucher_date, '%d-%m-%Y') as 'payment_date',  
            year(voucher_date) 'payment_year',
            av.payment_mode, 
            avd.debit as debit_amount,
            avd.credit as credit_amount,
            account_heads.account_head,
            av.description as 'payment_remarks', 
            business_partner_name as staff_name,
            s.staff_eid as staff_number, 
            payment_remarks as 'note_remarks', 
            payment_type, payment_month, 
            deduction_amount
            from account_vouchers av
            join account_voucher_detail avd on av.id_account_vouchers = avd.account_voucher_id
            join account_heads on account_heads.id_account_heads = avd.account_head_id
            join staff s on av.business_partner_id = s.id_staff
            where av.business_partner_id=".$staffid." 
            and avd.account_head_id in(".$account_heads.") ";
            if($voucherid==0){
                $sql .= " and month(voucher_date) = '".$month."' 
                and year(voucher_date) = '".$year."' ";
            } else {
                $sql .= " and av.id_account_vouchers = ".$voucherid." ";
            }
        $sql .= " and av.voucher_status = 'Active'
            group by av.id_account_vouchers order by voucher_date desc";
        
        echo $sql; exit();
       $query=$this->db->query($sql);
       
       
        
        return $query->result_array();
        
    }
    
    
    function printslips($staffid, $month, $year, $voucherid=0, $monthname=''){
       
        
        $sql="SELECT  s.id_staff, s.staff_fullname, s.staff_eid, s.staff_designation, s.staff_department, 
            s.staff_eid staff_number,
                s.staff_date_of_joining, s.staff_cnic, s.staff_bank, s.staff_bank_account,
                s.staff_bank_account_title,
                id_account_vouchers, id_account_voucher_detail,
                DATE_FORMAT(voucher_date, '%d-%m-%Y') AS 'payment_date',
                YEAR(voucher_date) 'payment_year',
                av.payment_mode,
                avd.debit AS debit_amount,
                avd.credit AS credit_amount,
                account_heads.account_head,
                av.description AS 'payment_remarks',
                business_partner_name AS staff_name,               
                aem.entity_name
            from account_vouchers av
            join account_voucher_detail avd on av.id_account_vouchers = avd.account_voucher_id
            join account_heads on account_heads.id_account_heads = avd.account_head_id
            join staff s on av.business_partner_id = s.id_staff   
            JOIN account_event_mapping aem on aem.account_head_id =  avd.account_head_id and aem.account_event_id = 26
            where av.business_partner_id=".$staffid." 
            ";
            if($voucherid==0){
                $sql .= " and av.description like '%".$monthname." ".$year."%'";
            } else {
                $sql .= " and av.id_account_vouchers = ".$voucherid." and av.description like '%".$monthname." ".$year."%'";
            }
        $sql .= " and av.voucher_status = 'Active' and left(av.description, 14) = 'Salary Payable'
            order by id_account_vouchers, id_account_voucher_detail ";
        
       // echo $sql; exit();
       $query=$this->db->query($sql);
       
       
       $payables = $query->result_array();
       
//       $sql1="SELECT  s.id_staff, s.staff_fullname, s.staff_eid, s.staff_designation, s.staff_department, 
//            s.staff_eid staff_number,
//                s.staff_date_of_joining, s.staff_cnic, s.staff_bank, s.staff_bank_account,
//                s.staff_bank_account_title,
//                id_account_vouchers, id_account_voucher_detail,
//                DATE_FORMAT(voucher_date, '%d-%m-%Y') AS 'payment_date',
//                YEAR(voucher_date) 'payment_year',
//                av.payment_mode,
//                avd.debit AS debit_amount,
//                avd.credit AS credit_amount,
//                account_heads.account_head,
//                av.description AS 'payment_remarks',
//                business_partner_name AS staff_name,               
//                aem.entity_name
//            from account_vouchers av
//            join account_voucher_detail avd on av.id_account_vouchers = avd.account_voucher_id
//            join account_heads on account_heads.id_account_heads = avd.account_head_id
//            join staff s on av.business_partner_id = s.id_staff   
//            JOIN account_event_mapping aem on aem.account_head_id =  avd.account_head_id and aem.account_event_id = 26 
//            and aem.entity_name='salary_expense' 
//            where av.business_partner_id=".$staffid." 
//            ";
//            if($voucherid==0){
//                $sql1 .= " and month(av.voucher_date) = ".$month." and year(av.voucher_date) = '".$year."'";
//            } else {
//                $sql1 .= " and av.id_account_vouchers = ".$voucherid." and month(av.voucher_date) = ".$month." and year(av.voucher_date) = '".$year."'";
//            }
//        $sql1 .= " and av.voucher_status = 'Active' 
//            order by id_account_vouchers, id_account_voucher_detail ";
//        
//       // echo $sql1; exit();
//       $query1=$this->db->query($sql1);
//       
//       $payment = $query1->result_array();
//       
       
//       $result = array_merge($payables, $payment);
       
       //echo '<pre>';
       //print_r($payment);
       //exit();
       return $payables;
        
    }
    
    public function printpayments($staffid, $month, $year, $voucherid=0){
        
//        $sql="SELECT  s.id_staff,s.staff_fullname, s.staff_eid, s.staff_designation, s.staff_department, 
//                s.staff_eid staff_number,
//                s.staff_date_of_joining, s.staff_cnic, s.staff_bank, s.staff_bank_account,
//                s.staff_bank_account_title,
//                id_account_vouchers, id_account_voucher_detail,
//                DATE_FORMAT(voucher_date, '%d-%m-%Y') AS 'payment_date',
//                YEAR(voucher_date) 'payment_year',
//                av.payment_mode,
//                avd.debit AS debit_amount,
//                avd.credit AS credit_amount,
//                account_heads.account_head,
//                av.description AS 'payment_remarks',
//                business_partner_name AS staff_name                
//            from account_vouchers av
//            join account_voucher_detail avd on av.id_account_vouchers = avd.account_voucher_id
//            join account_heads on account_heads.id_account_heads = avd.account_head_id
//            join staff s on av.business_partner_id = s.id_staff               
//            JOIN account_event_mapping aem on aem.account_head_id = account_heads.id_account_heads and aem.account_event_id=26 
//            and aem.entity_name = 'salary_payable' 
//            where av.business_partner_id=".$staffid." 
//            ";
//            if($voucherid==0){
//                $sql .= " and month(voucher_date) = '".$month."' 
//                and year(voucher_date) = '".$year."' ";
//            } else {
//                $sql .= " and av.staffpayment_id = ".$voucherid." ";
//            }
//        $sql .= " and av.voucher_status = 'Active' 
//            order by id_account_vouchers, id_account_voucher_detail ";
//        
        
        $nextmonth = $month + 1;
        $sql = "SELECT 
                s.id_staff,
                s.staff_fullname,
                s.staff_eid,
                s.staff_designation,
                s.staff_department,
                s.staff_eid staff_number,
                s.staff_date_of_joining,
                s.staff_cnic,
                s.staff_bank,
                s.staff_bank_account,
                s.staff_bank_account_title,
                id_account_vouchers,
                id_account_voucher_detail,
                DATE_FORMAT(voucher_date, '%d-%m-%Y') AS 'payment_date',
                YEAR(voucher_date) 'payment_year',
                av.payment_mode,
                avd.debit AS debit_amount,
                avd.credit AS credit_amount,
                account_heads.account_head,
                av.description AS 'payment_remarks',
                business_partner_name AS staff_name,
                aem.entity_name
            FROM
                account_vouchers av
                    JOIN
                account_voucher_detail avd ON av.id_account_vouchers = avd.account_voucher_id
                    JOIN
                account_heads ON account_heads.id_account_heads = avd.account_head_id
                    JOIN
                staff s ON av.business_partner_id = s.id_staff
                    JOIN
                account_event_mapping aem ON aem.account_head_id = avd.account_head_id
                    AND aem.account_event_id = 26
                    AND aem.entity_name = 'salary_payable'
            WHERE
                av.business_partner_id = ".$staffid."                    
                    AND MONTH(av.voucher_date) = ".$nextmonth . "    
                    AND YEAR(av.voucher_date) = '".$year."' 
                    AND av.voucher_status = 'Active'
                    and avd.credit=0
                    group by id_account_vouchers, id_account_voucher_detail
            ORDER BY id_account_vouchers , id_account_voucher_detail";
        
        
        
        
       //echo $sql; exit();
       $query=$this->db->query($sql);
       return $query->result_array();
        
        
    }
    
    public function day_attendance($mydate){
        
        if(null!==$mydate){
            $today=$mydate;
        }else{
            $today=date('Y-m-d');
        }
        
        
        $sql="SELECT id_staff_attendance, concat('assets/images/staff/',staff_image) as staff_image, id_staff, staff_fullname, staff_cell, date_format(time_in,'%H:%i:%s') time_in, date_format(time_out,'%H:%i:%s') time_out
            FROM staff
            left join staff_attendance on staff_attendance.staff_id= staff.id_staff 
            and date_format(time_in,'%Y-%m-%d')='".$today."'
            where staff.staff_active='Y'";
        if($this->session->userdata('common_products')=='Yes'){
            $sql .= " and (staff.business_id=". $this->session->userdata('businessid') ." OR staff.staff_shared = 'Yes') ";
        }else{
            $sql .=" and staff.business_id = ".$this->session->userdata('businessid');
        }
        
        $sql .= " order by staff_order";
        
           
        $query=$this->db->query($sql);
        
        
        return $query->result_array();
        
    }
    
    
    
    public function get_staff_payment_types(){
        
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('payment_type_active', 'Yes');
        $query = $this->db->get('staff_payment_types');
        
        
        return $query->result_array();
       
    }

    function searchnameforstaff($match) {
        $this->db->select('*, staff_fullname as id');
        $this->db->like('staff_fullname', $match);
        $this->db->where('business_id', $this->session->userdata('businessid'));    
        $query = $this->db->get("staff");
        
        return $query->result_array();
    }    
    
    function get_staff_payments($payment_type, $startdate, $enddate){
              
        $sql="SELECT month(payment_date), ifnull(sum(payment_amount),0) 'total' FROM 
            staff_payments
            where payment_date >= '".$startdate."' 
            and payment_date <= '".$enddate."' ";
        if($payment_type==='Other'){
            $sql.= "and payment_type not in ('Commission','Salary') ";
        }else {
            $sql.= "and payment_type='".$payment_type."' ";
        }
        //$sql .= " group by month(payment_date);";
        
        $query =$this->db->query($sql);
        
        
        
        return $query->result_array();
        
        
    }

    function get_staff_booked_min($staffid, $date){
        
        $sql = "select staff_id, sum(a.booked_min) as booked_min, staff.staff_work_min, staff.staff_fullname, '".$date."' as mdate,
                case when staff_work_min - Round(a.booked_min/60) <= 0 
                then 'Over Booked' when staff_work_min - Round(a.booked_min/60) <= 20 
                and staff_work_min - Round(a.booked_min/60) >= 0 then 'Booked' else 'Available' End as staffstatus 
                from staff
                left join
                (SELECT staff_id, service_id,
                ifnull(time(visit_service_start),0) as start, 
                ifnull(time(visit_service_end),0) as end, 
                ifnull(Round(TIME_TO_SEC(TIMEDIFF(time(visit_service_end) , time(visit_service_start)))/60),0) as booked_min
                FROM staff
                left join visit_service_staffs  on staff.id_staff = visit_service_staffs.staff_id and visit_service_staff_status='Active' 
                left join visit_services on visit_services.id_visit_services = visit_service_staffs.visit_service_id and visit_service_status='Active' 
                and date(visit_services.visit_service_start) = '".$date."' 
                where staff_id=".$staffid."
                group by staff_id, service_id) as a
                on a.staff_id = staff.id_staff
                where staff.id_staff = ".$staffid.";";
        
        
        $query =$this->db->query($sql);
        return $query->result_array();
        
    }
    function updateFCMToken($staffid){
        
        $this->db->where("id_staff=".$staffid."");
        $this->db->set('fcm_id',null);
        $this->db->update("staff");
        
        return $staffid;
    }
    
    function getHrmServer(){
        
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));        
        $query = $this->db->get("key_code");
        
        return $query->row();
    }
    
    
    function staff_month_attendance_detail($staffid, $year, $month){
        $margin = 20;
       
       $this->db->select('timein_margin');
       $this->db->where('id_business', $this->session->userdata('businessid'));
       $m = $this->db->get('business');
       $businss_margin = $m->row(); 
       if($m->num_rows() > 0){
           $margin = $businss_margin->timein_margin;
       }
        
        $this->db->select('id_staff, staff_fullname, staff_image, staff_salary, 
                provident_fund_rate, week_day_off, deduction_days_absent, 
                deduction_days_late, total_late_allowed, total_absents_allowed, 
                salary_monthly_tax, day_start_time');
        $this->db->join('deduction_policy', 'id_deduction_policy = staff.deduction_policy');
        $this->db->where('id_staff', $staffid);
        $qresult = $this->db->get('staff');
        $q = $qresult->row();
        //print_r($q);exit();
        $week_day_off = $q->week_day_off;
        $day_start_time = $q->day_start_time;
        
        
        $sql = "SELECT 
                mDays.Date,
                mDays.Day,
                '".$week_day_off."' as week_day_off,
                ".$q->id_staff." as id_staff, 
                '".$q->staff_fullname."' AS staff_fullname,
                ".$q->salary_monthly_tax." as salary_monthly_tax,
                min(attendance.time_in) time_in,
                max(attendance.time_out) time_out,
                staff_leaves.staff_leave_date,
                staff_leaves.leave_reason,
                holidays.holiday_date,
                holidays.holiday_reason,
                CONCAT(ROUND(TIMESTAMPDIFF(MINUTE, min(attendance.time_in), max(attendance.time_out)) / 60,2),' Hours') AS 'Work_Hours',
                CASE WHEN
                        IFNULL(attendance.time_in, '') != '' AND attendance.time_in != CONCAT(DATE(attendance.time_in), ' 00:00:00')
                    THEN 1
                    ELSE 0
                END AS 'Present',
                CASE
                    WHEN INSTR('".$week_day_off."',  mDays.Day) > 0 AND IFNULL(attendance.time_in, '') = '' THEN 0
                    WHEN '".$week_day_off."' Not Like concat('%',mDays.Day,'%') AND IFNULL(attendance.time_in, '') = '' 
                        AND IFNULL(staff_leave_date, '') = '' 
                        AND IFNULL(holidays.holiday_date,'') = ''  THEN 1 
                    WHEN IFNULL(holidays.holiday_date,'') != '' THEN 0    
                    WHEN IFNULL(staff_leave_date, '') != '' THEN 0
                    ELSE 0
                END AS 'Absent',
                CASE
                    WHEN
                        TIMESTAMPDIFF(MINUTE,
                            CONCAT(mDays.Date, ' ', staff.day_start_time),
                            min(attendance.time_in)) > ".$margin."
                    THEN
                        1
                    WHEN min(attendance.time_in) = CONCAT(DATE(min(attendance.time_in)), ' 00:00:00') THEN 0
                    ELSE 0
                END AS 'Late',
                CASE
                    WHEN IFNULL(staff_leave_date, '') = '' THEN 0
                    WHEN '".$week_day_off."' NOT LIKE concat('%',mDays.Day,'%') AND IFNULL(holidays.holiday_date,'') = '' AND IFNULL(staff_leave_date, '') != '' AND IFNULL(attendance.time_in, '') = '' THEN 1        
                    ELSE 0
                END AS 'Leaves',
                CASE 
                    WHEN IFNULL(holidays.holiday_date,'') != '' THEN 1
                    WHEN INSTR('".$week_day_off."', mDays.Day) > 0 THEN 1
                    ELSE 0 
                END AS 'Holiday',
                attendance.address,   
                business.business_opening_time,
                business.business_closing_time
            FROM (SELECT 
                    FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-', n)), '%Y-%m-%d') AS Date,
                    FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-', n)), '%a') AS Day
                            FROM
                    (SELECT 
                                    (((b4.0 << 1 | b3.0) << 1 | b2.0) << 1 | b1.0) << 1 | b0.0 AS n
                            FROM
                                    (SELECT 0 UNION ALL SELECT 1) AS b0, (SELECT 0 UNION ALL SELECT 1) AS b1, (SELECT 0 UNION ALL SELECT 1) AS b2, (SELECT 0 UNION ALL SELECT 1) AS b3, (SELECT 0 UNION ALL SELECT 1) AS b4) t
                            WHERE
                                    n > 0 AND n <= DAY(LAST_DAY('".$year."-".$month."-01'))) AS mDays
            LEFT JOIN
                (SELECT staff_id, time_in, time_out, address
                FROM staff_attendance
                WHERE
                    MONTH(time_in) = ".$month."
                    AND YEAR(time_in) = '".$year."'
                    AND staff_id = ".$q->id_staff.") AS attendance ON DATE(time_in) = mDays.Date
            LEFT JOIN
                (SELECT id_staff,
                        staff_fullname,
                        staff_image,
                        week_day_off,
                        day_start_time,
                        business_id
                FROM staff WHERE id_staff = ".$q->id_staff.") AS staff ON staff.id_staff = attendance.staff_id
            LEFT JOIN 
                (SELECT staff_id,
                        staff_leave_date,
                        leave_reason
                 FROM staff_leaves 
                 WHERE staff_id = ".$q->id_staff."
                 AND staff_leave_status = 'Active' 
                 AND MONTH(staff_leave_date) =  ".$month."
                 AND YEAR(staff_leave_date) =  '".$year."') As staff_leaves 
                 ON date(staff_leaves.staff_leave_date) = mDays.Date
            LEFT JOIN (
		SELECT holiday_date,
                holiday_day,
                holiday_reason
                FROM holidays WHERE";
        
        if($this->session->userdata('common_products')=='No'){
            $sql .= " business_id= ".$this->session->userdata('businessid')." AND ";
        }
        
        $sql .= " MONTH(holiday_date) = ".$month."
                AND YEAR(holiday_date)='".$year."'       
                ) As holidays ON holiday_date = mDays.Date
            LEFT JOIN
                (SELECT id_business, business_opening_time, business_closing_time
                FROM business) AS business ON staff.business_id = business.id_business
            GROUP BY mDays.Date    
            ORDER BY mDays.Date;";
        
        //echo $sql; exit();
        
        $query = $this->db->query($sql);
        
        return $query->result_array();
        
    }
    
    
    
    function staff_year_attendance($year=null, $month= null){
        
        if($year==null){
            $year = date('Y');
        }
        
        if($month==null){
            $month = date('m');
        }
        
        
        $sql = "select attendance.id_staff, attendance.staff_fullname, a.month, a.year, 
            attendance.daysinmonth as daysinmonth, 
            count(time_in) present,
               attendance.daysinmonth - count(time_in) as absent, 
               CASE WHEN staff_leaves.leaves is null then 0 else staff_leaves.leaves END as leaves,
               holidays.holidays as holidays
               from (
                   SELECT 'Jan' month, year(now()) year, 1 monthOrder UNION 
                   SELECT 'Feb' month, year(now()) year, 2 monthOrder UNION 
                   SELECT 'Mar' month, year(now()) year, 3 monthOrder UNION 
                   SELECT 'Apr' month, year(now()) year, 4 monthOrder UNION 
                   SELECT 'May' month, year(now()) year, 5 monthOrder UNION 
                   SELECT 'Jun' month, year(now()) year, 6 monthOrder UNION 
                   SELECT 'Jul' month, year(now()) year, 7 monthOrder UNION 
                   SELECT 'Aug' month, year(now()) year, 8 monthOrder UNION 
                   SELECT 'Sep' month, year(now()) year, 9 monthOrder UNION 
                   SELECT 'Oct' month, year(now()) year, 10 monthOrder UNION 
                   SELECT 'Nov' month, year(now()) year, 11 monthOrder UNION 
                   SELECT 'Dec' month, year(now()) year, 12 monthOrder 
               ) AS a join 
                       (select id_staff, staff_fullname, staff_attendance.time_in,
                       DAYOFMONTH(LAST_DAY(staff_attendance.time_in)) as daysinmonth
                       from staff_attendance 
                       join staff on staff.id_staff = staff_attendance.staff_id 
                       where staff.business_id= ". $this->session->userdata('businessid') ." 
                        and staff.staff_active='Y'
                        and year(staff_attendance.time_in) = year(now())
                       ) as attendance on month(attendance.time_in) = a.monthOrder and year(attendance.time_in) = a.year

                LEFT JOIN 
                       (SELECT staff_id,
                           month(staff_leave_date) as leavemonth,
                           year(staff_leave_date) as leaveyear,
                           count(*) as leaves
                        FROM staff_leaves 
                        JOIN staff on staff.id_staff=staff_leaves.staff_id
                        WHERE 
                        staff.business_id= ". $this->session->userdata('businessid') ." 
                        AND staff_leave_status = 'Active'                  
                        AND YEAR(staff_leave_date) =  year(now())
                        GROUP BY staff_id, month(staff_leave_date)
                        ) As staff_leaves 
                        ON staff_leaves.leavemonth = a.monthOrder and leaveyear = a.year

               LEFT JOIN (
                       SELECT month(holidays.holiday_date) as monthholiday, 
                       year(holidays.holiday_date) as yearholiday, 
                       count(*) as holidays
                       FROM holidays 
                       WHERE 
                       holidays.business_id= ". $this->session->userdata('businessid') ." 		
                       AND YEAR(holiday_date)= year(now())  
                       GROUP BY month(holiday_date), year(holiday_date)
                       ) As holidays ON holidays.monthholiday  =a.monthOrder and yearholiday = a.year

               group by id_staff, monthOrder
               order by id_staff, monthOrder";
        
             //  echo $sql; exit;
        $query = $this->db->query($sql);
        
        return $query->result_array();
        
    }
    
    
    function staff_month_commission_detail($staffid, $year, $month){
        
        $this->db->select('id_staff, staff_fullname, staff_image, staff_salary, commission_mode, commission_target, staff_commission_perc, salary_monthly_tax');                
        $this->db->join('deduction_policy', 'id_deduction_policy = staff.deduction_policy');
        $this->db->where('id_staff', $staffid);        
        $qresult = $this->db->get('staff');
        $q = $qresult->row();
        
        $sql = "
            SELECT mDays.Date, mDays.Day, ".$q->id_staff." as id_staff, '".$q->staff_fullname."' as staff_fullname, 
                '".$q->staff_image."' as staff_image,
            '".$q->commission_mode."' as commission_mode, '".$q->commission_target."' as commission_target, ".$q->salary_monthly_tax." as salary_monthly_tax,
            sum(invoice_staff.paid) as paid, 
            sum(invoice_staff.final_price) as final_price, 
            case when staff.commission_mode = 'Services' then round(sum(invoice_staff.commission),2)             
                when staff.commission_mode = 'Target' AND sum(invoice_staff.paid) >= staff.commission_target  then  round((sum(invoice_staff.paid)*staff.staff_commission_perc)/100,2)
                else 0
                end as service_commission, 
            sum(invoice_staff.requested) as requested, 
            sum(invoice_staff.additional_staff) as additional_staff 
            FROM
            (
            select FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-',n)),'%Y-%m-%d') as Date, 
            FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-',n)),'%a') as Day 
            from (
                    select (((b4.0 << 1 | b3.0) << 1 | b2.0) << 1 | b1.0) << 1 | b0.0 as n
                            from  (select 0 union all select 1) as b0,
                                  (select 0 union all select 1) as b1,
                                  (select 0 union all select 1) as b2,
                                  (select 0 union all select 1) as b3,
                                  (select 0 union all select 1) as b4 ) t
                    where n > 0 and n <= day(last_day('".$year."-".$month."-01'))
            ) as mDays
            LEFT JOIN(
                SELECT invoice.invoice_date, id_invoice, id_invoice_staff, invoice_staff.staff_id, 
                invoice_staff.paid, invoice_staff.final_price, invoice_staff.commission, 
                case when invoice_staff.requested = 'Yes' then 1 else 0 end as requested, 
                case when invoice_staff.additional_staff = 'Yes' then 1 else 0 end as additional_staff
                from invoice_staff
                join invoice on invoice.id_invoice = invoice_staff.invoice_id and invoice_status = 'valid'
                where invoice_staff.staff_id = ".$q->id_staff." 
                and month(invoice.invoice_date) = ".$month." 
                and year(invoice.invoice_date) = '".$year."'
            ) as invoice_staff on date(invoice_staff.invoice_date) = mDays.Date
            LEFT JOIN(
                    SELECT id_staff, staff_fullname, staff_image, commission_mode, staff_commission_perc, commission_target 
                    from staff
                    where id_staff = ".$q->id_staff."
            ) as staff on staff.id_staff = invoice_staff.staff_id
            group by mDays.Date, id_staff 
            order by mDays.Date
            ;";
        $query = $this->db->query($sql);
        
        return $query->result_array();
        
    }
    
    function staff_month_retail_commission_detail($staffid, $year, $month){
        $this->db->select('id_staff, staff_fullname, staff_image, staff_salary, commission_mode, commission_target, staff_commission_perc, salary_monthly_tax');
                
        $this->db->join('deduction_policy', 'id_deduction_policy = staff.deduction_policy');
        $this->db->where('id_staff', $staffid);
        $qresult = $this->db->get('staff');
        $q = $qresult->row();
        
        
        $sql = "
            SELECT mDays.Date, mDays.Day, ".$q->id_staff." as id_staff, '".$q->staff_fullname."' as staff_fullname, 
                '".$q->staff_image."' as staff_image,
            '".$q->commission_mode."' as commission_mode, '".$q->commission_target."' as commission_target, ".$q->salary_monthly_tax." as salary_monthly_tax,
            sum(invoice_products.paid) as paid, 
            sum(invoice_products.final_price) as final_price, 
            case when staff.commission_mode = 'Services' then round(sum(invoice_products.commission),2) 
                     when staff.commission_mode = 'Target' AND sum(invoice_products.paid) >= staff.commission_target  then  round((sum(invoice_products.paid)*staff.staff_commission_perc)/100,2)
                 else 0
            end as service_commission
            FROM
            (
            select FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-',n)),'%Y-%m-%d') as Date, 
            FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-',n)),'%a') as Day 
            from (
                    select (((b4.0 << 1 | b3.0) << 1 | b2.0) << 1 | b1.0) << 1 | b0.0 as n
                            from  (select 0 union all select 1) as b0,
                                  (select 0 union all select 1) as b1,
                                  (select 0 union all select 1) as b2,
                                  (select 0 union all select 1) as b3,
                                  (select 0 union all select 1) as b4 ) t
                    where n > 0 and n <= day(last_day('".$year."-".$month."-01'))
            ) as mDays
            LEFT JOIN(
                    SELECT invoice.invoice_date, id_invoice, invoice_products.staff_id, 
                invoice_products.paid, invoice_products.final_price, invoice_products.commission
                from invoice_products
                join invoice on invoice.id_invoice = invoice_products.invoice_id and invoice_status = 'valid'
                where invoice_products.staff_id = ".$q->id_staff." 
                and month(invoice.invoice_date) = ".$month." 
                and year(invoice.invoice_date) = '".$year."'
            ) as invoice_products on date(invoice_products.invoice_date) = mDays.Date
            LEFT JOIN(
                    SELECT id_staff, staff_fullname, staff_image, commission_mode, staff_commission_perc, commission_target 
                    from staff
                    where id_staff = ".$q->id_staff."
            ) as staff on staff.id_staff = invoice_products.staff_id
            group by mDays.Date, id_staff 
            order by mDays.Date
            ;";
        $query = $this->db->query($sql);
        
        return $query->result_array();
        
    }
    
    
    function get_allowances($business_id){
        
        $this->db->select('*');
        $this->db->where('allowances.business_id', $business_id);
        $aresult = $this->db->get('allowances');
        return  $aresult->result();
    }
    
    function staff_month_allowances($staffid){
        
        $this->db->select('staff_allowance.staff_id, allowances.id_allowances, allowances.allowance_name, allowances.entity_name, staff_allowance.allowance_amount');
        $this->db->join('allowances', 'allowances.id_allowances = staff_allowance.allowance_id');
        $this->db->where('staff_allowance.staff_id', $staffid);
        $this->db->where('staff_allowance.staff_allowance_status', 'Active');
        $aresult = $this->db->get('staff_allowance');
        
        $allowances = $aresult->result_array();
        
        return $allowances;
    }
    
    
    function staff_month_payables($staffid, $year, $month){
        $margin = 20;
         
         
       $this->db->select('timein_margin');
       $this->db->where('id_business', $this->session->userdata('businessid'));
       $m = $this->db->get('business');
       $businss_margin = $m->row(); 
       if($m->num_rows() > 0){
           $margin = $businss_margin->timein_margin;
       }
         
         
        $this->db->select('id_staff, staff_fullname, staff_image, staff_salary, provident_fund_rate, 
                week_day_off, deduction_days_absent, deduction_days_late, total_late_allowed, 
                total_absents_allowed, salary_monthly_tax, salary_type, day_start_time');
        $this->db->join('deduction_policy', 'id_deduction_policy = staff.deduction_policy');
        $this->db->where('id_staff', $staffid);
        $qresult = $this->db->get('staff');
        $q = $qresult->row();
        
        //print_r($q);exit();
        
        
        $week_day_off = $q->week_day_off;
        
        $sql = "SELECT ".$q->id_staff." as id_staff, '". $q->staff_fullname ."' as staff_fullname, '".
                $q->staff_image."' as staff_image, ". 
                $q->staff_salary." as staff_salary, '". 
                $q->salary_type."' as salary_type, ". 
                $q->provident_fund_rate. " as provident_fund_rate, '". 
                $q->week_day_off."' as week_day_off, '". 
                $q->deduction_days_absent."' as deduction_rate_absent, '". 
                $q->deduction_days_late ."' as deduction_rate_late, ". 
                $q->total_late_allowed." as total_late_allowed, ".
                $q->total_absents_allowed." as total_absents_allowed, ".
                $q->salary_monthly_tax." as salary_monthly_tax, 
                sum(ifnull(Work_Hours,0)) as 'WorkHours', sum(Present) as 'Present', sum(Absent) as 'Absent', sum(Late) as 'Lates',  sum(Leaves) as 'Leaves',
                round(".$q->staff_salary."/count(Date),2) day_salary, 
                case when sum(Absent) >= ".$q->total_absents_allowed." then round(".$q->staff_salary."*".$q->deduction_days_absent."/count(Date) * (floor(sum(Absent) -".$q->total_absents_allowed.")), 2) else 0 end as absent_deduction,
                CASE WHEN 'monthly' = '".$q->salary_type."' THEN
                    case when sum(Late) >= ".$q->total_late_allowed." then round(".$q->staff_salary."*".$q->deduction_days_late."/count(Date) * (floor(sum(Late) -".$q->total_late_allowed.")), 2) else 0 end
                WHEN 'daily' = '".$q->salary_type."' THEN
                    case when sum(Late) >= ".$q->total_late_allowed." then round(((".$q->staff_salary."* floor(sum(Late)) - (".$q->staff_salary." * ".$q->total_late_allowed.")) * ".$q->deduction_days_late."), 2) else 0 end
                ELSE 0 END as late_deduction,
                round((".$q->staff_salary."*".$q->provident_fund_rate.")/100,2) as provident_fund
        FROM
        (SELECT 
        mDays.Date,
            mDays.Day,
            1 AS id_staff,
            attendance.time_in,
            attendance.time_out,
            CASE WHEN attendance.time_out is not null THEN
            ROUND(TIMESTAMPDIFF(MINUTE, attendance.time_in, attendance.time_out) / 60, 2)
            ELSE 0
            END
            AS 'Work_Hours',
            CASE
                WHEN
                    IFNULL(attendance.time_in, '') != ''
                        AND attendance.time_in != CONCAT(DATE(attendance.time_in), ' 00:00:00')
                THEN
                    1
                ELSE 0
            END AS 'Present',
		CASE
                    WHEN
                        INSTR('".$q->week_day_off."',  mDays.Day) > 0
                            AND IFNULL(attendance.time_in, '') = ''
                    THEN
                        0
                    WHEN
                        '".$q->week_day_off."' NOT LIKE concat('%',mDays.Day,'%')
                            AND IFNULL(attendance.time_in, '') = ''
                            AND IFNULL(staff_leave_date, '') = ''
                            AND IFNULL(holidays.holiday_date, '') = ''
                    THEN
                        1
                    WHEN IFNULL(holidays.holiday_date, '') != '' THEN 0
                    WHEN IFNULL(staff_leave_date, '') != '' THEN 0
                    ELSE 0
            END AS 'Absent',
            CASE
                WHEN TIMESTAMPDIFF(MINUTE, CONCAT(mDays.Date, ' ', '".$q->day_start_time."'), attendance.time_in) > ".$margin." THEN 1
                WHEN attendance.time_in = CONCAT(DATE(attendance.time_in), ' 00:00:00') THEN 0
                ELSE 0
            END AS 'Late',
            
            CASE
                WHEN IFNULL(staff_leave_date, '') = '' THEN 0
                WHEN
                    INSTR('".$q->week_day_off."',  mDays.Day) > 0
                        AND IFNULL(holidays.holiday_date, '') != ''
                        AND IFNULL(staff_leave_date, '') != ''
                        AND IFNULL(attendance.time_in, '') = ''
                THEN
                    1
                ELSE 0
            END AS 'Leaves',
            
            CASE
                WHEN IFNULL(holidays.holiday_date, '') != '' THEN 1
                WHEN INSTR('".$q->week_day_off."',  mDays.Day) > 0 THEN 1
                ELSE 0
            END AS 'Holiday',
            
            attendance.address,
            business.business_opening_time,
            business.business_closing_time
            FROM
             (SELECT 
                 FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-', n)), '%Y-%m-%d') AS Date,
                     FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-', n)), '%a') AS Day
             FROM
                 (SELECT 
                 (((b4.0 << 1 | b3.0) << 1 | b2.0) << 1 | b1.0) << 1 | b0.0 AS n
             FROM
                 (SELECT 0 UNION ALL SELECT 1) AS b0, (SELECT 0 UNION ALL SELECT 1) AS b1, (SELECT 0 UNION ALL SELECT 1) AS b2, (SELECT 0 UNION ALL SELECT 1) AS b3, (SELECT 0 UNION ALL SELECT 1) AS b4) t
             WHERE
                 n > 0
                     AND n <= DAY(LAST_DAY('".$year."-".$month."-01'))) AS mDays
                 LEFT JOIN
             (SELECT 
                 staff_id, time_in, time_out, address
             FROM
                 staff_attendance
             WHERE
                 MONTH(time_in) = ".$month."
                     AND YEAR(time_in) = '".$year."'
                     AND staff_id = ".$q->id_staff.") AS attendance ON DATE(time_in) = mDays.Date
                 LEFT JOIN
             (SELECT 
                 id_staff,
                     staff_fullname,
                     staff_image,
                     week_day_off,
                     business_id, salary_type
             FROM
                 staff
             WHERE
                 id_staff = ".$q->id_staff.") AS staff ON staff.id_staff = attendance.staff_id
                 LEFT JOIN
             (SELECT 
                 staff_id, staff_leave_date
                    FROM
                        staff_leaves
                    WHERE
                        staff_id = ".$q->id_staff."
                            AND staff_leave_status = 'Active'
                            AND MONTH(staff_leave_date) = ".$month."
                            AND YEAR(staff_leave_date) = '".$year."') AS staff_leaves ON DATE(staff_leaves.staff_leave_date) = mDays.Date
                LEFT JOIN (
                        SELECT holiday_date,
                        holiday_day,
                        holiday_reason
                        FROM holidays WHERE ";
           if($this->session->userdata('common_products')=='No'){
               $sql .= " business_id= ".$this->session->userdata("businessid")." AND ";
           }
    $sql .= " MONTH(holiday_date) = ".$month."
                 AND YEAR(holiday_date)='".$year."'        
                 ) As holidays ON holiday_date = mDays.Date
                LEFT JOIN
                    (SELECT 
                        id_business, business_opening_time, business_closing_time
                    FROM
                        business) AS business ON staff.business_id = business.id_business
                GROUP BY mDays.Date        
                ORDER BY mDays.Date) AS a
                GROUP BY id_staff
                ";
       // echo $sql; exit();
        $query = $this->db->query($sql);
        
        return $query->result_array();
        
    }
    
    function staff_month_commission($staffid, $year, $month){
        
        $this->db->select('id_staff, staff_fullname, staff_image, staff_salary, commission_mode, commission_target, staff_commission_perc');
                
        $this->db->join('deduction_policy', 'id_deduction_policy = staff.deduction_policy');
        $this->db->where('id_staff', $staffid);
        $qresult = $this->db->get('staff');
        $q = $qresult->row();
        
        $sql="
            SELECT month(Date) as Month, '".$q->commission_mode."' as commission_mode, '".$q->commission_target."' as commission_target,
            sum(paid) paid, sum(final_price) final_price, ifnull(sum(service_commission),0) as service_commission, 
            ifnull(sum(requested),0) as requested, 
            ifnull(sum(additional_staff),0) as additional_staff
            FROM
            (
            SELECT mDays.Date, mDays.Day, id_staff, staff.staff_fullname, staff.staff_image,
            staff.commission_mode, staff.commission_target,
            sum(invoice_staff.paid) as paid, 
            sum(invoice_staff.final_price) as final_price, 
            case when staff.commission_mode = 'Services' then round(sum(invoice_staff.commission),2) 
                     when staff.commission_mode = 'Target' AND sum(invoice_staff.paid) >= staff.commission_target  then  round((sum(invoice_staff.paid)*staff.staff_commission_perc)/100,2)
                 else 0
            end as service_commission, 
            sum(invoice_staff.requested) as requested, 
            sum(invoice_staff.additional_staff) as additional_staff 
            FROM
            (
            select FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-',n)),'%Y-%m-%d') as Date, 
            FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-',n)),'%a') as Day 
            from (
                    select (((b4.0 << 1 | b3.0) << 1 | b2.0) << 1 | b1.0) << 1 | b0.0 as n
                            from  (select 0 union all select 1) as b0,
                                  (select 0 union all select 1) as b1,
                                  (select 0 union all select 1) as b2,
                                  (select 0 union all select 1) as b3,
                                  (select 0 union all select 1) as b4 ) t
                    where n > 0 and n <= day(last_day('".$year."-".$month."-01'))
            ) as mDays
            LEFT JOIN(
                SELECT invoice.invoice_date, id_invoice, id_invoice_staff, invoice_staff.staff_id, 
                invoice_staff.paid, invoice_staff.final_price, invoice_staff.commission, 
                case when invoice_staff.requested = 'Yes' then 1 else 0 end as requested, 
                case when invoice_staff.additional_staff = 'Yes' then 1 else 0 end as additional_staff
                from invoice_staff
                join invoice on invoice.id_invoice = invoice_staff.invoice_id and invoice.invoice_status='valid' 
                where invoice_staff.staff_id = ".$q->id_staff." 
                and month(invoice.invoice_date) = ".$month." 
                and year(invoice.invoice_date) = '".$year."'
            ) as invoice_staff on date(invoice_staff.invoice_date) = mDays.Date
            LEFT JOIN(
                    SELECT id_staff, staff_fullname, staff_image, commission_mode, staff_commission_perc, commission_target 
                    from staff
                    where id_staff = ".$q->id_staff."
            ) as staff on staff.id_staff = invoice_staff.staff_id
            group by mDays.Date
            ) as c
            group by month(Date)
            ";
        //echo $sql; exit();
        $query = $this->db->query($sql);
        
        return $query->result_array();        
        
    }
    
    function staff_month_retail_commission($staffid, $year, $month){
        
        $this->db->select('id_staff, staff_fullname, staff_image, staff_salary, commission_mode, 
                commission_target, staff_commission_perc');
        $this->db->where('id_staff', $staffid);
        $qresult = $this->db->get('staff');
        $q = $qresult->row();
        
        $sql="
            SELECT month(Date) as Month, '".$q->commission_mode."' as commission_mode, '".$q->commission_target."' as commission_target,
            sum(paid) paid, sum(final_price) final_price, ifnull(sum(retail_commission),0) as retail_commission
            FROM
            (
            SELECT mDays.Date, mDays.Day, id_staff, staff.staff_fullname, staff.staff_image,
            staff.commission_mode, staff.commission_target,
            sum(invoice_products.paid) as paid, 
            sum(invoice_products.final_price) as final_price, 
            case when staff.commission_mode = 'Services' then round(sum(invoice_products.commission),2) 
                     when staff.commission_mode = 'Target' AND sum(invoice_products.paid) >= staff.commission_target  then  round((sum(invoice_products.paid) * staff.staff_commission_perc)/100,2)
                 else 0
            end as retail_commission            
            FROM
            (
            select FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-',n)),'%Y-%m-%d') as Date, 
            FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-',n)),'%a') as Day 
            from (
                    select (((b4.0 << 1 | b3.0) << 1 | b2.0) << 1 | b1.0) << 1 | b0.0 as n
                            from  (select 0 union all select 1) as b0,
                                  (select 0 union all select 1) as b1,
                                  (select 0 union all select 1) as b2,
                                  (select 0 union all select 1) as b3,
                                  (select 0 union all select 1) as b4 ) t
                    where n > 0 and n <= day(last_day('".$year."-".$month."-01'))
            ) as mDays
            LEFT JOIN(
                SELECT invoice.invoice_date, id_invoice, invoice_products.staff_id, 
                invoice_products.paid, invoice_products.final_price, invoice_products.commission          
                from invoice_products
                join invoice on invoice.id_invoice = invoice_products.invoice_id and invoice.invoice_status='valid'
                where invoice_products.staff_id = ".$q->id_staff." 
                and month(invoice.invoice_date) = ".$month." 
                and year(invoice.invoice_date) = '".$year."'
            ) as invoice_products on date(invoice_products.invoice_date) = mDays.Date
            LEFT JOIN(
                    SELECT id_staff, staff_fullname, staff_image, commission_mode, staff_commission_perc, commission_target 
                    from staff
                    where id_staff = ".$q->id_staff."
            ) as staff on staff.id_staff = invoice_products.staff_id
            group by mDays.Date
            ) as c
            group by month(Date)
            ";
        //echo $sql; exit();
        $query = $this->db->query($sql);
        
        return $query->result_array();        
        
    }    
    
    public function staff_payables_receivables($businessid, $account_heads, $staff_id=null){
                
        $sql = "SELECT 
                id_staff, staff_eid, staff_fullname, month(voucher_date) as voucher_month, year(voucher_date) as voucher_year, voucher_date,
                id_account_vouchers, business_partner_id, account_vouchers.description, concat(staff_bank_account, '<br>', staff.staff_bank_account_title, '<br>', staff_bank) staff_account,
                credit, sum(ifnull(paid, 0)) as paid,
                round(credit - sum(ifnull(paid,'')), 2) as salary_payable 
                from staff	
                join account_vouchers on staff.id_staff = account_vouchers.business_partner_id
                join account_voucher_detail on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id
                
                left join (
                    select staffpayment_id, sum(debit) as paid from account_vouchers 
                    join account_voucher_detail on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id
                    where voucher_status='Active' and staffpayment_id is not null
                    group by staffpayment_id
                ) as payments on payments.staffpayment_id = account_vouchers.id_account_vouchers

                where business_partner =3   
                and credit > 0
                and account_vouchers.voucher_status='Active'
                and account_voucher_detail.account_head_id = ". $account_heads[0] . "                
                and account_vouchers.business_id=".$businessid." ";
        if(null !== $staff_id){
            $sql .= " and id_staff = " . $staff_id;
        } else {
            $sql .= " group by id_staff, id_account_vouchers, business_partner_id order by staff_eid;";
        }
      // echo $sql; exit();
        $query = $this->db->query($sql);
        
        return $query->result_array();     
        
    }

    public function check_payable($staffid, $month, $year){
        
        $sql = "SELECT * FROM account_vouchers
                where business_partner=3
                and business_partner_id=".$staffid."
                and account_vouchers.voucher_status='Active'
                and description like 'Salary Payable%".$month."% ".$year."%'";
        
        $query = $this->db->query($sql);
        
        return $query->result_array();    
        
    }
    
    public function create_payable_voucher($row, $month, $year, $voucherdate){
//        print_r($row);
//        
//        foreach($row as $key => $value){
//            
//                //print_r($key); 
//                
//                $allowance_accounts = $this->accounting_model->get_mapped_account_by_name($key);
//                echo'<pre>';
//                print_r($allowance_accounts) ;
//               echo'</pre>';            
//        }
        
        ///create payable account voucher
       // exit();
        $count=0;
        if($this->session->userdata('auto_voucher')=='Yes' && $row['final_payable']>0){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(26);
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                   array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']."|".$ah['description']);
                } else {
                   array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']."|".$ah['description']);
                }
            }
            
            $bank_name='';
            $date = date_parse($month);
             if($voucherdate != null && $voucherdate !=''){
                 $my_month = sprintf("%02d", $date['month']);
                 
                 $voucherdate = $year.'-'.$my_month.'-28';
             }
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Salary Payable booked for Staff ' . $row['staff_fullname'] . ' ID: '.$row['staff_id'].' on '. date('d-m-Y').', for the Month '.$month.' '. $year,
                'voucher_date' => $voucherdate,
                'voucher_amount' => $row['staff_salary']+$row['staff_commission'],
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Back Office',
                'business_partner'=> 3,
                'business_partner_id'=>$row['staff_id'],
                'business_partner_name'=>$row['staff_fullname'],
                'voucher_type'=>3,
                'payment_mode'=>'Cash',
                'bank_name'=>$bank_name,
                'auto_voucher'=>'Yes'
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                
                if($debit[2]=="salary_expense"){$debitamount = $row['staff_salary'];}                
                if($debit[2]=="commission_service_expense"){$debitamount = $row['staff_commission'];}
                if($debit[2]=="commission_retail_expense"){$debitamount = $row['retail_commission'];}
                if($debit[2]=="provident_fund_employer"){$debitamount = $row['provident_fund_employer'];}
                if($debit[2]=="reimbursement_expense"){$debitamount = $row['reimbursements'];}
                //if($debit[2]=="bonus_expense"){$debitamount = $row['bonus'];}
                if($debit[2]=="miscellaneous_payments"){$debitamount = $row['miscellanous'];}
                //if($debit[2]=="rounded_adjustment" && $row['rounded_adjustment'] < 0.5){$debitamount= $row['rounded_adjustment'];}
                
                if($debit[3] == "Custom Allowance Increase"){
                    foreach($row as $key => $value){
                        $allowance_accounts = $this->accounting_model->get_mapped_account_by_name($key);
                        if(null!==$allowance_accounts){
                            $debitamount= $row[$debit[2]];                            
                        }
                    }
                }
                
                if(null==$debitamount || $debitamount==''){$debitamount=0;}
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //insert debit detail
                if($debitamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account); 
                //check entity
                
                if($credit[2]=="absent_deduction"){$creditamount= $row['deduction_absent'];}
                if($credit[2]=="late_deduction"){$creditamount = $row['deduction_late'];}                
                //if($credit[2]=="provident_fund_employee"){$creditamount= $row['provident_fund_employee'];}
                if($credit[2]=="tax_amount"){$creditamount= $row['tax_deduction'];}
                if($credit[2]=="other_deduction"){$creditamount= $row['other_deduction'];}
                if($credit[2]=="loan_deduction"){$creditamount= $row['loan_deduction'];}
                if($credit[2]=="salary_payable"){$creditamount= $row['final_payable'];}
                if($credit[2]=="provident_fund_payable"){$creditamount= $row['provident_fund_employee']+$row['provident_fund_employer'];}
                if($credit[2]=="rounded_adjustment"){$creditamount= $row['rounded_adjustment'];}
                
                if($credit[3] == "Custom Allowance Increase"){
                    foreach($row as $key => $value){
                        $allowance_accounts = $this->accounting_model->get_mapped_account_by_name($key);
                        if(null!==$allowance_accounts){
                            $creditamount= $row[$credit[2]];                            
                        }
                     }
                }
                
                if(null==$creditamount || $creditamount==''){ $creditamount=0;}
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
                    
            }
            $count=1;
        } else {
            $count=0;
        }
        return $count;
    }

    public function create_payment_voucher($row, $payment_mode, $credit_account_id, $instrument_number, $account_voucher_date, $staffpayment_id){
        //print_r($row);
        //exit();
        $count=0;
        if($this->session->userdata('auto_voucher')=='Yes' && $row['payingnow'] > 0){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $dAccount = $this->accounting_model->get_event_account(26, 'salary_payable');
            $debit_account = $dAccount->account_head_id;
            //var_dump ($account_heads); exit();
            
            $bank_name='';
            
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Salary & Wages Paid out to Staff: ' . $row['staff_fullname'] . ' ID: '.$row['staff_id'].' on '.$account_voucher_date,
                'voucher_date' => $account_voucher_date,
                'voucher_amount' => $row['payingnow'],
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Back Office',
                'business_partner'=> 3,
                'business_partner_id'=>$row['staff_id'],
                'business_partner_name'=>$row['staff_fullname'],
                'voucher_type'=>1,
                'payment_mode'=> $payment_mode,
                'bank_name' => '',
                'auto_voucher'=>'Yes',
                'staffpayment_id' => $row['voucher_id'] 
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            $debitamount=0;
            $debitamount = $row['payingnow'];
            if(null==$debitamount || $debitamount==''){$debitamount=0;}
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $debit_account,
                'instrument_number' => $instrument_number,
                'debit' => round($debitamount,2),
                'credit' => 0
            );
            //insert debit detail
            if($debitamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }


            //enter credit entries
            $creditamount=0;
            $creditamount = $row['payingnow'];
            if(null==$creditamount || $creditamount==''){$creditamount=0;}
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $credit_account_id,
                'instrument_number' => $instrument_number,
                'credit' => round($creditamount,2),
                'debit' => 0
            );
            //insert debit detail
            if($creditamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
            $count++;
        }
        return $count;
    }
    
    
    function staff_month_loan_installment($staff_id){
        
        $this->db->select('*');
        $this->db->where('account_event_mapping.account_event_id', 26);
        $this->db->where('account_event_mapping.entity_name','loan_deduction');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $query1 = $this->db->get('account_event_mapping');
        
        $ah = $query1->row();

        if($query1->num_rows() > 0){
            $account_head = $ah->account_head_id;

            $sql = "SELECT id_staff, business_partner_id, ifnull(sum(debit),0) as debit, ifnull(sum(credit),0) as credit, ifnull(sum(debit) - sum(credit),0) as balance
                    FROM staff
                    left join (
                            Select business_partner_id, sum(debit) debit, sum(credit) credit
                            from account_vouchers 
                            join account_voucher_detail on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id
                            where account_head_id = ".$account_head."
                            and business_partner=3
                            and business_partner_id = ".$staff_id."
                            and voucher_status = 'Active'
                        group by business_partner_id
                        ) as account_vouchers
                    on account_vouchers.business_partner_id = staff.id_staff 
                    where id_staff=".$staff_id."
                    group by business_partner_id";
            
            $query = $this->db->query($sql);

            $totalloan = $query->result_array();              

            $sql = "SELECT  staff_id, ceil(sum(loan_applications.installment)) balance, sum(debit)-sum(credit) totalbalance
                    FROM loan_applications
                    join account_vouchers on account_vouchers.loan_application_id = loan_applications.id_loan_applications
                    join account_voucher_detail on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
                    WHERE loan_applications.staff_id = ".$staff_id."
                    AND loan_applications.application_status='Approved'
                    AND account_vouchers.voucher_status='Active'
                    AND account_voucher_detail.account_head_id = ".$account_head."
                    GROUP BY staff_id";
            
            $query1 = $this->db->query($sql);

            $applicationloan =  $query1->result_array();    

            if($query1->num_rows() > 0){
                if($totalloan[0]['balance'] > $applicationloan[0]['totalbalance']){
                    $installment =  $totalloan[0]['balance'] - $applicationloan[0]['totalbalance'];
                    $installment = array( 'balance'=>$installment + $applicationloan[0]['balance']);
                    $loan = [];
                    array_push($loan, $installment);
                    return  $loan;
                }else{
                    return $applicationloan;
                }
            }else{
                return $totalloan;
            }
            
        }else {
            return  false;
        }
    }
    
    function get_floors($business_id=null){
        
        if($business_id == null){
            $business_id = $this->session->userdata('businessid');
        }
        
        $this->db->select('*');
        $this->db->where('floor_status', 'Active');
        $this->db->where('business_id', $business_id);
        $query = $this->db->get('business_floors');
        //echo $query; exit();
        return $query->result_array();
    }
    
}
