<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Salary_slips extends CI_Controller
{
  public $page_data = array();

  function __construct()
  {
    parent::__construct();
    $this->initial();
  }

  public function initial()
  {
    ini_set('max_execution_time', 5000);
    ini_set("memory_limit", "-1");

    $this->load->model('User_model', 'User');
    $this->load->model('Attendance_model', 'Attendance');
    $this->load->model('Work_model', 'Work');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Employees_model', 'Employee');
    $this->load->model('Salary_slips_model', 'Salary_slips');
    $this->load->library('Bills_management','bills_management');
    $this->load->model('Labour_model', 'Labour');
    $this->load->library('Projects_management','projects_management');
    $this->load->library('Accounts_management', 'accounts_management');

    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","general_manager","supervisor","accounts_manager","auditor","qs","qs_manager","hr_manager");
    if($this->User->is_logged_in($allowed_user_roles)==false){
      redirect(base_url(), 'refresh');
    }
    //        File Directory
    $this->page_data['directory'] = "hr";

    $this->db->where('(e.user_id=0 or (e.user_id!=0 and u.acc_status=1))');
    $this->page_data['employees'] = $this->Employee->select_employee("e.*,u.user_alias")->result();
  }

  public function index()
  {
    $this->view();
  }

  public function view()
  {
    $this->page_data['works'] = $this->Work->select_work("*")->result();
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['labours_2'] = $this->Labour->select_labours()->result();
    $user_accounts_where = "ur.role_name='supervisor' or ur.role_name='general_manager'";
    $this->page_data['user_accounts'] = $this->Account->select_account_heads("",$user_accounts_where,"user")->result();
    if($this->config->item('app_module_hr')==1 && ($this->session->userdata('user_role')=='accounts_manager' || $this->session->userdata('user_role')=='auditor' || $this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='madmin' || $this->session->userdata('user_role')=='hr_manager' || ($this->session->userdata('user_role')=='general_manager' && $this->config->item('User_general_manager_hr_data_enabled')==1))) {
      $this->page_data['page_name'] = 'salary_slips_view';
      $this->load->view('Index', $this->page_data);
    }else{
      redirect(base_url(), 'refresh');
    }
  }

  public function profile($id='')
  {
    if($id!=''){
      $salary_slip_data = $this->Salary_slips->select_salary_slips("e.employee_name,e.civil_id,e.phone_no,e.user_designation,ss.*,ss.basic_wage_type as basic_wage_type,ss.created_by as ss_created_by",array('ss.salary_id'=>$id));
      if($salary_slip_data->num_rows()==1){
        $this->page_data['salary_slip_data'] = $salary_slip_data->row();
        $this->page_data['salary_payments'] = $this->Account->select_account_transaction("ats.*,ah1.acc_head_name as debit_account,u1.user_alias as created_user", array("ats.reference_id" => $id, "ats.reference_type" => 'salary_slip'),'salary_slip')->result();

        $this->db->where("ats.tr_type",'salary_advance_transaction');
        $this->db->where("ats.tr_other_data",date('Y-m',strtotime($salary_slip_data->row()->month)));
        $this->page_data['advance_payments'] = $this->Account->select_account_transaction("ats.*,ah1.acc_head_name as debit_account,u1.user_alias as created_user", array("ats.reference_id" => $salary_slip_data->row()->employee_id, "ats.reference_type" => 'employee'),'employee')->result();

        $this->page_data['net_pay_in_words'] = $this->accounts_management->amount_in_words($this->page_data['salary_slip_data']->total_salary_amount-$this->page_data['salary_slip_data']->lwp_amount-$this->page_data['salary_slip_data']->advance_paid_amount);

        $this->page_data['page_name'] = 'salary_slip_profile';
        $this->load->view('Index', $this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }

  public function add()
  {
    $this->page_data['works'] = $this->Work->select_work("*")->result();
    if($this->config->item('app_module_hr')==1 && ($this->session->userdata('user_role')=='accounts_manager' || $this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='madmin' || ($this->session->userdata('user_role')=='general_manager' && $this->config->item('User_general_manager_hr_data_enabled')==1))) {
      // $this->page_data['page_name'] = 'salary_slips_add_'.$this->config->item('HR_salary_slip_template');
      $this->page_data['page_name'] = 'salary_slips_add';
      $this->load->view('Index', $this->page_data);
    }else{
      redirect(base_url(), 'refresh');
    }
  }
  public function create()
  {
    $data2['employee_id'] = $data3['ss.employee_id'] = $this->security->xss_clean($this->input->post('employee'));
    $data2['month'] = $data3['ss.month'] = date('Y-m-t',strtotime("01 ".$this->security->xss_clean($this->input->post('month'))));
    if($this->config->item('HR_salary_slip_allow_multiple_in_a_month')==0){
      $count = $this->Salary_slips->select_salary_slips("",$data3)->num_rows();
    }else{
      $count = 0;
    }
    $data2['slip_type'] = $this->security->xss_clean($this->input->post('salary_slip_type'));
    if($data2['slip_type']=='Project'){
      $data2['work_id'] = $this->security->xss_clean($this->input->post('work_id'));
      $data2['project_stage_id'] = $this->projects_management->get_project_stage_id($data2['work_id']);
    }
    $data2['basic_wage'] = $this->security->xss_clean($this->input->post('basic_wage'));
    $data2['basic_wage_type'] = $this->security->xss_clean($this->input->post('basic_wage_type'));
    $data2['basic_wage_fixed'] = $this->security->xss_clean($this->input->post('basic_wage_fixed'));
    $data2['month_days'] = $this->security->xss_clean($this->input->post('month_days'));
    $data2['hourly_rate'] = $this->security->xss_clean($this->input->post('hourly_rate_2'));
    $data2['daily_work_hour'] = $this->security->xss_clean($this->input->post('daily_work_hour'));
    $data2['holidays'] = $this->security->xss_clean($this->input->post('holidays'));
    $data2['medical_leave'] = $this->security->xss_clean($this->input->post('medical_leave'));
    $data2['absent'] = $this->security->xss_clean($this->input->post('absent'));
    $data2['worked_nos'] = $this->security->xss_clean($this->input->post('worked_nos'));
    $data2['regular_hours'] = $this->security->xss_clean($this->input->post('regular_hours'));
    $data2['overtime'] = $this->security->xss_clean($this->input->post('overtime'));
    $data2['overtime_period'] = $this->security->xss_clean($this->input->post('overtime_type'));
    $data2['overtime_rate'] = $this->security->xss_clean($this->input->post('overtime_rate'));
    $data2['overtime_amount'] = $this->security->xss_clean($this->input->post('overtime_amount'));
    if($this->config->item('HR_salary_slip_template')==3){
      $data2['bonus_percent'] = $this->config->item('HR_salary_bonus_percent');
      $data2['bonus_amount'] = $this->security->xss_clean($this->input->post('bonus_amount'));
      $data2['tiffin_rate_per_day'] = $this->config->item('HR_salary_tiffin_allowance_per_day');
      $data2['tiffin_allowance_amount'] = $this->security->xss_clean($this->input->post('tiffin_amount'));
      $data2['hra_percent'] = $this->config->item('HR_salary_hra_percent');
      $data2['hra_amount'] = $this->security->xss_clean($this->input->post('hra_amount'));
      $data2['ceb_percent'] = $this->config->item('HR_salary_ceb_percent');
      $data2['ceb_amount'] = $this->security->xss_clean($this->input->post('ceb_amount'));
      $data2['el_percent'] = $this->config->item('HR_salary_el_percent');
      $data2['el_amount'] = $this->security->xss_clean($this->input->post('el_amount'));
      $data2['total_salary_amount'] = $this->security->xss_clean($this->input->post('total_salary'));
      $data2['pf_percent'] = $this->config->item('HR_salary_pf_percent');
      $data2['pf_amount'] = $this->security->xss_clean($this->input->post('pf_amount'));
      $data2['esi_percent'] = $this->config->item('HR_salary_esi_percent');
      $data2['esi_amount'] = $this->security->xss_clean($this->input->post('esi_amount'));
    }elseif($this->config->item('HR_salary_slip_template')==4){
      $data2['max_payable_days'] = $this->security->xss_clean($this->input->post('max_payable_days'));
      $data2['net_paid_days'] = $this->security->xss_clean($this->input->post('net_paid_days'));
      $data2['paid_leaves'] = $this->security->xss_clean($this->input->post('paid_leaves'));
      $data2['weekly_off_days'] = $this->security->xss_clean($this->input->post('weekly_off_days'));
      $data2['working_days'] = $this->security->xss_clean($this->input->post('working_days'));
      $data2['lwp_days'] = $this->security->xss_clean($this->input->post('lwp_days'));

      $data2['total_basic_salary_percent'] = $this->config->item('HR_salary_basic_salary_percent');
      $data2['total_basic_salary_amt'] = $this->security->xss_clean($this->input->post('total_basic_wage'));
      $data2['hra_percent'] = $this->config->item('HR_salary_hra_percent');
      $data2['hra_amount'] = $this->security->xss_clean($this->input->post('hra_amount'));
      $data2['conveyance_alwnc_percent'] = $this->config->item('HR_salary_conveyance_allowance_percent');
      $data2['conveyance_alwnc_amt'] = $this->security->xss_clean($this->input->post('conv_allowance_amt'));
      $data2['special_alwnc_percent'] = $this->config->item('HR_salary_special_allowance_percent');
      $data2['special_alwnc_amt'] = $this->security->xss_clean($this->input->post('special_allowance_amount'));
      $data2['city_compens_alwnc_percent'] = $this->config->item('HR_salary_city_compensatory_allowance_percent');
      $data2['city_compens_alwnc_amt'] = $this->security->xss_clean($this->input->post('city_compens_amount'));
      $data2['total_salary_amount'] = $this->security->xss_clean($this->input->post('total_salary'));
      $data2['pf_percent'] = $this->config->item('HR_salary_pf_percent');
      $data2['pf_amount'] = $this->security->xss_clean($this->input->post('pf_amount'));
      $data2['esi_percent'] = $this->config->item('HR_salary_esi_percent');
      $data2['esi_amount'] = $this->security->xss_clean($this->input->post('esi_amount'));
      $data2['lwp_amount'] = $this->security->xss_clean($this->input->post('lwp_amount'));
    }else{
      $data2['total_salary_amount'] = $this->security->xss_clean($this->input->post('total_wage'));
    }
    $data2['allowance'] = $this->security->xss_clean($this->input->post('allowance'));
    if($this->input->post('incentive')){
      $data2['incentive'] = $this->security->xss_clean($this->input->post('incentive'));
    }
    if($this->input->post('bonus')){
      $data2['bonus_amount'] = $this->security->xss_clean($this->input->post('bonus'));
    }
    $data2['other_deductions'] = $this->security->xss_clean($this->input->post('deductions'));
    $data2['net_salary_amount'] = $this->security->xss_clean($this->input->post('total_wage'));
    $data2['total_paid_amount'] = $this->security->xss_clean($this->input->post('paid_amount'));
    $data2['total_balance_amount'] = $this->security->xss_clean($this->input->post('balance_amount'));
    $data2['advance_paid_amount'] = $this->security->xss_clean($this->input->post('advance_paid'));
    $data2['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data2['created_date'] = date('Y-m-d H:i:s');
    $data2['created_by'] = $this->session->userdata('user_id');
    if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
      $data2['entry_approval_status'] = 0;
    }
    if($count==0) {
      $result2 = $this->Salary_slips->create_salary_slip($data2);
      $flash_data['status'] = $result2['status'];
      if ($result2['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Salary Slip Added Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';

        // Insert IF Payment Exist
        if($this->security->xss_clean($this->input->post('paid_amount'))>0){
          $transaction_data['reference_id'] = $result2['insert_id'];
          $transaction_data['reference_type'] = "salary_slip";
          $transaction_data['tr_type'] = "salary_slip_transaction";
          $transaction_data['tr_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('paid_date'))));
          $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
          $transaction_data['tr_credit_acc'] = 10;//Salary Slip payments
          $transaction_data['tr_description'] = "Salary Slip Transaction";
          $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('paid_amount'));
          $transaction_data['tr_mode'] = $this->security->xss_clean($this->input->post('payment_mode'));
          $transaction_data['tr_reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
          if($this->input->post('reference_date')!=''){
            $transaction_data['tr_reference_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('reference_date'))));
          }
          $transaction_data['tr_remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
          $transaction_data['created_date'] = date('Y-m-d H:i:s');
          $transaction_data['created_by'] = $this->session->userdata('user_id');
          if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
            $transaction_data['tr_entry_approval_status'] = 0;
          }
          $transaction_result =  $this->Account->create_account_transaction($transaction_data);
          $flash_data['flashdata_msg'] = 'Salary Slip & Transaction Added Successfully!.';
        }
        $this->bills_management->calculate_salary_slip_total($result2['insert_id']);
      } else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else{
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. Salary Slip on Same Month for this Employee is Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function update()
  {
    $data2['salary_id'] = $data3['ss.salary_id !='] = $this->security->xss_clean($this->input->post('salary_id'));
    $data2['employee_id'] = $data3['ss.employee_id'] = $this->security->xss_clean($this->input->post('employee'));
    $data2['month'] = $data3['ss.month'] = date('Y-m-t',strtotime("01 ".$this->security->xss_clean($this->input->post('month'))));
    if($this->config->item('HR_salary_slip_allow_multiple_in_a_month')==0){
      $count = $this->Salary_slips->select_salary_slips("",$data3)->num_rows();
    }else{
      $count = 0;
    }
    $data2['slip_type'] = $this->security->xss_clean($this->input->post('salary_slip_type_edit'));
    if($data2['slip_type']=='Project'){
      $data2['work_id'] = $this->security->xss_clean($this->input->post('work_id'));
    }else{
      $data2['work_id'] = 0;
    }
    $data2['basic_wage'] = $this->security->xss_clean($this->input->post('basic_wage'));
    $data2['basic_wage_type'] = $this->security->xss_clean($this->input->post('basic_wage_type'));
    $data2['basic_wage_fixed'] = $this->security->xss_clean($this->input->post('basic_wage_fixed'));
    $data2['month_days'] = $this->security->xss_clean($this->input->post('month_days'));
    $data2['hourly_rate'] = $this->security->xss_clean($this->input->post('hourly_rate_2'));
    $data2['daily_work_hour'] = $this->security->xss_clean($this->input->post('daily_work_hour'));
    $data2['holidays'] = $this->security->xss_clean($this->input->post('holidays'));
    $data2['medical_leave'] = $this->security->xss_clean($this->input->post('medical_leave'));
    $data2['absent'] = $this->security->xss_clean($this->input->post('absent'));
    $data2['worked_nos'] = $this->security->xss_clean($this->input->post('worked_nos'));
    $data2['regular_hours'] = $this->security->xss_clean($this->input->post('regular_hours'));
    $data2['overtime'] = $this->security->xss_clean($this->input->post('overtime'));
    $data2['overtime_period'] = $this->security->xss_clean($this->input->post('overtime_type'));
    $data2['overtime_rate'] = $this->security->xss_clean($this->input->post('overtime_rate'));
    $data2['overtime_amount'] = $this->security->xss_clean($this->input->post('overtime_amount'));
    $data2['allowance'] = $this->security->xss_clean($this->input->post('allowance'));
    if($this->input->post('incentive')){
      $data2['incentive'] = $this->security->xss_clean($this->input->post('incentive'));
    }
    if($this->input->post('bonus')){
      $data2['bonus_amount'] = $this->security->xss_clean($this->input->post('bonus'));
    }
    $data2['other_deductions'] = $this->security->xss_clean($this->input->post('deductions'));
    $data2['net_salary_amount'] = $data2['total_salary_amount'] = $this->security->xss_clean($this->input->post('total_wage'));
    $data2['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data2['updated_date'] = date('Y-m-d H:i:s');
    $data2['updated_by'] = $this->session->userdata('user_id');
    if($count==0) {
      $result2 = $this->Salary_slips->update_salary_slip($data2);
      $flash_data['status'] = $result2;
      if ($result2 == 1) {
        $flash_data['flashdata_msg'] = 'Salary Slip Details Updated Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';

        $this->bills_management->calculate_salary_slip_total($data2['salary_id']);
      } else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else{
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. Salary Slip on Same Month for this Employee is Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function delete()
  {
    $data2['salary_id'] = $this->security->xss_clean($this->input->post('salary_id'));
    $data2['delete_status'] = 1;
    $result2 = $this->Salary_slips->update_salary_slip($data2);
    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['flashdata_msg'] = 'Salary Slip Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function select_salary_slips($page_data_type='',$list_type=''){
    $json_data=$array=$employee_payment_array=array();
    $j=$sl_no=0;
    $total_salary_amount=$total_paid_amount=$total_balance_amount=0;
    $data=array();
    if(isset($_POST['employee']) && $_POST['employee']!='' && $_POST['employee']!='all'){
      $data['ss.employee_id'] = $_POST['employee'];
    }
    if (isset($_POST['acc_head_id']) && $_POST['acc_head_id'] != '' && $_POST['acc_head_id'] != 'all') {
      $acc_head_id = $_POST['acc_head_id'];
      $account_heads_where['ah.acc_head_id'] = $_POST['acc_head_id'];
      $account_heads_data	= $this->Account->select_account_heads("acc_head_id",$account_heads_where)->row();
      if($account_heads_data->acc_employee_id!=0){
        $data['ss.employee_id'] = $account_heads_data->acc_employee_id;
      }
    }
    $btn_delete=$btn_edit=$btn_add_payment='';
    if(isset($_POST['start_month']) && $_POST['start_month']!=''){
      $start_date=date('Y-m', strtotime($_POST['start_month']));
      $data["ss.month >="]= $start_date."-01";
    }
    if(isset($_POST['end_month']) && $_POST['end_month']!=''){
      $end_date=date('Y-m', strtotime($_POST['end_month']));
      $data["ss.month <="]= $end_date."-".date('t',strtotime($_POST['end_month']));
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!=''){
      $start_date=date('Y-m', strtotime($_POST['start_date']));
      $data["ss.month >="]= $start_date."-01";
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!=''){
      $end_date=date('Y-m', strtotime($_POST['end_date']));
      $data["ss.month <="]= $end_date."-".date('t',strtotime($_POST['end_date']));
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['ss.work_id'] = $_POST['work'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $this->db->where_in('ss.work_id',explode(',',$_POST['work_ids']));
    }
    if(isset($_POST['stage_id']) && $_POST['stage_id']!='' && $_POST['stage_id']!='all'){
      $data['ss.project_stage_id'] = $_POST['stage_id'];
    }
    if($this->config->item('user_data_access_view_all')!=1){
      $data['ss.created_by'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['ss.created_by'] = $_POST['user_id'];
    }
    if($this->session->userdata('user_role')=='general_manager' && $this->config->item('User_general_manager_client_payment_view_all')==0){
      $data['ss.created_by'] = $this->session->userdata('user_id');
    }
    $entry_approval = 1;
    if($this->config->item('User_enable_data_entry_approval')==1){//webapp users approval
      $entry_approval = 'all';
    }
    if($page_data_type=='approval_entries'){
      $entry_approval = 'all';
      $data['u.user_role >'] =2;
      if(isset($_POST['approval_status']) && $_POST['approval_status']!='' && $_POST['approval_status']!='all'){
        $entry_approval = $_POST['approval_status'];
      }
    }

    $result	= $this->Salary_slips->select_salary_slips("ss.*,e.employee_name,e.user_designation,u.user_alias,wc.work_name,u.user_role as created_user_role_id",$data,'','','','','',$entry_approval);
    if($result->num_rows()>0){
      foreach($result->result() as $row):
        $sl_no++;
        if($this->config->item('HR_salary_slip_template')!=3){
          $bill_id_column = 25;
        }else{
          $bill_id_column = 33;
        }
        if($this->session->userdata('user_role')!='auditor' && ( $this->session->userdata('user_role')=='admin' || $this->session->userdata('user_id')==$row->created_by)) {
          $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="salary_slip_delete_btn" href="#salary_slip_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-trash"></i>
          </a>';
          $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="salary_slip_edit_btn" href="#salary_slip_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-edit"></i>
          </a>';
        }
        $btn_add_payment = '';
        if($row->total_balance_amount<=0){
          $payment_status="<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Paid</span>";
        }else{
          if($row->total_balance_amount==$row->net_salary_amount){
            $payment_status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Not Paid</span>";
          }else{
            $payment_status="<span class='m-badge m-badge--info m-badge--wide'><i class='fa fa-times-circle'></i> Partially Paid</span>";
          }
          // if($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')=='supervisor' && $this->session->userdata('user_id')==$row->created_by)) {

          if($this->session->userdata('user_role')!='auditor' || $this->session->userdata('user_data_permission')['adding']==1) {
            $btn_add_payment = '<a style="margin-left: 5px;margin-right: 5px" data-bill-type="salary_slip" data-bill-id-column="'.$bill_id_column.'" id="btn_add_bill_payment" data-toggle="modal"  href="#bill_payment_add_modal" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
            <i class="la la-plus-circle"></i>
            </a>';
          }

          // }
        }

        if($row->basic_wage_type=='Hourly'){
          $basic_wage_type = '/Hour';
          $worked_nos_type = ' Hours';
        }elseif($row->basic_wage_type=='Daily'){
          $basic_wage_type = '/Day';
          $worked_nos_type = ' Days';
        }else{
          $basic_wage_type = '/Month';
          $worked_nos_type = ' Days';
        }
        if($row->overtime_period=='Hours'){
          $overtime_period = ' Hours';
          $overtime_rate_period = '/Hour';
        }else{
          $overtime_period = ' Days';
          $overtime_rate_period = '/Day';
        }

        $btn_approve = $entry_approval_status = '';
        if(($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')=='accounts_manager' && $row->created_user_role_id>2 && (($this->config->item('User_enable_data_entry_approval_2_level')==0 && $row->created_user_role_id != 16) || $this->config->item('User_enable_data_entry_approval_2_level')==1))) && $page_data_type=='approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval')==1){
          $btn_approve = '<a style="margin-left: 5px;margin-right: 5px" data-type="salary_slip" data-approval-status="'.$row->entry_approval_status.'" data-id="'.$row->salary_id.'" id="btn_data_entry_approval" href="#data_entry_approve_modal" data-toggle="modal" class="btn btn-sm btn-warning m-btn m-btn--icon  m-btn--pill m-btn--air">
          <i class="la la-check-circle"></i> / <i class="la la-times-circle"></i>
          </a>';
        }
        if(($page_data_type=='approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval')==1) || $this->config->item('User_enable_data_entry_approval')==1){
          if($row->entry_approval_status==1){
            $entry_approval_status="<br/><span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Approved</span>";
          }elseif($row->entry_approval_status==2){
            $entry_approval_status="<br/><span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> Rejected</span>";
          }else{
            $entry_approval_status="<br/><span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> Pending</span>";
          }
        }

        $array[$j][]=$sl_no;
        $array[$j][]='<a href="'.base_url().'salary_slips/profile/'.$row->salary_id.'">'."#".$row->salary_id.'</a>';
        // $array[$j][]='<a href="' . base_url() . 'employees/profile/' . $row->employee_id . '">' . $row->employee_name . '</a>';
        $array[$j][]=$row->employee_name;
        $array[$j][]=$row->user_designation;
        $employee_payment_array[$j][] = $array[$j][]=date('M Y',strtotime($row->month));
        $array[$j][]=$row->slip_type." Expense";
        if($row->work_id!='' && $row->work_id!=0){
          $array[$j][]='<a href="'.base_url().'work/profile/'.$row->work_id.'">'.$row->work_name.'</a>';
        }else{
          $array[$j][]='';
        }
        $array[$j][]=$row->worked_nos.$worked_nos_type;
        $array[$j][]=number_format($row->basic_wage,$this->config->item('Currency_amount_decimals_2'),'.','').$basic_wage_type;
        if($this->config->item('HR_salary_slip_template')!=3){
          $array[$j][]=$row->overtime.$overtime_period;
          $array[$j][]=number_format($row->overtime_rate,$this->config->item('Currency_amount_decimals_2'),'.','').$overtime_rate_period;
          $array[$j][]=number_format($row->overtime_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        }else{
          if($row->basic_wage_type=='Monthly'){
            $array[$j][]=number_format($row->basic_wage,2);
          }else{
            $array[$j][]=number_format($row->worked_nos*$row->basic_wage,2);
          }
          $array[$j][]=number_format($row->bonus_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
          $array[$j][]=number_format($row->tiffin_allowance_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
          $array[$j][]=$row->overtime.$overtime_period;
          $array[$j][]=number_format($row->overtime_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
          $array[$j][]=number_format($row->hra_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
          $array[$j][]=number_format($row->ceb_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
          $array[$j][]=number_format($row->el_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
          $array[$j][]=number_format($row->total_salary_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
          $array[$j][]=number_format($row->pf_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
          $array[$j][]=number_format($row->esi_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        }
        $array[$j][]=number_format($row->allowance,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=number_format($row->incentive,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=number_format($row->bonus_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=number_format($row->other_deductions,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=number_format($row->net_salary_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=number_format($row->advance_paid_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=number_format($row->total_paid_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=number_format($row->total_paid_amount+$row->advance_paid_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $employee_payment_array[$j][]=$array[$j][]=number_format($row->total_balance_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=$payment_status;
        $array[$j][]=$row->remarks;
        if ($this->config->item('UI_hide_created_date_field')==0){
          $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : '.date('d-m-Y',strtotime($row->created_date))."</li><li>Created By : ".$row->user_alias."</li>".$entry_approval_status;
        }else{
          $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>'.$entry_approval_status;
        }
        $array[$j][]=$btn_add_payment.$btn_edit.$btn_delete.$btn_approve;
        $employee_payment_array[$j][]=$array[$j][]=$row->salary_id;
        $employee_payment_array[$j][]=$array[$j][]=$row->employee_id;
        $array[$j][]=$row->work_id;
        $array[$j][]=date('m-Y',strtotime($row->month));
        $array[$j][]=$row->slip_type;
        $array[$j][]=number_format($row->basic_wage,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=$row->basic_wage_type;
        $array[$j][]=$row->overtime;
        $array[$j][]=$row->overtime_period;
        $array[$j][]=number_format($row->overtime_rate,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=$row->worked_nos;
        $array[$j][]=$row->basic_wage_fixed;
        $array[$j][]=$row->holidays;
        $array[$j][]=$row->medical_leave;
        $array[$j][]=$row->absent;
        $array[$j][]=$row->month_days;
        $array[$j][]=$row->hourly_rate;
        $array[$j][]=$row->regular_hours;
        $array[$j][]=$row->daily_work_hour;
        $array[$j][]=$row->entry_approval_status;

        $total_salary_amount+=$row->net_salary_amount;
        $total_paid_amount+=$row->total_paid_amount+$row->advance_paid_amount;
        $total_balance_amount+=$row->total_balance_amount;

        $j++;
      endforeach;


      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][] = '';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      if($this->config->item('HR_salary_slip_template')!=3){
        $array[$j][]='';
        $array[$j][]='';
        $array[$j][]='';
      }else{
        $array[$j][]='';
        $array[$j][]='';
        $array[$j][]='';
        $array[$j][]='';
        $array[$j][]='';
        $array[$j][]='';
        $array[$j][]='';
        $array[$j][]='';
        $array[$j][]='';
        $array[$j][]='';
        $array[$j][]='';
      }
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_salary_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_paid_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_balance_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';

    }


    $json_data['data']=$array;
    $json_data['draw']=5;
    $json_data['recordsTotal']=sizeof($array);
    $json_data['recordsFiltered']=sizeof($array);
    if($list_type=='employee_payment'){
      $json_data = $employee_payment_array;
    }
    echo json_encode($json_data);  // send data as json format
  }


  public function get_advance_salary()
  {
    $json_data=$employee_payment_array=array();
    $j=$sl_no=0;
    $month_days = $holidays = $sundays = $total_paid_leaves = $total_unpaid_leaves = 0;
    $data=array();
    $total_advance_paid = $advance_amount = $current_advance = 0 ;
    if(isset($_POST['employee_id']) && $_POST['employee_id']!='' && $_POST['employee_id']!='all' && isset($_POST['month']) && $_POST['month']!='' && $_POST['month']!='all'){
      // Get Advance Data
      $data['ats.reference_id'] = $_POST['employee_id'];
      $data['ats.reference_type'] = 'employee';
      $data['ats.tr_type'] = 'salary_advance_transaction';
      $data['ats.tr_other_data'] = date('Y-m',strtotime($_POST['month']));
      $data2['ss.month'] = date('Y-m-t',strtotime($_POST['month']));
      $data2['ss.employee_id'] = $_POST['employee_id'];
      $advance_result = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$data,'employee');
      $total_advance_paid = $advance_result->result()[0]->total_amount;
      $current_advance_result = $this->Salary_slips->select_salary_slips("ss.*",$data2);
      if($current_advance_result->num_rows() != 0){
        $current_advance = $current_advance_result->row()->advance_paid_amount;
      }

      // Get Leave Data & Month Data & Holidays
      $month_days = date('t',strtotime($_POST['month']));
      $year = date('Y',strtotime($_POST['month']));
      $month = date('m',strtotime($_POST['month']));
      $daytime = strtotime(date($year."/".$month."/01 00:00:01"));
      $daysOfMonth = date("t", $daytime);

      for ($day=1;  $day <= $daysOfMonth; $day++) {
        $time = strtotime(date($year.'/'.$month.'/'.$day.' 00:00:01'));
        $dayStr = date('l', $time);
        if ($dayStr == 'Sunday') {
          $sundays++;
        }
      }
      $employee_data	= $this->Employee->select_employee("*",array("employee_id"=>$_POST['employee_id']));
      if($employee_data->num_rows()==1){
        $paid_leaves_where['lt.leave_paid'] = 1;
        $paid_leaves_where['uat.attendance_status'] = 2;
        $paid_leaves_where['uat.user_id'] = $employee_data->row()->user_id;
        $paid_leaves_where['uat.attendance_date >='] = date('Y-m-01',strtotime($_POST['month']));
        $paid_leaves_where['uat.attendance_date <='] = date('Y-m-t',strtotime($_POST['month']));
        $total_paid_leaves = $this->Attendance->select_attendance('uat.*',$paid_leaves_where)->num_rows();

        $unpaid_leaves_where = $paid_leaves_where;
        $unpaid_leaves_where['lt.leave_paid'] = 0;
        $total_unpaid_leaves = $this->Attendance->select_attendance('uat.*',$unpaid_leaves_where)->num_rows();
      }

      $holiday_where["holiday_date >="] = date('Y-m-01',strtotime($_POST['month']));
      $holiday_where["holiday_date <="] = date('Y-m-t',strtotime($_POST['month']));
      $holidays = $this->Settings->select_holidays("",$holiday_where)->num_rows();
    }
    $json_data['advance'] = $total_advance_paid - $current_advance;
    $json_data['month_days'] = $month_days;
    $json_data['sundays'] = $sundays;
    $json_data['holidays'] = $holidays;
    $json_data['total_paid_leaves'] = $total_paid_leaves;
    $json_data['total_unpaid_leaves'] = $total_unpaid_leaves;

    echo json_encode($json_data);
  }

}
?>
