<?php

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

class Staff_controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // Your own constructor code
        $this->load->model('staff_model');
        $this->load->model('business_model');
        $this->load->model('accounting_model');
        $this->load->model('attendance_model');
       
        if ($this->session->userdata('role') == '') {
            redirect('logout');
        }
    }

    public function getschedulerstaff(){
        
        $data = $this->staff_model->get_scheduler_staff();
        echo(json_encode($data));
        
    }
    
    public function presentstaff() {
        //get the posted values

        $data = $this->staff_model->get_present_staff();
        echo(json_encode($data));
    }

    public function availablestaff() {
        //get the posted values

        $data = $this->staff_model->get_available_staff();
        echo(json_encode($data));
    }

    public function absentstaff() {
        //get the posted values

        $data = $this->staff_model->get_absent_staff();
        echo(json_encode($data));
    }

    public function checkStaffStatus() {

        $result = $this->staff_model->check_staff_status();
        if ($result && is_null($result->time_out)) {
            echo 'online';
        } else {
            echo 'offline';
        }
    }

    public function timein() {
        //get the posted values
        $mytime=null;
        
        if(null !== $this->input->post('mydatetime')){
            $mytime=$this->input->post('mydatetime');
        }else if(null !== $this->input->post('mdate')){
            $mytime=$this->input->post('mdate').date(' h:i:s');
           
        }
        
        $result = $this->staff_model->update_timein($mytime);
        echo "success|" . $result;
    }

    public function timeout() {
        //get the posted values
        $mytime=null;
        
        if(null !== $this->input->post('mydatetime')){
            $mytime=$this->input->post('mydatetime');
        }
        
        $result = $this->staff_model->update_timeout($mytime);
        echo "success|" . $result;
    }

    public function staff_list() {
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            //storemanager,hr,reception...user serial
            checkroles(1, 1, 0);

            $data['nav'] = 'my_business';
            $data['subnav'] = 'staff';

            $data['staffs'] = $this->staff_model->all_staff();
            $data['business'] = $this->business_model->getbusinessdetails();

            $startdate= date("Y-n-j", strtotime("first day of previous month"));
            $enddate= date("Y-n-j", strtotime("last day of previous month"));
            $this->load->model('report_model');
            //$data['commissions']=$this->report_model->commissions($startdate, $enddate);
            $data['commissions']=[];
            $data['lastmonthyear']=  $this->sqldates_model->lastmonthyear();

            $data['bank_accounts'] = $this->accounting_model->get_account_heads(3,'all',$this->session->userdata('businessid'));
            $data['cash_accounts'] = $this->accounting_model->get_account_heads(2,'all',$this->session->userdata('businessid'));

            $data['deduction_policies'] = $this->staff_model->get_deduction_policies();
            $data['allowances'] = $this->staff_model->get_allowances($this->session->userdata('businessid'));
            
            $data['floors'] = $this->staff_model->get_floors($this->session->userdata('businessid'));
            
           

            $row1= $this->staff_model->getHrmServer();
            $data['serverurl'] = $row1->serverurl; 
           // print_r($data['deduction_policies'] ); exit();
            
            $this->load->view('includes/header', $data);
            $this->load->view('staff/staff_list_view');
            $this->load->view('includes/footer');
        }
    }
    
    

    
    public function get_commissions(){
        
        $month = $this->input->post('month');
        $year = $this->input->post('year');
        
        $startdate=  $year."-".$month."-1";
        $enddate= $year."-".$month."-31";
        $this->load->model('report_model');
        $data=$this->report_model->commissions($startdate, $enddate);
        
        echo json_encode($data);
        
    }

    public function add_staff() {
        $result = $this->staff_model->add_staff();
        echo "success|" . $result;
    }

    public function update_staff() {
        
        $result = $this->staff_model->update_staff();
        echo "success|" . $result;
    }

    public function update_staff_scheduler() {
        $result = $this->staff_model->update_staff_scheduler();
        echo "success|" . $result;
    }
    
    public function update_staff_shared() {
        $result = $this->staff_model->update_staff_shared();
        echo "success|" . $result;
    }
    
    function staff_status() {
        $result = $this->staff_model->staff_status();
        echo "success";
        
    }

    public function image_staff() {
        
        if ($this->input->post('id_image_staff', TRUE) && $this->input->post('id_image_staff', TRUE) != "") {
            $image = "";
            if ($_FILES['staff_image']['name'] && $_FILES['staff_image']['name'] != "") {
                $image = $this->image_upload('images/staff', 'staff_image', 'gif|jpg|png');
                if ($image == FALSE) {
                    $this->session->set_flashdata('errorimage', 'The image dimension must be 128 X 128');
                    //redirect($this->session->userdata('tips_tricks_edit_url'));
                    redirect(base_url('staff_list'));
                } else {
                    $image = $image;
                }
            } else {
                $image = ($this->input->post('org_image', TRUE) != "" ? $this->input->post('org_image', TRUE) : NULL);
            }

            $result = $this->staff_model->image_staff($image);
            if ($result) {
                redirect(base_url('staff_list'));
            }
        }
    }

    function image_upload($folder = NULL, $image = NULL, $type = NULL, $width = NULL, $height = NULL, $encrypt = NULL) {
        $config['upload_path'] = 'assets/' . $folder . '/';
        $config['allowed_types'] = $type;
        $config['max_size'] = '2048';

        if ($width != NULL && $height != NULL) {
            $config['max_width'] = $width;
            $config['max_height'] = $height;
        }
        if ($encrypt != NULL) {
            $config['encrypt_name'] = TRUE;
        }

        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        if (!$this->upload->do_upload($image)) {
            return FALSE;
        } else {
            return $this->upload->data('file_name');
        }
    }

    public function order_function() {
        $id = $this->input->post('id');
        $orderid = $this->input->post('orderid');

        $result = $this->staff_model->update_order_function($id, $orderid);
        echo('success|' . $result);
        die;
    }

    public function changelistorder() {
        $result = $this->staff_model->changelistorder();
        echo('success|' . 1);
        die;
    }
    
    public function edit_staff(){
        $data['staff'] = array();
        $data['allowances'] = array();
        
        $staff = $this->staff_model->edit_staff();
        $allowances = $this->staff_model->staff_allowances();
        
        array_push($data['staff'], $staff);
        
        array_push($data['allowances'], $allowances);
        
        echo (json_encode($data));
        die;
    }

    
    public function get_active_staff(){
        
        $data = $this->staff_model->get_active_staff();
        echo (json_encode($data));
        die;
        
    }
    
    public function updatesalaries(){
         // Unescape the string values in the JSON array
        $tableData = stripcslashes($this->input->post('salarydata'));

        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        // now $tableData can be accessed like a PHP array
        
        $data = [];
        $count=0;
        $date=date("Y-m-d H:i:s");
        
        $count=0;
        
//        print_r($tableData);
//        exit();
        
        foreach($tableData as $row){
            $check_existing = $this->staff_model->check_salary_record($row['staff_id'],$this->input->post('month'),$this->input->post('year'));
            //echo var_dump($check_existing); exit();
            if(sizeOf($check_existing)>0 && $check_existing[0]['staff_id']==$row['staff_id']){
                //do nothing as salary already exists
            } else {
                if($row['payment_amount']>0){
                    $datasalary = array(
                        'created_by' => $this->session->userdata('businessid'),
                        'staff_id' => $row['staff_id'],
                        'staff_name' => $row['staff_name'],
                        'payment_amount' => $row['payment_amount'],
                        'payment_type' => $row['payment_type'],
                        'payment_mode' =>  $this->input->post('salarymode'),
                        'payment_remarks' => $row['payment_remarks'],
                        'payment_date' => $date,
                        'payment_month' => $this->input->post('month'),
                        'payment_year' => $this->input->post('year')
                    );
                    $staffpayment_id=$this->staff_model->update_salaries($datasalary);
                    
                    ///create account voucher
                    if($this->session->userdata('auto_voucher')=='Yes'){
                        $debit_accounts=[];
                        $credit_accounts=[];

                        $account_heads = $this->accounting_model->get_mapped_accounts(25);
                        //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']);
                            } else {
                                array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                            }
                        }

                        $bank_name='';
                        //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
                        $data = array( 
                            'business_id' => $this->session->userdata('businessid'),
                            'description' => 'Salary paid to ' . $row['staff_name'] . ' on '. date('d-m-Y').' for the month '. $this->input->post('month') .', staff ID : '. $row['staff_id'].' '.$row['payment_remarks'],
                            'voucher_date' => date('Y-m-d H:i:s'),
                            'voucher_amount' => $row['payment_amount'],
                            '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_name'],
                            'voucher_type'=>1,
                            'payment_mode'=>$row['payment_amount'],
                            'bank_name'=>$bank_name,
                            'staffpayment_id'=>$staffpayment_id,
                            '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]=="amount_paid" && $row['payment_amount'] > 0){$debitamount= $row['payment_amount'];}

                            $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 entry
                        
                        if($this->input->post('salarymode')=="cash"){
                            $account_head_id = $this->input->post('cash_accounts');
                        }
                        if($this->input->post('salarymode')=="check"){
                            $account_head_id = $this->input->post('bank_accounts');
                        }
                        $data_detail=array(
                            'account_voucher_id' => $account_voucherid,
                            'account_head_id' => $account_head_id,
                            'debit' => 0,
                            'credit' => round($row['payment_amount'],2)
                        );
                        //insert credit detail
                        if($row['payment_amount']>0){
                            $this->db->insert('account_voucher_detail', $data_detail);
                        }

                    }

                    $count++;
                }
            }
            
        }
        
        echo "success|".$count;
        
    }
    
    public function updatecommissions(){
        
         // Unescape the string values in the JSON array
        $tableData = stripcslashes($this->input->post('commissionsdata'));

        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        // now $tableData can be accessed like a PHP array
        
        $data = [];
        $count=0;
        $date=date("Y-m-d H:i:s");
        
        $count=0;
        foreach($tableData as $row){
            $check_existing = $this->staff_model->check_commission_record($row['staff_id'],$this->input->post('month'),$this->input->post('year'));
            //echo sizeOf($check_existing); exit();
            if(sizeOf($check_existing)>0 && $check_existing[0]['staff_id']==$row['staff_id']){
                //do nothing as salary already exists
            } else {
                $datacommission = array(
                    'created_by' => $this->session->userdata('businessid'),
                    'staff_id' => $row['staff_id'],
                    'staff_name' => $row['staff_name'],
                    'payment_amount' => $row['payment_amount'],
                    'payment_type' => $row['payment_type'],
                    'payment_mode' =>  $this->input->post('paymentmode'),
                    'payment_remarks' => $row['payment_remarks'],
                    'payment_date' => $date,
                    'payment_month' => $this->input->post('month'),
                    'payment_year' => $this->input->post('year')
                );
                $staffpayment_id=$this->staff_model->update_salaries($datacommission);
                
                ///create account voucher
                    if($this->session->userdata('auto_voucher')=='Yes'){
                        $debit_accounts=[];
                        $credit_accounts=[];

                        $account_heads = $this->accounting_model->get_mapped_accounts(25);
                        //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']);
                            } else {
                                array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                            }
                        }

                        $bank_name='';
                        //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
                        $data = array( 
                            'business_id' => $this->session->userdata('businessid'),
                            'description' => 'Commissions paid to ' . $row['staff_name'] . ' on '. date('d-m-Y').', staff ID : '. $row['staff_id'].', For the month of '. $this->input->post('month').' '.$this->input->post('year') .' , '.$row['payment_remarks'],
                            'voucher_date' => date('Y-m-d H:i:s'),
                            'voucher_amount' => $row['payment_amount'],
                            '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_name'],
                            'voucher_type'=>1,
                            'payment_mode'=>$row['payment_amount'],
                            'bank_name'=>$bank_name,
                            'staffpayment_id'=>$staffpayment_id,
                            '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]=="commissions_amount" && $row['payment_amount'] > 0){$debitamount= $row['payment_amount'];}

                            $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 entry
                        
                        if($this->input->post('paymentmode')=="cash"){
                            $account_head_id = $this->input->post('cash_accounts');
                        }
                        if($this->input->post('paymentmode')=="check"){
                            $account_head_id = $this->input->post('bank_accounts');
                        }
                        $data_detail=array(
                            'account_voucher_id' => $account_voucherid,
                            'account_head_id' => $account_head_id,
                            'debit' => 0,
                            'credit' => round($row['payment_amount'],2)
                        );
                        //insert credit detail
                        if($row['payment_amount']>0){
                            $this->db->insert('account_voucher_detail', $data_detail);
                        }

                    }
                
                $count++;
            }
            
        }
        
        echo "success|".$count;
        
       
    }
    
    public function add_payment(){
//        echo $this->input->post('payment_type');
//        exit();
        $staffpayment_id=$this->staff_model->add_payment();
        
        ///create account voucher
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];

            $account_heads = $this->accounting_model->get_mapped_accounts(25);
            //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']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }

            $bank_name='';
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => $this->input->post('payment_type').' paid to ' . $this->input->post('staff_name') . ' on '. date('d-m-Y'). ' For the month of '. $this->input->post('payment_month') .' '. $this->input->post('payment_year'). ', staff ID : '. $this->input->post('staff_id').'. '. $this->input->post('payment_remarks'),
                'voucher_date' => $this->input->post('payment_date'),
                'voucher_amount' => $this->input->post('payment_amount'),
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Back Office',
                'business_partner'=> 3,
                'business_partner_id'=>$this->input->post('staff_id'),
                'business_partner_name'=>$this->input->post('staff_name'),
                'voucher_type'=>1,
                'payment_mode'=>$this->input->post('payment_mode'),
                'bank_name'=>$bank_name,
                'staffpayment_id'=>$staffpayment_id,
                '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]=="amount_paid" && $this->input->post('payment_type')=="Salary" && $this->input->post('payment_amount') > 0){$debitamount= $this->input->post('payment_amount');}
                if($debit[2]=="commissions_amount" && $this->input->post('payment_type')=="Commission" && $this->input->post('payment_amount') > 0){$debitamount= $this->input->post('payment_amount');}
                if($debit[2]=="bonus_amount" && $this->input->post('payment_type')=="Bonus" && $this->input->post('payment_amount') > 0){$debitamount= $this->input->post('payment_amount');}
                if($debit[2]=="allowance_amount" && $this->input->post('payment_type')=="Allowance" && $this->input->post('payment_amount') > 0){$debitamount= $this->input->post('payment_amount');}
                if($debit[2]=="gift_amount" && $this->input->post('payment_type')=="Gift"  && $this->input->post('payment_amount') > 0){$debitamount= $this->input->post('payment_amount');}
                if($debit[2]=="special_occasion_amount" && $this->input->post('payment_type')=="Special Occasion"  && $this->input->post('payment_amount') > 0){$debitamount= $this->input->post('payment_amount');}
                if($debit[2]=="loan_amount" && $this->input->post('payment_type')=="Loan"  && $this->input->post('payment_amount') > 0){$debitamount= $this->input->post('payment_amount');}
                
                $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 entry

            if($this->input->post('payment_mode')=="cash"){
                $account_head_id = $this->input->post('cash_account_id');
            }
            if($this->input->post('payment_mode')=="Bank"){
                $account_head_id = $this->input->post('bank_account_id');
            }
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $account_head_id,
                'debit' => 0,
                'credit' => round($this->input->post('payment_amount'),2)
            );
            //insert credit detail
            if($this->input->post('payment_amount')>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }

        }

        echo "success|".$staffpayment_id;
        
    }
    
    public function staff_account($staffid){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            //storemanager,hr,reception...user serial
           checkroles(1, 1, 0);

           $data['nav'] = 'my_business';
           $data['subnav'] = 'staff';

           $data['details'] = $this->staff_model->staff_details($staffid);
        
           $data['salary'] = $this->staff_model->staff_salary($staffid);
           
           $accounts = $this->accounting_model->get_event_account(25, 'loan_amount');
           $loanaccount = $accounts->account_head_id;
              
           $data['loan'] = $this->staff_model->staff_loan($staffid, $loanaccount);
           
           $data['payment_types'] = $this->staff_model->get_staff_payment_types();
           
           $data['bank_accounts'] = $this->accounting_model->get_account_heads(3,'all',$this->session->userdata('businessid'));
           $data['cash_accounts'] = $this->accounting_model->get_account_heads(2,'all',$this->session->userdata('businessid'));

           $data['business'] = $this->business_model->getbusinessdetails();
           $data['lastmonthyear']=  $this->sqldates_model->lastmonthyear();

           $this->load->view('includes/header', $data);
           $this->load->view('staff/staff_account');
           $this->load->view('includes/footer');
           
           
        }
        
    }
    
    public function paymentslips(){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['business'] = $this->business_model->getbusinessdetails();
            $data['lastmonthyear']=  $this->sqldates_model->lastmonthyear();
            
            $data['staff']= $this->staff_model->get_active_staff();
            
            $data['selected_staff'] = 0;
            
            
            $this->load->view('includes/header', $data);
            $this->load->view('staff/print_payment_slips');
            $this->load->view('includes/footer');
        }
    }
    public function printslips(){
       
        $voucherid=0;
        
        if(null !==$this->input->post('voucherid')){
            $voucherid=$this->input->post('voucherid');
        }
        
        $vouchers = $this->staff_model->printslips($this->input->post('staff_id'), $this->input->post('selected_month'), $this->input->post('selected_year'), $voucherid, $this->input->post('month'));
//        echo '<pre>';
//        print_r($vouchers); 
//        echo  '</pre>';
        
        $data['vouchers'] = [];
        $data['payments'] = [];
        foreach($vouchers as $voucher){            
            $data['vouchers'][$voucher['id_account_vouchers']][] = $voucher;
        }

        foreach($data['vouchers'] as $key=>$val){
            
            $payments = $this->staff_model->printpayments($this->input->post('staff_id'), $this->input->post('selected_month'), $this->input->post('selected_year'), $key);
            foreach($payments as $payment){            
                $data['vouchers'][$voucher['id_account_vouchers']]['payments'][] = $payment;               
            }
        }
//        echo '<pre>';
//        print_r($data['vouchers'] ); 
//        echo  '</pre>';
//        exit();
        
        $data['business'] = $this->business_model->getbusinessdetails();
        $data['staff']= $this->staff_model->get_active_staff();
        
        $data['selected_staff'] = $this->input->post('staff_id');
        $data['lastmonthyear'][0] = array( 
            'MonthName'=>$this->input->post('month') ,
            'Month'=>$this->input->post('selected_month') ,
            'Year'=>$this->input->post('selected_year')
                );
        
        
        $this->load->view('includes/header', $data);
        $this->load->view('staff/print_payment_slips');
        $this->load->view('includes/footer');
    }
    
    public function searchpayments(){
        
        $voucherid=0;
        
        if(null !==$this->input->post('voucherid')){
            $voucherid=$this->input->post('voucherid');
        }
        
        $data = $this->staff_model->searchpayments($this->input->post('staff_id'), $this->input->post('payment_month'), $this->input->post('payment_year'), $voucherid);
        echo (json_encode($data));
    }

    

    
     public function openstaffrecieveslip(){
        
        $voucherid=0;
        
        if(null !== $this->input->post('voucherid')){
            $voucherid=$this->input->post('voucherid');
        }
        $data['business'] = $this->business_model->getbusinessdetails();
        $data['slip_data'] = $this->staff_model->searchpayments($this->input->post('staff_id'), $this->input->post('payment_month'), $this->input->post('payment_year'), $voucherid);
        
        if($this->session->userdata('role')=='Sh-Users'){
                 $this->load->view('includes/sh_header', $data);
            }else {
                $this->load->view('includes/header', $data);
            }
            $this->load->view('staff/print_receiving_slip');
            $this->load->view('includes/footer');
        
    }
    
    public function day_attendance(){
        //echo 'dayattendace'; exit();
        if($this->session->userdata('role')==''){
            $this->load->view('login_view');
        } else { 
            $data['nav'] = 'invoice';
           $data['subnav'] = 'attendance';

            $this->db->select('qr_enabled');
            $this->db->where('id_business', $this->session->userdata('businessid'));
            $q = $this->db->get('business');            
            $qr_enabled = $q->row();
            
            if($qr_enabled->qr_enabled == 'Yes'){
                if($this->session->userdata('role') == 'Super User' || $this->session->userdata('role') == 'HR' || $this->session->userdata('role') == 'Manual Attendance') {    
                //} else if($this->session->userdata('role') == 'Admin' || $this->session->userdata('role') == 'Super User' || $this->session->userdata('role') == 'Reception') {    

                    if(null!==$this->input->post('myDate')){
                        $mydate=$this->input->post('myDate');
                    }else{
                        $mydate=date('Y-m-d');
                    }

                    $data['staff']= $this->staff_model->day_attendance($mydate);

                    $data['mydate']= $mydate;

                    if($this->session->userdata('role')=='Sh-Users'){
                         $this->load->view('includes/sh_header', $data);
                    }else {
                        $this->load->view('includes/header', $data);
                    }
                    $this->load->view('attendance_view');
                    $this->load->view('includes/footer');
                } else {
                    $data['nav'] = 'report';
                    $data['subnav'] = 'attendance';

                    $data['business']=$this->business_model->getbusinessdetails();

                    //$qr= $this->getRandomString(8);

                    //$this->attendance_model->update_qr($qr);

                    $data['key_code'] = $this->attendance_model->get_qr();

                    $this->load->view('includes/header', $data);
                    $this->load->view('key_code_generator'); 
                    $this->load->view('includes/footer');
                }
            } else {
                if(null!==$this->input->post('myDate')){
                    $mydate=$this->input->post('myDate');
                }else{
                    $mydate=date('Y-m-d');
                }

                $data['staff']= $this->staff_model->day_attendance($mydate);

                $data['mydate']= $mydate;

                if($this->session->userdata('role')=='Sh-Users'){
                     $this->load->view('includes/sh_header', $data);
                }else {
                    $this->load->view('includes/header', $data);
                }
                $this->load->view('attendance_view');
                $this->load->view('includes/footer');
            }
        }
    }
    
    public function searchnameforstaff(){
        
        $staffname = $this->input->get("staffname", TRUE);
        $data = $this->staff_model->searchnameforstaff($staffname);

        echo(json_encode($data));
        
    }
    
    
    public function check_availability(){
        
        
        $staffids = $this->input->post("staffids", TRUE);
        $dates = $this->input->post("dates", TRUE);
        $bookedminutes=[];
        
        for($x=0; $x <= sizeof($staffids)-1; $x++){
            array_push($bookedminutes, $this->staff_model->get_staff_booked_min($staffids[$x], $dates[$x]));
            
        }
        
        echo(json_encode($bookedminutes)); 
    }
    
    
    
    public function business_staff_payables($business_id, $month, $year){
        
        $staff = $this->staff_model->business_staff($business_id);
        $data =[]; 
        
        foreach($staff as $s){
            $payables = $this->staff_model->staff_month_payables($s['id_staff'], $year, $month);
            $commission = $this->staff_model->staff_month_commission($s['id_staff'], $year, $month);
            if(sizeof($payables)>0 && sizeof($commission)>0){
                $record = array_merge($payables, $commission);
                array_push($data, $record); 
            }
        }
        //echo '<pre>';
        //print_r($data);exit();
        echo json_encode($data);
        
    }   
   
    
    public function staff_month_attendance_all($business_id, $month, $year){
        
        $staff = $this->staff_model->business_staff($business_id);
        $data =[]; 
        
        foreach($staff as $s){
            $record = $this->staff_model->staff_month_attendance_detail($s['id_staff'], $year, $month);
            
            array_push($data, $record); 
        }
        
        echo json_encode($data);
    }
    
    public function staff_month_attendance_single($staff_id, $month, $year){
        $data = $this->staff_model->staff_month_attendance_detail($staff_id, $year, $month);
        echo json_encode($data);
    }
    
    public function staff_month_commission_all($business_id, $month, $year){
        
        $staff = $this->staff_model->business_staff($business_id);
        $data =[]; 
        
        foreach($staff as $s){
            $record = $this->staff_model->staff_month_commission_detail($s['id_staff'], $year, $month);
            array_push($data, $record); 
        }
        
        echo json_encode($data);
    }
    
    public function staff_month_commission_single($staff_id, $month, $year){
        $data = $this->staff_model->staff_month_commission_detail($staff_id, $year, $month);
        echo json_encode($data);
    }
    
    public function staff_payment_calculator($business_id=null){
       //exit();
    
       if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {

            if(null != $this->input->post('business_id')){
                $business_id=$this->input->post('business_id');
            }


            $staff=0; $data['selectedstaff']=0;
            if(null !== $this->input->post('staff_id')){
                $staff = $this->input->post('staff_id');
                $data['selectedstaff']=$this->input->post('staff_id');
            }

            if(null !== $this->input->post('month')){
                $month =  $this->input->post('month');
                $year =   $this->input->post('year');      
            } else {
                $month =  date("m", strtotime("first day of previous month"));
                $year =   date('Y');
            }
            
          
            
            if(null == $business_id){
                $data['business'] = $this->business_model->getbusinessdetails();
                $business_id = $data['business'][0]['id_business'];
            } else{
                $data['business'] = $this->business_model->getbusinessdetails($business_id);
            }
            
            if($this->session->userdata('common_products')=='Yes'){
                $data['branches']=$this->business_model->get_all_branches();
            }else{
                $data['branches']=[];
            }
            
            $data['staff'] = $this->staff_model->business_staff($business_id);

            $data['allowances'] = $this->staff_model->get_allowances($business_id);
            
            
            if(date_format(date_create($year."-".$month.""),'Y-m-d') <= date('Y-m-d')){

                //$staff = $this->staff_model->business_staff($business_id);
                $list =[]; 
                $allowances = [];
                //foreach($staff as $s){
                if($staff>0){    
                    $payable = $this->staff_model->staff_month_payables($staff, $year, $month);
                    $commission = $this->staff_model->staff_month_commission($staff, $year, $month);                    
                    $retail_commission = $this->staff_model->staff_month_retail_commission($staff, $year, $month);
                    $allo= $this->staff_model->staff_month_allowances($staff);
                    $l = $this->staff_model->staff_month_loan_installment($staff);
                                        
                    $allowances = array('allowances' => $allo);
                    $loan = array('loan'=> $l);
                    
                            
                    $record = array_merge($payable, $commission, $retail_commission, $allowances, $loan);
                    array_push($list, $record); 
                }
                //}

                $data['payables'] = $list;
                //echo '<pre>'; print_r($data['payables']); exit();
            }else{
                $data['payables'] = [];
            }
            
            
            $data['month'] = $month;
            $data['year'] = $year;
            
            $monthNum  = $month;
            $dateObj   = DateTime::createFromFormat('!m', $monthNum);
            $data['monthName'] = $dateObj->format('F'); // March
            //echo $data['monthName'] ; exit();
            
            $this->load->view('includes/header', $data);
            $this->load->view('staff/staff_payment_calculator');
            $this->load->view('includes/footer');
        }
    }
    
    public function view_staff_attendance_single($staff_id, $month, $year){
        
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['payables'] = $this->staff_model->staff_month_attendance_detail($staff_id, $year, $month);
            
            $data['month'] = $month;
            $data['year'] = $year;
            
            $monthNum  = $month;
            $dateObj   = DateTime::createFromFormat('!m', $monthNum);
            $data['monthName'] = $dateObj->format('F'); // March
            
            $this->load->view('includes/header', $data);
            $this->load->view('staff/staff_attendance_single');
            $this->load->view('includes/footer');
        }    
        

    }
    
    public function view_staff_commission_single($staff_id, $month, $year){
        
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['payables'] = $this->staff_model->staff_month_commission_detail($staff_id, $year, $month);
            
            $data['month'] = $month;
            $data['year'] = $year;
            
            $monthNum  = $month;
            $dateObj   = DateTime::createFromFormat('!m', $monthNum);
            $data['monthName'] = $dateObj->format('F'); // March
            
            $this->load->view('includes/header', $data);
            $this->load->view('staff/staff_commission_single');
            $this->load->view('includes/footer');
        } 
    }
    
    public function view_retail_staff_commission_single($staff_id, $month, $year){
        
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['payables'] = $this->staff_model->staff_month_retail_commission_detail($staff_id, $year, $month);
            
            $data['month'] = $month;
            $data['year'] = $year;
            
            $monthNum  = $month;
            $dateObj   = DateTime::createFromFormat('!m', $monthNum);
            $data['monthName'] = $dateObj->format('F'); // March
            
            $this->load->view('includes/header', $data);
            $this->load->view('staff/staff_retail_commission_single');
            $this->load->view('includes/footer');
        } 
    }
    
    
    public function staff_payables_receivables($businessid){
        
        $salary_account = $this->accounting_model->get_event_account(26, 'salary_payable');
        $loan_account = $this->accounting_model->get_event_account(25, 'loan_amount');
        
        $account_heads[0]=$salary_account->account_head_id;
        $account_heads[1]=$loan_account->account_head_id;
        
        $data = $this->staff_model->staff_payables_receivables($businessid, $account_heads);
        echo json_encode($data);
        
    }
    
    public function view_staff_payables_receivables($businessid){
        
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            
            $data['business'] = $this->business_model->get_business_details();

            $data['bank_accounts'] = $this->accounting_model->get_account_heads(3,'all',$this->session->userdata('businessid'));
            $data['cash_accounts'] = $this->accounting_model->get_account_heads(2,'all',$this->session->userdata('businessid'));
            $data['card_accounts'] = $this->accounting_model->get_account_heads(8,'all',$this->session->userdata('businessid'));
            
            $salary_account = $this->accounting_model->get_event_account(26, 'salary_payable');
            $loan_account = $this->accounting_model->get_event_account(25, 'loan_amount');

            $account_heads[0]=$salary_account->account_head_id;
            $account_heads[1]=$loan_account->account_head_id;

            $data['payables'] = $this->staff_model->staff_payables_receivables($businessid, $account_heads);
            
            $this->load->view('includes/header', $data);
            $this->load->view('staff/staff_payables_receivables');
            $this->load->view('includes/footer');
        } 
        
    }

    public function payable_approval_sheet($businessid){

        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            
            $data['business'] = $this->business_model->get_business_details();

            $salary_account = $this->accounting_model->get_event_account(26, 'salary_payable');
            $loan_account = $this->accounting_model->get_event_account(25, 'loan_amount');

            $account_heads[0]=$salary_account->account_head_id;
            $account_heads[1]=$loan_account->account_head_id;

            $data['payables'] = $this->staff_model->staff_payables_receivables($businessid, $account_heads);
            
            $this->load->view('includes/header', $data);
            $this->load->view('staff/payable_approval_sheet');
            $this->load->view('includes/footer');
        } 

    }

    public function resetappregistration(){
        $this->load->library('xmlrpc');
        $this->load->helper('url');
        
        $staffid= $this->input->post('staffid');
        $data = $this->staff_model->updateFCMToken($staffid);
        
        //hrm
//        $staff = $this->staff_model->staff_details($staffid);
//        //print_r($staff);exit();
//        $row1= $this->staff_model->getHrmServer();
//        $serverurl = $row1->serverurl;      
//        //print_r($serverurl);exit();
//        $this->xmlrpc->server($serverurl, 80);
//        $this->xmlrpc->method('updateFCMToken');
//
//        $request = '{"idStaff":"'.$staffid.'","fcmid":"","businessid":"'.$this->session->userdata('businessid').'","cellNumber":"'.$staff[0]['staff_cell'].'"}';
////        $request = array(
////                        array(
////                            'idStaff' => array($staffid, 'string'),
////                            'fcmid' => array('','string'),
////                            'businessid' => array($this->session->userdata('businessid'),'string'),
////                            'cellNumber' => array($staff[0]['staff_cell'],'string')
////                            )
////                        );
//
////        $request = json_encode($request);
////        $request = xml_convert($request);
////        print_r($request); exit();
//        $this->xmlrpc->request($request);
//        
//        if(!$this->xmlrpc->send_request())
//        {
//            echo $this->xmlrpc->display_error();
//        }
        echo "success|".$data;
    }
    
    function check_payable(){
        //exit();
        
        $month = $this->input->post('month');
        $year = $this->input->post('year');
        
        $tableData = stripcslashes($_POST['TableData']);

        // Decode the JSON array
        $tableData = json_decode($tableData, TRUE);
        //print_r($tableData);exit();
        $count = 0;
        foreach($tableData as $row){
            
            $check = $this->staff_model->check_payable($row['staff_id'], $month, $year);
            //print_r(sizeof($check));exit();
            
            if(sizeof($check)==0){
                //create new payable voucher
                $voucher = $this->staff_model->create_payable_voucher($row, $month, $year, $this->input->post('voucher_date'));
                $count=$count + $voucher;
            }
        }
        echo json_encode($count);
        
    }
    
    public function check_staff_payment(){
       
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            
            $payment_mode = $this->input->post('payment_mode');
            $instrument_number = $this->input->post('instrument_number');
            $bank_account = $this->input->post('bank_account');
            $cash_account = $this->input->post('cash_account');
            $card_account = $this->input->post('card_account');
            $account_voucher_date = $this->input->post('account_voucher_date');
            
            if(null==$payment_mode || $payment_mode=='')
            {
                echo 'error|Payment Mode not specified';
                exit();     
            }elseif($payment_mode=='Cash'){
                $credit_account_id=$this->input->post('cash_account');
            }elseif($payment_mode=='Bank'){
                $credit_account_id=$this->input->post('bank_account');
            }elseif($payment_mode=='Card'){
                $credit_account_id=$this->input->post('card_account');
            }else{
                echo 'error|Payment Mode not specified';
                exit();
            }
           
            
            if(null==$account_voucher_date || $account_voucher_date == ''){
                echo 'error|Payment date not specified';
                exit();
            }
            
            
            $tableData = stripcslashes($_POST['TableData']);
            $tableData = json_decode($tableData, TRUE);
            
           
            $count = 0;
            
            if(sizeof($tableData)>0){
                foreach($tableData as $row){
//                    echo '<pre>';
//                    print_r($row);
//                    echo '</pre>';
//                    exit();
                     $datasalary = array(
                        'created_by' => $this->session->userdata('userid'),
                        'staff_id' => $row['staff_id'],
                        'staff_name' => $row['staff_fullname'],
                        'payment_amount' => $row['payingnow'],
                        'payment_type' => 1,
                        'payment_mode' =>  'Cash',
                        'payment_remarks' => 'Payable Salary',
                        'payment_date' => date('Y-m-d'),
                        'month_number' => $row['month'],
                        'payment_year' => $row['year'],
                        'account_voucher_id' => $row['voucher_id']
                    );
                    $staffpayment_id=$this->staff_model->update_salaries($datasalary);
                
                    //create new payment voucher
                    $voucher = $this->staff_model->create_payment_voucher($row, $payment_mode, $credit_account_id, $instrument_number, $account_voucher_date, $staffpayment_id);
                    $count=$count + $voucher;
                }
            }else{
                echo 'error|No Staff Selected!';
                exit();
            }
            
            echo $count." vouchers created";
            exit();
        }
    }
    
    public function remove_attendance(){

        $id_attendance = $this->input->post('id_attendance');
        $id_staff = $this->input->post('id_staff');

        
        $sql="delete from staff_attendance where staff_id= ". $id_staff ." and id_staff_attendance = " . $id_attendance;

        $this->db->query($sql);
         echo "success";

    }
    
 }
