<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Employees 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('Work_model', 'Work');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Employees_model', 'Employee');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Salary_slips_model', 'Salary_slips');
    $this->load->library('Bills_management','bills_management');
    $this->load->library('Accounts_management','accounts_management');
    $this->load->model('Labour_model', 'Labour');
    $this->load->model('Vehicle_model', 'Vehicle');
    $this->load->model('Attendance_model', 'Attendance');

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

    $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('Labour_group_member_payment')==0){
      $this->db->where('(l.labour_type=0 or (l.labour_type=1 and group_position=1))');
    }
    $this->page_data['labours_2'] = $this->Labour->select_labours()->result();
  }

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

  public function view()
  {
    $this->page_data['owned_vehicles'] = $this->Vehicle->select_vehicle('v.*',array('v.vehicle_type'=>'own'))->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'] = 'employees_view';
      $this->load->view('Index', $this->page_data);
    }else{
      redirect(base_url(), 'refresh');
    }
  }
  public function attendance($page='view')
  {
    $this->page_data['employees'] = $this->Employee->select_employee("e.*,ed.department_name")->result();
    if($this->config->item('HR_punching_machine_attendance')==1) {
      if($page=='add'){
        $this->page_data['page_name'] = 'employee_attendance_import';
      }else{
        $this->page_data['page_name'] = 'employee_attendance_view';
      }
      $this->load->view('Index', $this->page_data);
    }else{
      redirect(base_url(), 'refresh');
    }
  }
  public function site_visit_log($page='view')
  {
    $this->page_data['employees'] = $this->Employee->select_employee("e.*,ed.department_name")->result();
    if($this->config->item('HR_employee_site_visit')==1) {
      $this->page_data['page_name'] = 'employee_site_visit_log';
      $this->load->view('Index', $this->page_data);
    }else{
      redirect(base_url(), 'refresh');
    }
  }
  public function leave_applications($page='view')
  {
    $this->page_data['leave_types'] = $this->Employee->select_leave_types("")->result();
    $this->page_data['employees'] = $this->Employee->select_employee("e.*,ed.department_name")->result();
    if($this->config->item('HR_leave_application')==1) {
      $this->page_data['page_name'] = 'employee_leave_applications';
      $this->load->view('Index', $this->page_data);
    }else{
      redirect(base_url(), 'refresh');
    }
  }
  public function payments()
  {
    $this->page_data['works'] = $this->Work->select_work("*")->result();
    $this->page_data['employees'] = $this->Employee->select_employee("e.*,u.user_alias")->result();
    $data['ss.total_balance_amount >'] = 0;

    $this->page_data['salary_slips'] = $this->Salary_slips->select_salary_slips("ss.*,e.employee_name,e.user_designation,u.user_alias,wc.work_name",$data)->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')=='hr_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'] = 'payments_view';
      $this->load->view('Index', $this->page_data);
    }else{
      redirect(base_url(), 'refresh');
    }
  }


  public function get_employee_opbalance()
  {
    if($this->input->post('employee_id')){
      $employee_id = $employee_data['employee_id'] = $this->security->xss_clean($this->input->post('employee_id'));
      $opbalance = $this->Employee->select_employee("e.*,u.user_alias",$employee_data)->row()->op_balance;

      $data['ats.tr_type'] = "employee_opbalance_transaction";
      $data['ats.reference_id'] = $employee_id ;
      $total_opbalance_returned = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_opbalance_returned",$data)->row()->total_opbalance_returned;

      $employee_opbalance = $opbalance - $total_opbalance_returned;
    }else{
      $employee_opbalance = 0;
    }
    $array = array('op_balance' => $employee_opbalance);
    echo json_encode($array);
  }
  public function create()
  {
    $data['employee_name'] = $this->security->xss_clean($this->input->post('name'));
    $data['user_designation'] = $this->security->xss_clean($this->input->post('designation'));
    $employee_where = "((e.employee_name='" . $data['employee_name'] . "' and e.user_designation='" . $data['user_designation'] . "')";
    if ($this->input->post('employee_code') != '') {
      $data['employee_code'] = $this->security->xss_clean($this->input->post('employee_code'));
      $employee_where .= " or e.employee_code='" . $data['employee_code'] . "'";
    }
    $employee_where .= ")";
    $employee_count = $this->Employee->select_employee("e.employee_code",$employee_where)->num_rows();
    $data['address'] = $this->security->xss_clean($this->input->post('address'));
    $data['phone_no'] = $this->security->xss_clean($this->input->post('contact_no'));
    $data['gender'] = $this->security->xss_clean($this->input->post('gender'));
    if ($this->input->post('dob') != '') {
      $data['dob'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('dob'))));
    }
    $data['nationality'] = $this->security->xss_clean($this->input->post('nationality'));
    $data['sponsor'] = $this->security->xss_clean($this->input->post('sponsor'));
    $data['work_location'] = $this->security->xss_clean($this->input->post('work_location'));
    $data['civil_id'] = $this->security->xss_clean($this->input->post('civil_id'));
    if ($this->input->post('civil_id_expiry_date') != '') {
      $data['civil_id_expiry_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('civil_id_expiry_date'))));
    }
    $data['passport_no'] = $this->security->xss_clean($this->input->post('passport_no'));
    if ($this->input->post('passport_expiry_date') != '') {
      $data['passport_expiry_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('passport_expiry_date'))));
    }
    $data['health_card_no'] = $this->security->xss_clean($this->input->post('health_card_no'));
    if ($this->input->post('health_card_expiry_date') != '') {
      $data['health_card_expiry_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('health_card_expiry_date'))));
    }
    if ($this->input->post('joined_date') != '') {
      $data['joined_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('joined_date'))));
    }
    if ($this->input->post('arrived_date') != '') {
      $data['date_of_arrival'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('arrived_date'))));
    }
    $data['bank_name'] = $this->security->xss_clean($this->input->post('bank_name'));
    $data['bank_account_no'] = $this->security->xss_clean($this->input->post('bank_account_no'));
    if ($this->input->post('bank_card_expiry_date') != '') {
      $data['bank_card_expiry_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('bank_card_expiry_date'))));
    }
    $data['basic_wage'] = $this->security->xss_clean($this->input->post('basic_wage'));
    $data['basic_wage_type'] = $this->security->xss_clean($this->input->post('basic_wage_type'));
    $data['basic_wage_fixed'] = $this->security->xss_clean($this->input->post('fixed_basic_wage'));
    $data['op_balance'] = $this->security->xss_clean($this->input->post('opening_balance'));
    $data['food_allowance'] = $this->security->xss_clean($this->input->post('food_allowance'));
    $data['salary_incentive'] = $this->security->xss_clean($this->input->post('incentive'));
    $data['department'] = $this->security->xss_clean($this->input->post('department'));
    if($data['department']==1 && $this->input->post('assigned_vehicles') && !empty($this->input->post('assigned_vehicles'))){
      $data['assigned_vehicles'] = implode(',',$this->input->post('assigned_vehicles'));
    }
    $data['t_shirt_size'] = $this->security->xss_clean($this->input->post('t_shirt_size'));
    $data['shoes_size'] = $this->security->xss_clean($this->input->post('shoes_size'));
    $data['pant_size'] = $this->security->xss_clean($this->input->post('pant_size'));
    $data['biometric_id'] = $this->security->xss_clean($this->input->post('biometric_id'));
    $data['created_by'] = $this->session->userdata('user_id');
    $data['created_date'] = date('Y-m-d H:i:s');

    if($employee_count==0) {
      $result2 = $this->Employee->create_employee($data);
      $flash_data['status'] = $result2['status'];
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Employee Added Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';

        // CReate Account Head
        $account_data['acc_head_name'] = $data['employee_name']."'s Account";
        $account_data['account_type'] = 32; //Cash Account
        $account_data['acc_employee_id'] = $result2['insert_id'];
        $account_data['head_editable'] = 0;
        $account_data['op_balance'] = 0;
        $account_data['created_date'] = date('Y-m-d H:i:s');
        $account_data['created_by'] = $this->session->userdata('user_id');
        $account_result = $this->Account->create_account_head($account_data);

      } 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'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. Employee with Same Name / Employee Code 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()
  {
    $data['employee_id'] = $this->security->xss_clean($this->input->post('employee_id'));
    $data['employee_name'] = $user_update['user_alias'] = $this->security->xss_clean($this->input->post('name'));
    $data['user_designation'] = $user_update['user_designation'] = $this->security->xss_clean($this->input->post('designation'));
    $employee_where = "((e.employee_name='" . $data['employee_name'] . "' and e.user_designation='" . $data['user_designation'] . "')";
    if ($this->input->post('employee_code') != '') {
      $data['employee_code'] = $user_update['employee_code'] = $this->security->xss_clean($this->input->post('employee_code'));
      $employee_where .= " or e.employee_code='" . $data['employee_code'] . "'";
    }
    $data['employee_id'] = $this->security->xss_clean($this->input->post('employee_id'));
    $employee_where .= ") and e.employee_id!=" . $data['employee_id'];
    $employee_count = $this->Employee->select_employee("e.employee_code",$employee_where)->num_rows();

    $data['address'] = $user_update['address'] = $this->security->xss_clean($this->input->post('address'));
    $data['phone_no'] = $user_update['phone_no'] = $this->security->xss_clean($this->input->post('contact_no'));
    $data['gender'] = $this->security->xss_clean($this->input->post('gender_edit'));
    if ($this->input->post('dob') != '') {
      $data['dob'] = $user_update['dob'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('dob'))));
    }else{
      $data['dob'] = $user_update['dob'] = '';
    }
    $data['nationality'] = $this->security->xss_clean($this->input->post('nationality'));
    $data['sponsor'] = $this->security->xss_clean($this->input->post('sponsor'));
    $data['work_location'] = $this->security->xss_clean($this->input->post('work_location'));
    $data['civil_id'] = $this->security->xss_clean($this->input->post('civil_id'));
    if ($this->input->post('civil_id_expiry_date') != '') {
      $data['civil_id_expiry_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('civil_id_expiry_date'))));
    }else{
      $data['civil_id_expiry_date'] = '';
    }
    $data['passport_no'] = $this->security->xss_clean($this->input->post('passport_no'));
    if ($this->input->post('passport_expiry_date') != '') {
      $data['passport_expiry_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('passport_expiry_date'))));
    }else{
      $data['passport_expiry_date'] = '';
    }
    $data['health_card_no'] = $this->security->xss_clean($this->input->post('health_card_no'));
    if ($this->input->post('health_card_expiry_date') != '') {
      $data['health_card_expiry_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('health_card_expiry_date'))));
    }else{
      $data['health_card_expiry_date'] = '';
    }
    if ($this->input->post('joined_date') != '') {
      $data['joined_date'] = $user_update['joined_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('joined_date'))));
    }else{
      $data['joined_date'] = $user_update['joined_date'] = '';
    }
    if ($this->input->post('arrived_date') != '') {
      $data['date_of_arrival'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('arrived_date'))));
    }else{
      $data['date_of_arrival'] = '';
    }
    $data['bank_name'] = $this->security->xss_clean($this->input->post('bank_name'));
    $data['bank_account_no'] = $this->security->xss_clean($this->input->post('bank_account_no'));
    if ($this->input->post('bank_card_expiry_date') != '') {
      $data['bank_card_expiry_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('bank_card_expiry_date'))));
    }else{
      $data['bank_card_expiry_date'] = '';
    }
    $data['basic_wage'] = $this->security->xss_clean($this->input->post('basic_wage'));
    $data['basic_wage_type'] = $this->security->xss_clean($this->input->post('basic_wage_type_edit'));
    $data['basic_wage_fixed'] = $this->security->xss_clean($this->input->post('fixed_basic_wage_edit'));
    $data['op_balance'] = $this->security->xss_clean($this->input->post('opening_balance'));
    $data['food_allowance'] = $this->security->xss_clean($this->input->post('food_allowance'));
    $data['salary_incentive'] = $this->security->xss_clean($this->input->post('incentive'));
    $data['department'] = $this->security->xss_clean($this->input->post('department'));
    if($data['department']==1 && $this->input->post('assigned_vehicles') && !empty($this->input->post('assigned_vehicles'))){
      $data['assigned_vehicles'] = implode(',',$this->input->post('assigned_vehicles'));
    }else{
      $data['assigned_vehicles'] = '';
    }
    $data['t_shirt_size'] = $this->security->xss_clean($this->input->post('t_shirt_size'));
    $data['shoes_size'] = $this->security->xss_clean($this->input->post('shoes_size'));
    $data['pant_size'] = $this->security->xss_clean($this->input->post('pant_size'));
    $data['biometric_id'] = $this->security->xss_clean($this->input->post('biometric_id'));
    $data['updated_by'] = $this->session->userdata('user_id');
    $data['updated_date'] = date('Y-m-d H:i:s');

    if($employee_count==0) {
      $employee_data = $this->Employee->select_employee("e.*",array("e.employee_id"=>$data['employee_id']));
      if($employee_data->num_rows()==1){
        $employee_data = $employee_data->row();
        if($employee_data->user_id!=0){
          //Update in users
          $user_update['user_id'] = $employee_data->user_id;
          $this->User->update_user($user_update);
        }
        $result2 = $this->Employee->update_employee($data);
        $flash_data['status'] = $result2;
        if($flash_data['status'] == 1){
          $flash_data['flashdata_msg'] = 'Employee Details Updated Successfully!.';
          $flash_data['flashdata_type'] = 'success';
          $flash_data['alert_type'] = 'success';
          $flash_data['flashdata_title'] = 'Success !';

          $account_head_data = $this->Account->select_account_heads("",array("acc_employee_id"=>$data['employee_id']));
          if($account_head_data->num_rows()==1){
            // Update Account Head
            $account_data['acc_head_name'] = $this->security->xss_clean($this->input->post('name'))."'s Account";
            $account_data['acc_head_id'] = $account_head_data->row()->acc_head_id;
            $account_data['updated_date'] = date('Y-m-d H:i:s');
            $account_data['updated_by'] = $this->session->userdata('user_id');
            $account_result = $this->Account->update_account_head($account_data);
          }
        }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'] = 2;
        $flash_data['flashdata_msg'] = 'Sorry.. Employee with Same Name & Designation Already Exist!';
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Duplication !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. Employee with Same Name / Employee Code 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()
  {
    $data['employee_id'] =  $this->security->xss_clean($this->input->post('employee_id'));
    $data['delete_status'] = 1;

    $result2 = $this->Employee->update_employee($data);
    $flash_data['status'] = $result2;
    if($result2 == 1){
      $flash_data['flashdata_msg'] = 'Employee Profile Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';

      //  Delete Account Head
      $account_data['account_type'] = 32;
      $account_data['acc_employee_id'] = $data['employee_id'];
      $account_details = $this->Account->select_account_heads("*",$account_data);
      if($account_details->num_rows()==1){
        $account_data['acc_head_id'] = $account_details->row()->acc_head_id;
        $account_data['delete_status'] = 1;
        $this->Account->update_account_head($account_data);
      }
    }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_employee(){
    $json_data=array();
    $j=0;
    $data=array();
    if($this->session->userdata('user_role')!='admin'){
      // $data['e.created_by'] = $this->session->userdata('user_id');
    }
    $result	= $this->Employee->select_employee("e.*,u.user_alias,ed.department_name",$data);
    $result_array=$result->result();
    $array=array();
    $sl_no=0;
    foreach($result_array as $row):
      $sl_no++;

      $btn_edit = $btn_delete = '';
      if($this->session->userdata('user_role')!='auditor'){
        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="employee_edit_btn" href="#employee_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>';
      }
      if($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')!='admin' && $this->session->userdata('user_id')==$row->created_by)) {
        if($row->user_id==0){
          $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="employee_delete_btn" href="#employee_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>';
        }
      }

      $assigned_vehicle_names = '';
      if($this->config->item('app_module_vehicle_management')==1 && $row->department==1){
        $assigned_vehicles = explode(',',$row->assigned_vehicle_names);
        foreach ($assigned_vehicles as $key => $value) {
          if($value!=''){
            $value = explode(';',$value);
            $assigned_vehicle_names.='<a style="margin-top:5px" href="'.base_url().'vehicles/profile/'.$value[2].'" class="btn btn-outline-primary m-btn btn-sm m-btn--custom m-btn--outline-2x" >'.$value[0].' ['.$value[1].']</a><br/>';
          }
        }
      }
      $civil_id_remaining_days = $civil_id_status = $passport_remaining_days = $passport_status = '';
      if($row->civil_id_expiry_date != '0000-00-00'){
        $now = time();
        $expiry_date = strtotime($row->civil_id_expiry_date);
        $remain_days = $expiry_date - $now;
        $civil_id_remaining_days = round($remain_days / (60 * 60 * 24));
        if($civil_id_remaining_days>30){
          $civil_id_status = "<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Valid</span>";
        }elseif($civil_id_remaining_days<30 && $civil_id_remaining_days>0){
          $civil_id_status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Expire Soon</span>";
        }else{
          $civil_id_status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Expired</span>";
        }
      }
      if($row->passport_expiry_date != '0000-00-00'){
        $now = time();
        $expiry_date = strtotime($row->passport_expiry_date);
        $remain_days = $expiry_date - $now;
        $passport_remaining_days = round($remain_days / (60 * 60 * 24));
        if($passport_remaining_days>30){
          $passport_status = "<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Valid</span>";
        }elseif($passport_remaining_days<30 && $passport_remaining_days>0){
          $passport_status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Expire Soon</span>";
        }else{
          $passport_status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Expired</span>";
        }
      }

      $array[$j][]=$sl_no;
      $array[$j][]=$row->employee_id;
      // $array[$j][]='<a href="'.base_url().'employees/profile/'.$row->employee_id.'" >'.$row->employee_name.'</a>';
      $array[$j][]=$row->employee_name;
      $array[$j][]=$row->employee_code;
      $array[$j][]=$row->department_name;
      $array[$j][]=$row->user_designation;
      $array[$j][]=$row->phone_no;
      $array[$j][]=$row->address;
      $array[$j][]=$row->gender;
      $array[$j][] = ($row->dob != '0000-00-00')?date('d-m-Y', strtotime($row->dob)):"";
      $array[$j][]=$row->nationality;
      $array[$j][]=$row->sponsor;
      $array[$j][]=$row->work_location;
      $array[$j][] = ($row->date_of_arrival != '0000-00-00')?date('d-m-Y', strtotime($row->date_of_arrival)):"";
      $array[$j][] = ($row->joined_date != '0000-00-00')?date('d-m-Y', strtotime($row->joined_date)):"";
      $array[$j][]=number_format($row->basic_wage,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$row->basic_wage_type;
      $array[$j][]=($row->basic_wage_fixed==1)?"Yes":"No";
      $array[$j][]=$row->op_balance;
      $array[$j][]=$row->food_allowance;
      $array[$j][]=$row->salary_incentive;
      $array[$j][]=$row->civil_id;
      $array[$j][] = ($row->civil_id_expiry_date != '0000-00-00')?date('d-m-Y', strtotime($row->civil_id_expiry_date)):"";
      $array[$j][] = $civil_id_remaining_days;
      $array[$j][] = $civil_id_status;
      $array[$j][]=$row->passport_no;
      $array[$j][] = ($row->passport_expiry_date != '0000-00-00')?date('d-m-Y', strtotime($row->passport_expiry_date)):"";
      $array[$j][] = $passport_remaining_days;
      $array[$j][] = $passport_status;
      $array[$j][]=$row->health_card_no;
      $array[$j][] = ($row->health_card_expiry_date != '0000-00-00')?date('d-m-Y', strtotime($row->health_card_expiry_date)):"";
      $array[$j][]=$row->bank_name;
      $array[$j][]=$row->bank_account_no;
      $array[$j][] = ($row->bank_card_expiry_date != '0000-00-00')?date('d-m-Y', strtotime($row->bank_card_expiry_date)):"";
      $array[$j][]=$row->t_shirt_size;
      $array[$j][]=$row->shoes_size;
      $array[$j][]=$row->pant_size;
      $array[$j][]=$row->biometric_id;
      $array[$j][]=$assigned_vehicle_names;
      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>";
      }else{
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>';
      }
      $array[$j][]=$btn_edit.$btn_delete;
      $array[$j][]=$row->basic_wage_fixed;
      $array[$j][]=$row->user_id;
      $array[$j][]=$row->department;
      $array[$j][]=$row->assigned_vehicles;

      $j++;
    endforeach;

    $json_data['data']=$array;
    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    echo json_encode($json_data);  // send data as json format
  }
  public function select(){
    $data['delete_status'] = 0;
    if(isset($_POST['id']) && $_POST['id']!=""){
      $data['employee_id'] = $_POST['id'];
    }
    $result	= $this->Employee->select_employee("*",$data);
    if($result->num_rows()>0) {
      foreach ($result->result() as $row):
        $id[] = $row->employee_id;
        $name[] = $row->employee_name;
        $location[]  = $row->address;
      endforeach;
      echo json_encode(array("count" => $result->num_rows(),"id" => $id,"name" => $name,"location" => $location));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }
  public function select_details(){
    $data=array();
    if(isset($_POST['employee_id']) && $_POST['employee_id']!=""){
      $data['employee_id'] = $_POST['employee_id'];
    }
    $result	= $this->Employee->select_employee("*",$data);
    if($result->num_rows()==1) {
      $row = $result->row();

      $json_data['count'] = $result->num_rows();
      $json_data['id'] = $row->employee_id;
      $json_data['name'] = $row->employee_name;
      $json_data['civil_id'] = $row->civil_id;
      $json_data['phone'] = $row->phone_no;
      $json_data['designation'] = $row->user_designation;
      $json_data['department_name'] = $row->department_name;
      $json_data['basic_wage'] = $row->basic_wage;
      $json_data['basic_wage_type'] = $row->basic_wage_type;
      $json_data['basic_wage_fixed'] = $row->basic_wage_fixed;
      $json_data['current_balance']  = 0;
      $json_data['op_balance'] = $row->op_balance;
      // Get Last Leave Details
      $last_leave_data = array();
      $last_leaves = $this->Employee->select_employee_leave_applications("la.*,lt.leave_type_name,lt.leave_paid,u.user_alias,e.civil_id,e.employee_name,ed.department_name,e.phone_no,e.user_designation",array("la.employee_id"=>$row->employee_id),'',array("application_id","desc"),2)->result();
      foreach ($last_leaves as $key => $value) {
        $last_leave_data[$key]['leave_date_from'] = date('d-m-Y',strtotime($value->leave_date_from));
        $last_leave_data[$key]['leave_date_to'] = date('d-m-Y',strtotime($value->leave_date_to));
        $last_leave_data[$key]['leave_days'] = $value->no_of_days;
        $last_leave_data[$key]['leave_type'] = $value->leave_type_name;
        if($value->leave_paid==1){
          $last_leave_data[$key]['leave_type'] .= " [Paid]";
        }else{
          $last_leave_data[$key]['leave_type'] .= " [UnPaid]";
        }
      }
      // Get Annual Leave Allowance Summary

      $json_data['last_leave_data']  = $last_leave_data;
      echo json_encode($json_data);
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }

  public function create_payment()
  {
    $employee_payment_type =  $this->security->xss_clean($this->input->post('employee_payment_type'));
    $employee_id = $this->security->xss_clean($this->input->post('employee'));

    $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_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;
    }
    //Salary Slip
    if($employee_payment_type=='salary_slip'){
      $salary_slip_id = $this->security->xss_clean($this->input->post('salary_slip'));
      if($this->security->xss_clean($this->input->post('paid_amount'))>0){
        $transaction_data['reference_id'] = $salary_slip_id;
        $transaction_data['reference_type'] = "salary_slip";
        $transaction_data['tr_type'] = "salary_slip_transaction";
        $transaction_data['tr_description'] = "Salary Slip Transaction";
        $transaction_data['tr_credit_acc'] = 10;//Salary Slip payments
        $transaction_result =  $this->Account->create_account_transaction($transaction_data);
        $flash_data['status'] = $transaction_result['status'];
        if($flash_data['status']==1){
          $flash_data['flashdata_msg'] = 'Salary Slip Transaction Added 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 !!';
        }
      }
      $this->bills_management->calculate_salary_slip_total($salary_slip_id);
    }elseif($employee_payment_type=='op_balance'){
      //Opening Balance
      if($this->security->xss_clean($this->input->post('paid_amount'))>0){
        $transaction_data['reference_id'] = $employee_id;
        $transaction_data['reference_type'] = "employee";
        $transaction_data['tr_type'] = "employee_opbalance_transaction";
        $transaction_data['tr_description'] = "Employee Opening Balance Transaction";
        $transaction_data['tr_credit_acc'] = 16;//Employee payments
        $transaction_result =  $this->Account->create_account_transaction($transaction_data);
        $flash_data['status'] = $transaction_result['status'];
        if($flash_data['status']==1){
          $flash_data['flashdata_msg'] = 'Opening Balance Transaction Added 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 !!';
        }
      }
    }elseif($employee_payment_type=='advance_salary'){
      //Advance salary
      if($this->security->xss_clean($this->input->post('paid_amount'))>0){
        $transaction_data['reference_id'] = $employee_id;
        $transaction_data['tr_credit_acc'] = 16;//Employee payments
        $transaction_data['reference_type'] = "employee";
        $transaction_data['tr_work_id'] = $this->security->xss_clean($this->input->post('work_id'));
        $transaction_data['tr_other_data'] = date('Y-m',strtotime($this->security->xss_clean($this->input->post('month'))));
        $transaction_data['tr_type'] = "salary_advance_transaction";
        $transaction_data['tr_description'] = "Salary Advance Transaction";
        $transaction_result =  $this->Account->create_account_transaction($transaction_data);
        $flash_data['status'] = $transaction_result['status'];
        if($flash_data['status']==1){
          $flash_data['flashdata_msg'] = 'Advance Salary Transaction Added Successfully!.';
          $flash_data['flashdata_type'] = 'success';
          $flash_data['alert_type'] = 'success';
          $flash_data['flashdata_title'] = 'Success !';

          $this->bills_management->calculate_salary_slip_total('',$employee_id,$transaction_data['tr_other_data']);
        }
        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 !!';
        }
      }
    }elseif($employee_payment_type=='bata'){
      //Bata
      if($this->security->xss_clean($this->input->post('paid_amount'))>0){
        $transaction_data['reference_id'] = $employee_id;
        $transaction_data['tr_credit_acc'] = 16;//Employee payments
        $transaction_data['reference_type'] = "employee";
        $transaction_data['tr_work_id'] = $this->security->xss_clean($this->input->post('work_id'));
        $transaction_data['tr_other_data'] = date('Y-m',strtotime($this->security->xss_clean($this->input->post('month'))));
        $transaction_data['tr_type'] = "employee_bata_transaction";
        $transaction_data['tr_description'] = "Employee Bata Transaction";
        $transaction_result =  $this->Account->create_account_transaction($transaction_data);
        $flash_data['status'] = $transaction_result['status'];
        if($flash_data['status']==1){
          $flash_data['flashdata_msg'] = 'Employee Bata Transaction Added Successfully!.';
          $flash_data['flashdata_type'] = 'success';
          $flash_data['alert_type'] = 'success';
          $flash_data['flashdata_title'] = 'Success !';

          // $this->bills_management->calculate_salary_slip_total('',$employee_id,$transaction_data['tr_other_data']);
        }
        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 !!';
        }
      }
    }

    echo(json_encode($flash_data));

  }

  public function select_attendance($param=""){

    $attendance_status =  0;
    $json_data=array();
    $j=0;
    $sl_no=0;
    $array=array();
    $data=array();
    if(isset($_POST['employee']) && $_POST['employee']!='' && $_POST['employee']!='all'){
      $data['e.employee_id'] = $_POST['employee'];
    }

    $employees	= $this->Employee->select_employee("*",$data)->result();

    if(isset($_POST['date']) && $_POST['date']!=''){
      $date=array();
      $date=explode('-',$_POST['date']);
      $start_date=date('Y-m-d', strtotime($date[0]));
      $end_date=date('Y-m-d', strtotime($date[1]));
      // of period 1 day
      $interval = new DateInterval('P1D');
      $realEnd = new DateTime($end_date);
      $realEnd->add($interval);
      $date_period = new DatePeriod(new DateTime($start_date), $interval, $realEnd);

      foreach ($date_period as $key => $value) {
        $marked_data=$not_marked_data = array();
        $i=$k=0;
        foreach($employees as $row):
          $attendance_data = array();
          $btn_delete = '';
          // Check Attendece Exist ot Not
          $where['ea.employee_id'] = $row->employee_id;
          $where['ea.attendance_date'] = $value->format('Y-m-d');
          $where['ea.delete_status'] = 0;
          $attendance = $this->Employee->select_employee_attendance('ea.*',$where);

          if($attendance->num_rows()==1){
            $attendance = $attendance->row();

            $marked_data[$i] = array("attendance_id"=>'',"attendance_status"=>'',"signed_in_time"=>'',"signed_in_from"=>'',"signed_in_landmark"=>'',"signed_in_latitude"=>'',"signed_in_longitude"=>'',
            "signed_off_time"=>'',"signed_off_from"=>'',"signed_off_latitude"=>'',"signed_off_longitude"=>'',
            "leave_marked_time"=>'',"leave_marked_from"=>'',"leave_marked_latitude"=>'',"leave_marked_longitude"=>'',"attendance"=>'',"actions"=>'',"status"=>'',"worked_time"=>'');

            $marked_data[$i]['date'] = $value->format('d-m-Y');
            $marked_data[$i]['day'] = date('l',strtotime($value->format('Y-m-d')));
            $marked_data[$i]['employee_name'] = $row->employee_name;
            $marked_data[$i]['employee_id'] = $row->employee_id;
            $marked_data[$i]['attendance_id'] = $attendance->attendance_id;
            $marked_data[$i]['department'] = $row->department_name;
            $marked_data[$i]['biometric_id'] = $row->biometric_id;
            // $marked_data[$i]['attendance_status'] = "<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check-circle'></i> Marked</span>";
            // if($attendance->created_by!=$row->user_id){
            //   $marked_data[$i]['attendance_status'] .="<br/><span style='margin-top: 5px' class='m-badge m-badge--warning m-badge--wide'> Marked By ".$attendance->created_user."</span>";
            // }
            // $marked_data[$i]['attendance'] = "<span style='margin-top: 5px' class='m-badge m-badge--primary m-badge--wide'><i class='la la-calendar-check-o'></i> Marked As on Duty</span>";
            //
            // if(date('H:i',strtotime($attendance->signed_in_time)) > date('H:i',strtotime($row->duty_start_time))){
            //   $marked_data[$i]['attendance'] .="<br/><span style='margin-top: 5px' class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Signed In Late </span>";
            // }elseif(date('H:i',strtotime($attendance->signed_in_time)) < date('H:i',strtotime($row->duty_start_time))){
            //   $marked_data[$i]['attendance'] .="<br/><span style='margin-top: 5px' class='m-badge m-badge--info m-badge--wide'><i class='fa fa-check'></i> Signed In Early</span>";
            // }else{
            //   $marked_data[$i]['attendance'] .="<br/><span style='margin-top: 5px' class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Signed In On Time</span>";
            // }

            if($attendance->clock_in!='00:00:00'){
              $marked_data[$i]['signed_in_time'] = $attendance->clock_in;
            }else{
              $marked_data[$i]['signed_in_time'] = '';
            }
            if($attendance->clock_out!='00:00:00'){
              $marked_data[$i]['signed_off_time'] = $attendance->clock_out;
            }else{
              $marked_data[$i]['signed_off_time'] = '';
            }
            if($attendance->worked_time!='00:00:00'){
              $marked_data[$i]['worked_time'] = $attendance->worked_time;
            }else{
              $marked_data[$i]['worked_time'] = '';
            }

            if($this->session->userdata('user_role')=='admin') {
              $marked_data[$i]['actions'] = '<a style="margin-left: 5px;margin-right: 5px" id="attendance_edit_btn" href="#attendance_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>';
              $marked_data[$i]['actions'] .= '<a style="margin-left: 5px;margin-right: 5px" id="daily_attendance_delete_btn" href="#daily_attendance_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>';
            }
            $i++;

          }else{
            if($attendance_status==0 || $attendance_status==2){
              $not_marked_data[$k]['date'] = $value->format('d-m-Y');
              $not_marked_data[$k]['day'] = date('l',strtotime($value->format('Y-m-d')));
              $not_marked_data[$k]['employee_name'] = $row->employee_name;
              $not_marked_data[$k]['employee_id'] = $row->employee_id;
              $not_marked_data[$k]['department'] = $row->department_name;
              $not_marked_data[$k]['biometric_id'] = $row->biometric_id;
              $k++;
            }
          }
        endforeach;

        // Sort By Signed In Time
        usort($marked_data, function($a, $b) {
          // return $a['date'] <=> $b['date'];
          if (date('H:i:s',strtotime($a['signed_in_time'])) == date('H:i:s',strtotime($b['signed_in_time']))) return 0;
          return date('H:i:s',strtotime($a['signed_in_time'])) < date('H:i:s',strtotime($b['signed_in_time'])) ? -1 : 1;
        });
        foreach ($marked_data as $key => $value) {
          $sl_no++;
          $array[$j][]=$sl_no;
          $array[$j][]=$marked_data[$key]['attendance_id'];
          $array[$j][]=$marked_data[$key]['date'];
          $array[$j][]=$marked_data[$key]['day'];
          $array[$j][]=$marked_data[$key]['biometric_id'];
          $array[$j][]=$marked_data[$key]['department'];
          $array[$j][]=$marked_data[$key]['employee_name'];
          // $array[$j][]=$marked_data[$key]['attendance_status'];
          // $array[$j][]=$marked_data[$key]['attendance'];
          if($marked_data[$key]['signed_in_time']!='00:00:00'){
            $array[$j][]=date("H:i",strtotime($marked_data[$key]['signed_in_time']));
          }else{
            $array[$j][]="";
          }
          if($marked_data[$key]['signed_off_time']!='00:00:00'){
            $array[$j][]=date("H:i",strtotime($marked_data[$key]['signed_off_time']));
          }else{
            $array[$j][]="";
          }
          if($marked_data[$key]['worked_time']!='00:00:00'){
            $array[$j][]=date("H:i",strtotime($marked_data[$key]['worked_time']));
          }else{
            $array[$j][]="";
          }
          //
          // if($marked_data[$key]['signed_in_time']!='' && $marked_data[$key]['signed_off_time']!=''){
          //   $work_start_time = new DateTime(date('Y-m-d').' '.date("h:i:s A",strtotime($marked_data[$key]['signed_in_time'])));
          //   $work_end_time = new DateTime(date('Y-m-d').' '.date("h:i:s A",strtotime($marked_data[$key]['signed_off_time'])));
          //   $actual_worked_time = $work_start_time->diff($work_end_time);
          //   $actual_worked_time = $actual_worked_time->format('%H').":".$actual_worked_time->format('%I');
          //   $array[$j][] = $actual_worked_time;
          //
          //   if($row->duty_start_time!='' && $row->duty_start_time!='00:00:00' && $row->duty_end_time!='' && $row->duty_end_time!='00:00:00' ){
          //     $duty_start_time_normal = new DateTime(date('Y-m-d').' '.date("h:i:s A",strtotime($row->duty_start_time)));
          //     $duty_end_time_normal = new DateTime(date('Y-m-d').' '.date("h:i:s A",strtotime($row->duty_end_time)));
          //     $normal_work_time = $duty_start_time_normal->diff($duty_end_time_normal);
          //     $normal_work_time = $normal_work_time->format('%H').":".$normal_work_time->format('%I');
          //
          //     $normal_work_time_1 = new DateTime($normal_work_time.":00");
          //     $actual_worked_time_1 = new DateTime($actual_worked_time.":00");
          //     $overtime = $normal_work_time_1->diff($actual_worked_time_1);
          //     $overtime =  $overtime->format('%H').":".$overtime->format('%I');
          //     $array[$j][]=$overtime;
          //   }else{
          //     $array[$j][]=0;
          //   }
          // }else{
          //   $array[$j][]="";
          //   $array[$j][]=0;
          // }

          $array[$j][]=$marked_data[$key]['actions'];
          $j++;
        }
        foreach ($not_marked_data as $key => $value) {
          $sl_no++;
          $array[$j][]=$sl_no;
          $array[$j][]='';
          $array[$j][]=$not_marked_data[$key]['date'];
          $array[$j][]=$not_marked_data[$key]['day'];
          $array[$j][]=$not_marked_data[$key]['biometric_id'];
          $array[$j][]=$not_marked_data[$key]['department'];
          $array[$j][]=$not_marked_data[$key]['employee_name'];
          $array[$j][]='';
          $array[$j][]='';
          $array[$j][]='';
          $array[$j][]='';
          $j++;
        }

      }
    }

    $json_data['draw']=5;
    $json_data['recordsTotal']=sizeof($array);
    $json_data['recordsFiltered']=sizeof($array);
    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function select_site_visit_log($param=""){
    $json_data=array();
    $j=0;
    $sl_no=0;
    $array=array();
    $data=array();
    if(isset($_POST['employee']) && $_POST['employee']!='' && $_POST['employee']!='all'){
      $data['e.employee_id'] = $_POST['employee'];
    }
    if(isset($_POST['date']) && $_POST['date']!=''){
      $date=array();
      $date=explode('-',$_POST['date']);
      $start_date=date('Y-m-d', strtotime($date[0]));
      $end_date=date('Y-m-d', strtotime($date[1]));
      $data["STR_TO_DATE(esv.visit_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(esv.visit_date,'%Y-%m-%d') >="]= $start_date;
    }
    $site_vist = $this->Employee->select_employee_site_vist('esv.*,e.employee_name,ed.department_name,wc.work_name,u.user_alias as created_user',$data)->result();
    foreach($site_vist as $row):

      $sl_no++;
      $array[$j][]=$sl_no;
      $array[$j][]=$row->visit_id;
      $array[$j][]=date('d-m-Y',strtotime($row->visit_date));
      $array[$j][]=date('D',strtotime($row->visit_date));
      $array[$j][]=$row->department_name;
      $array[$j][]=$row->employee_name;
      $array[$j][]=$row->work_name;
      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->created_user."</li>";
      }else{
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->created_user.'</li>';
      }

      $j++;
    endforeach;

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

  public function import_attendance()
  {

    if ($_FILES['csv']["size"] > 0) {
      $dup_data = array();
      $filename = $_FILES["csv"]["tmp_name"];
      if (($getfile = fopen($filename, "r")) !== FALSE) {
        $data = fgetcsv($getfile, 1000, ",");
        $count = $success = $error = $dup = 0;
        $error_sl_no = array();
        $sl_no=1;
        while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
          $sl_no++;
          $num = count($data);
          $slice = $data;
          $attendance_data = array();
          $attendance_data['created_by'] = $this->session->userdata('user_id');
          $attendance_data['created_date'] = date('Y-m-d H:i:s');
          $employee_data = $this->Employee->select_employee("e.*",array('e.biometric_id' => $slice[0]));
          if($employee_data->num_rows()==1) {
            $employee_data = $employee_data->row();
            $attendance_data['employee_id'] = $employee_data->employee_id;
          }else{
            // Create Employee
            $employee_insert_data['employee_name'] = $slice[2];
            $employee_insert_data['user_designation'] = $slice[1];
            $employee_insert_data['basic_wage_type'] = 'Monthly';
            $employee_insert_data['basic_wage_fixed'] = 1;
            $employee_insert_data['biometric_id'] = $slice[0];
            $employee_insert_data['created_by'] = $this->session->userdata('user_id');
            $employee_insert_data['created_date'] = date('Y-m-d H:i:s');
            $department_data['department_name'] = $slice[1];
            if($slice[1]!=''){
              $department_details = $this->Employee->select_employee_department("",array("department_name"=>$department_data['department_name']));
              if($department_details->num_rows()==0){
                $department_data['editable'] = 1;
                $department_result = $this->Employee->create_employee_department($department_data);
                $employee_insert_data['department'] = $department_result['insert_id'];
              }else{
                $employee_insert_data['department'] = $department_details->row()->department_id;
              }
            }else{
              $employee_insert_data['department'] = 0;//default
            }
            $employee_insert_result = $this->Employee->create_employee($employee_insert_data);
            $attendance_data['employee_id'] = $employee_insert_result['insert_id'];
          }
          if($slice[6]!=''){
            $attendance_data['attendance_date'] = date('Y-m-d',strtotime($slice[3]));
            $attendance_count = $this->Employee->select_employee_attendance("ea.*",array('ea.attendance_date' => $attendance_data['attendance_date'],"ea.employee_id"=>$attendance_data['employee_id']))->num_rows();
            if($attendance_count==0){
              $attendance_data['clock_in'] = $slice[4];
              $attendance_data['clock_out'] = $slice[5];
              $attendance_data['worked_time'] = $slice[6];
              $result = $this->Employee->create_employee_attendance($attendance_data);
              if($result['status']==1){
                $success++;
                // echo $slice[0]." Imported Success<br/>";
              }else{
                $error++;
                // echo $slice[0]." Error<br/>";
              }
            }else{
              // echo $slice[0]." Already Exist<br/>";
            }
          }
        }


        if($success>0 && $error==0){
          $flash_data['flashdata_msg'] = $success.' Data Imported Successfully!.';
          $flash_data['flashdata_type'] = 'info';
          $flash_data['alert_type'] = 'info';
          $flash_data['flashdata_title'] = 'Success !';
        }elseif($success>0 && $error>0){
          $flash_data['flashdata_msg'] = $success.' Data Imported Successfully!.<br/>'.$error.' Data Not Imported!.';
          $flash_data['flashdata_type'] = 'warning';
          $flash_data['alert_type'] = 'warning';
          $flash_data['flashdata_title'] = 'Some Error Occurred !';
        }elseif($error>0){
          $flash_data['flashdata_msg'] = $error.' Data Not Imported!.';
          $flash_data['flashdata_type'] = 'warning';
          $flash_data['alert_type'] = 'warning';
          $flash_data['flashdata_title'] = 'Some Error Occurred !';
        }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['flashdata_msg'] = 'Sorry.. Some Error Occurred with File!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else {
      $flash_data['flashdata_msg'] = 'Sorry.. Some Error Occurred with File!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['error_sl_no'] = $error_sl_no;
    $this->session->set_flashdata($flash_data);
    // echo "<br/></br/>";
    // print_r($flash_data);
    redirect(base_url(). 'employees/attendance','refresh');
  }

  public function select_employee_leave_applications(){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $data=array();

    $result	= $this->Employee->select_employee_leave_applications("la.*,lt.leave_type_name,lt.leave_paid,u.user_alias,e.civil_id,e.employee_name,ed.department_name,e.phone_no,e.user_designation,u1.user_alias as approved_1_user",$data);
    $result_array=$result->result();

    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();

    foreach($result_array as $row):
      $btn_edit = '';
      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager'){
        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="leave_application_edit_btn" href="#leave_application_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>';
      }
      $approval_status_1='';
      if($row->approval_status_1==1){
        $approval_status_1='<span class="m-badge m-badge--primary m-badge--wide">Approved</span>';
        $approval_status_1.='<br/>Approved By '.$row->approved_1_user;
      }elseif($row->approval_status_1==2){
        $approval_status_1='<span class="m-badge m-badge--danger m-badge--wide">Rejected</span>';
        $approval_status_1.='<br/>Rejected By '.$row->approved_1_user;
      }else{
        $approval_status_1='<span class="m-badge m-badge--warning m-badge--wide">Pending</span>';
      }

      if($row->day_type=='half'){
        $day_type='<br/><span class="m-badge m-badge--warning m-badge--wide">Half Day</span>';
      }else{
        $day_type='<br/><span class="m-badge m-badge--info m-badge--wide">Full Day</span>';
      }

      $sl_no++;
      if($row->leave_paid==1){
        $leave_paid = ' [Paid]';
      }else{
        $leave_paid = ' [UnPaid]';
      }

      $array[$j][]=$row->application_id;
      $array[$j][]=$sl_no;
      $array[$j][]=$row->employee_name;
      $array[$j][]=$row->phone_no;
      $array[$j][]=$row->department_name;
      $array[$j][]=$row->civil_id;
      $array[$j][]=$row->user_designation;
      $array[$j][]=$row->leave_type_name.$leave_paid.$day_type;
      $array[$j][]=date('d-m-Y',strtotime($row->leave_date_from))." To ".date('d-m-Y',strtotime($row->leave_date_to));
      $array[$j][]=$row->no_of_days;
      $array[$j][]=$row->leave_reason;
      $array[$j][]=$approval_status_1."<br/>".$row->approved_remarks_1;
      $array[$j][]='';
      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>";
      }else{
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>';
      }
      $array[$j][]=$btn_edit;
      $array[$j][]=$row->employee_id;
      $array[$j][]=$row->leave_type;
      $array[$j][]=$row->approval_status_1;
      $array[$j][]=$row->approved_remarks_1;
      $array[$j][]=$row->day_type;
      $array[$j][]=date('d-M-Y',strtotime($row->leave_date_from));
      $array[$j][]=date('d-M-Y',strtotime($row->leave_date_to));

      $j++;

    endforeach;
    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function create_leave_application()
  {
    $data['employee_id'] = $this->security->xss_clean($this->input->post('employee'));
    $data['leave_type'] = $this->security->xss_clean($this->input->post('leave_type'));
    $data['leave_date_from'] = date('Y-m-d',strtotime($this->input->post('leave_date_from')));
    $data['leave_date_to'] = date('Y-m-d',strtotime($this->input->post('leave_date_to')));
    $data['no_of_days'] = $this->security->xss_clean($this->input->post('no_of_days'));
    $data['day_type'] = $this->security->xss_clean($this->input->post('day_type'));
    $data['leave_reason'] = $this->security->xss_clean($this->input->post('leave_reason'));
    $data['created_by'] = $this->session->userdata('user_id');
    $data['created_date'] = date('Y-m-d H:i:s');

    $result2 = $this->Employee->create_employee_leave_applications($data);
    $flash_data['status'] = $result2['status'];
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Leave Application Added 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 update_leave_application()
  {

    $data['application_id'] = $this->security->xss_clean($this->input->post('application_id'));
    $leave_application_data = $this->Employee->select_employee_leave_applications("la.*,e.user_id", $data)->row();
    $data['leave_type'] = $this->security->xss_clean($this->input->post('leave_type'));
    $data['no_of_days'] = $this->security->xss_clean($this->input->post('no_of_days'));
    $data['day_type'] = $this->security->xss_clean($this->input->post('day_type_edit'));
    $data['approval_status_1'] = $this->security->xss_clean($this->input->post('leave_application_status'));
    $data['approved_remarks_1'] = $this->security->xss_clean($this->input->post('remarks'));
    $data['approved_by_1'] = $this->session->userdata('user_id');

    $result = $this->Employee->update_employee_leave_applications($data);
    $flash_data['status'] = $result;
    if ($result == 1) {
      if($leave_application_data->user_id!=0){

        //  Start date
        $date = $leave_application_data->leave_date_from;
        // End date
        $end_date = $leave_application_data->leave_date_to;

        while (strtotime($date) <= strtotime($end_date)) {
          // Create Leave Entry in Attendance
          $leave_data = array();
          $leave_data['user_id'] = $leave_application_data->user_id;
          $leave_data['leave_type'] = $data['leave_type'];
          $leave_data['day_type'] = $data['day_type'];
          $leave_data['attendance_date'] = $date;
          $leave_data['attendance_status'] = 2;
          //          Check Already Exist
          $where['uat.user_id'] = $leave_data['user_id'];
          $where['uat.attendance_date'] = $date;
          $where['uat.delete_status'] = 0;
          $count = $this->Attendance->select_attendance('attendance_id',$where);
          if($data['approval_status_1']==1){
            if($count->num_rows()==0){
              $leave_data['created_date'] = date('Y-m-d H:i:s');
              $leave_data['created_by'] = $this->session->userdata('user_id');
              $result = $this->Attendance->insert_attendance($leave_data);
            }else{
              $leave_data['attendance_id'] = $count->row()->attendance_id;
              $result = $this->Attendance->update_attendance($leave_data);
            }
          }elseif($data['approval_status_1']==2 && $count->num_rows()==1){
            // Check Attendance Already Created, & Delete
            $leave_data['attendance_id'] = $count->row()->attendance_id;
            $leave_data['delete_status'] = 1;
            $result = $this->Attendance->update_attendance($leave_data);
          }
          // Increment Date
          $date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
        }
      }

      $flash_data['flashdata_msg'] = 'Leave Application Status Updated 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 !!';
    }

    echo (json_encode($flash_data));
  }

  public function create_department()
  {
    $data['department_name'] = $this->security->xss_clean($this->input->post('department_name'));
    $count = $this->Employee->select_employee_department("",$data)->num_rows();
    if($count==0) {
      $data['editable'] = 1;
      $result2 = $this->Employee->create_employee_department($data);
      $flash_data['status'] = $result2['status'];
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'HR Department Added 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 !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. HR Department Same Name 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 select_departments_list(){
    $data=array();
    if(isset($_POST['id']) && $_POST['id']!=""){
      $data['department_id'] = $_POST['id'];
    }
    if($this->config->item('app_module_vehicle_management')!=1){
      $data['department_id !='] = 1;
    }
    $result	= $this->Employee->select_employee_department("",$data);
    if($result->num_rows()>0) {
      $json_data['count'] = $result->num_rows();
      $json_data['data'] = $result->result();
      echo json_encode($json_data);
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }

  public function select_employee_leave_report(){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $data=array();
    $data['e.user_id !='] = 0;
    $result	= $this->Employee->select_employee("e.*,u.user_alias,ed.department_name",$data);
    $result_array=$result->result();

    $leave_types = $this->Employee->select_leave_types("")->result();
    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();

    foreach($result_array as $row):


      $sl_no++;

      $array[$j][]=$sl_no;
      $array[$j][]=$row->employee_name;
      $array[$j][]=$row->department_name;
      $array[$j][]=$row->user_designation;
      foreach ($leave_types as $key => $value) {

        $leave_where['uat.user_id'] = $row->user_id;
        $leave_where['leave_type'] = $value->leave_type_id;
        $leave_where['attendance_date >='] = date('Y-m-d',strtotime(date('Y-01-01')));
        $leave_where['attendance_date <='] = date('Y-m-d',strtotime(date('Y-12-31')));
        $leave_where['attendance_status'] = 2;
        $array[$j][] = $this->Attendance->select_attendance('attendance_id',$leave_where)->num_rows();

      }

      $j++;

    endforeach;
    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
}
?>
