<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Labours 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('Client_model', 'Client');
    $this->load->model('Labour_model', 'Labour');
    $this->load->model('Labour_wages_model', 'Labour_wages');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->library('phpqrcode/qrlib');
    $this->load->library('Projects_management','projects_management');

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

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

  public function view()
  {
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['work_types'] = $this->Work->select_work_types()->result();
    $this->page_data['labours'] = $this->Labour->select_labours()->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();
    $this->page_data['labour_groups'] = $this->Labour->select_labours("",array("labour_type"=>1,"labour_group !="=>0,"group_position"=>1))->result();

    $this->page_data['page_name'] = 'labours_view';
    $this->load->view('Index', $this->page_data);
  }
  public function add_group()
  {
    $this->page_data['page_name'] = 'labours_add_group';
    $this->load->view('Index', $this->page_data);
  }
  public function attendance($type='')
  {
    $this->page_data['work_types'] = $this->Work->select_work_types()->result();
    $this->page_data['labour_groups'] = $this->Labour->select_labours("",array("labour_type"=>1,"labour_group !="=>0,"group_position"=>1))->result();

    $this->page_data['work_id'] = "";
    if(isset($_GET['work_id']) && $_GET['work_id']!=''){
      $this->page_data['work_id'] = $_GET['work_id'];
    }
    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['labours'] = $this->Labour->select_labours("")->result();

    if($type=='add'){
      $this->page_data['page_name'] = 'labour_attendance_add';
    }else{
      $this->page_data['page_name'] = 'labour_attendance_view';
    }
    $this->load->view('Index', $this->page_data);
  }
  public function assign_project()
  {
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    $this->page_data['page_name'] = 'labour_assign_project';
    $this->load->view('Index', $this->page_data);
  }
  public function insurance_fd()
  {
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['labours_2'] = $this->Labour->select_labours()->result();

    $this->page_data['page_name'] = 'labour_insurance_fd';
    $this->load->view('Index', $this->page_data);
  }
  public function print_qrcode($id=""){
    if($id!="") {
      $this->page_data['labour_data'] = $this->Labour->select_labours("l.*,wt.type_name", array("labour_id" => $id));
      if($this->page_data['labour_data']->num_rows()==1){
        $this->page_data['labour_data'] = $this->page_data['labour_data']->row();
        $SERVERFILEPATH = FCPATH.'/uploads/labours/';
        $text = "labour_id=".$this->page_data['labour_data']->labour_id;
        $text1= $this->page_data['labour_data']->labour_id;

        $folder = $SERVERFILEPATH;
        $file_name1 = $text1."-Qrcode.png";
        $file_name = $folder.$file_name1;
        QRcode::png($text,$file_name,'L', 10, 2);

        $this->page_data['qr_code_image'] = $file_name1;

        $this->page_data['page_name'] = 'labour_qr_code';
        $this->load->view('Index',$this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }
  public function profile($id="")
  {
    if($id!="") {
      $labour_where = $labour_2_where=$work_data = array();
      $this->page_data['work_contracts'] = $this->Work->select_work("*",$work_data)->result();

      $this->page_data['labour_data'] = $this->Labour->select_labours("l.*,wt.type_name", array("labour_id" => $id));
      if($this->page_data['labour_data']->num_rows()==1){
        $this->page_data['labour_data'] = $this->page_data['labour_data']->row();
        if($this->page_data['labour_data']->labour_type==1 && $this->page_data['labour_data']->group_position==0){
          $this->page_data['labour_head_data'] = $this->Labour->select_labours("*", array("labour_group" => $this->page_data['labour_data']->labour_group,"group_position" => 1));
          $labour_where['l.labour_id'] = $id;
          $labour_2_where['l.labour_group'] = $this->page_data['labour_data']->labour_group;
        }elseif($this->page_data['labour_data']->labour_type==1 && $this->page_data['labour_data']->group_position==1){
          $labour_where['l.labour_group'] = $labour_2_where['l.labour_group'] = $this->page_data['labour_data']->labour_group;
        }else{
          $labour_where['l.labour_id'] = $labour_2_where['l.labour_id'] = $id;
        }

        $this->page_data['labours'] = $this->Labour->select_labours('',$labour_where)->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('',$labour_2_where)->result();
        $this->page_data['labour_groups'] = $this->Labour->select_labours("",array("labour_type"=>1,"labour_group !="=>0,"group_position"=>1))->result();


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

    }else{
      show_404();
    }

  }
  public function select_labour(){

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

    $data=array();
    $data['l.delete_status'] = 0;
    if(isset($_POST['labour_type']) && $_POST['labour_type']!='' && $_POST['labour_type']!='all'){
      $data['l.labour_type'] = $_POST['labour_type'];
    }

    if($this->config->item('Labour_projet_assigning')==1 && isset($_POST['work_id']) && $_POST['work_id']!='' && $_POST['work_id']!='all' ){
      $work_id = $_POST['work_id'];
      $this->db->where("FIND_IN_SET($work_id, l.assigned_projects)");
    }

    if(isset($_POST['labour_group_head']) && $_POST['labour_group_head']!='' && $_POST['labour_group_head']!='all'){
      $data['l.labour_group'] = $this->Labour->select_labours("l.labour_group",array("l.labour_id"=>$_POST['labour_group_head']))->row()->labour_group;
    }
    if($this->config->item('user_data_access_view_all')!=1){
      // $data['l.created_by'] = $this->session->userdata('user_id');
    }
    $result	= $this->Labour->select_labours("l.*,wt.type_name,u.user_alias",$data,array("labour_group","desc"),array("group_position","desc"),"","","",'all');
    $result_array=$result->result();


    $array=array();

    foreach($result_array as $row):

      $btn_edit = '';

      if($this->session->userdata('user_role')!='auditor'){
        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="labour_edit_btn" href="#labour_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_profile='<a style="margin-left: 5px;margin-right: 5px"  href="'.base_url().'labours/profile/'.$row->labour_id.'" class="btn btn-primary m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
      <i class="la la-eye"></i>
      </a>';

      $btn_qr_code='<a style="margin-left: 5px;margin-right: 5px" id="btn_qr_code" href="javascript:;" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
      <i class="la la-qrcode"></i>
      </a>';

      $btn_delete='';
      if($this->session->userdata('user_role')=='admin' || ($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="labour_delete_btn" href="#labour_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_add_member=$labour_type_name='';
      if($row->labour_type==0){
        $labour_type = "Individual Person";
      }else{
        $labour_type = "Group of Persons";
        if($row->group_position==1){
          $labour_type_name = "<br/><span style='margin-top: 5px' class='m-badge m-badge--success m-badge--wide'> Team Leader</span>";
          if($this->session->userdata('user_role')!='auditor' || $this->session->userdata('user_data_permission')['adding']==1){
            $btn_add_member='<a style="margin-left: 5px;margin-right: 5px" id="member_add_btn" href="#labour_add_modal" data-toggle="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>';
          }

          // Add a Blank Row
          $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][]="";
          $array[$j][]="";
          $array[$j][]="";

          $j++;
        }else{
          $labour_type_name = "<br/><span style='margin-top: 5px' class='m-badge m-badge--info m-badge--wide'> Team Member</span>";
        }
      }
      if($row->photo!=''){
        $image = base_url()."uploads/labours/".$row->photo;
      }else{
        $image = base_url()."uploads/labours/default.png";
      }
      $file = '';
      if($row->file_attachment!=''){
        $file = '<a target="_blank"  style="margin-left: 5px;margin-right: 5px"  href="'.base_url().'uploads/labours/'.$row->file_attachment.'" >Click To view</a>';
      }

      if($row->active_status==1){
        $active_status = "<span style='margin-top: 5px' class='m-badge m-badge--focus m-badge--wide'> Active</span>";
      }else{
        $active_status = "<span style='margin-top: 5px' class='m-badge m-badge--danger m-badge--wide'> Non Active</span>";
      }

      $labour_name = '<a href="' . base_url() . 'labours/profile/' . $row->labour_id . '"><div class="d-flex align-items-center">
      <div class="symbol symbol-60 symbol-xxl-100 mr-3 align-self-start align-self-xxl-center">
      <div class="symbol-label" style="background-image:url('.$image.')"></div>
      <i class="symbol-badge bg-success"></i>
      </div>
      </a>
      <div>
      <a href="' . base_url() . 'labours/profile/' . $row->labour_id . '" class="font-weight-bolder font-size-h5 text-dark-75 text-hover-primary">' . $row->labour_name . '</a>
      '.$labour_type_name.'<br/>'.$active_status.'</div></div>';

      if($row->fixed_wage==1){
        $fixed_wage = "Yes";
      }else{
        $fixed_wage = "No";
      }

      $contact = $row->labour_contact;
      if($row->labour_contact_2!=''){
        $contact.=',<br/>'.$row->labour_contact_2;
      }

      if($row->assigned_project_names!=''){
        $assigned_projects = explode(',', $row->assigned_project_names);
        $projects = '';
        foreach ($assigned_projects as $key => $value) {
          $projects .= "<span style='margin-top: 5px' class='m-badge m-badge--warning m-badge--wide'> ".$value."</span><br/>";
        }
      }else{
        $projects = '';
      }

      $array[$j][]=$row->labour_id;
      $array[$j][]=$labour_type;
      $array[$j][]= $labour_name;
      $array[$j][]=$contact;
      $array[$j][]=$row->type_name;
      $array[$j][]=$fixed_wage;
      $array[$j][]=number_format($row->daily_wage,$this->config->item('Currency_amount_decimals_2'),'.', '');
      $array[$j][]=number_format($row->overtime_rate_per_hr,$this->config->item('Currency_amount_decimals_2'),'.', '');
      $array[$j][]=number_format($row->ta_per_day,$this->config->item('Currency_amount_decimals_2'),'.', '');
      $array[$j][]=number_format($row->opening_balance,$this->config->item('Currency_amount_decimals_2'),'.', '');
      $array[$j][]=$row->aadhar_no;
      $array[$j][]=$row->address;
      $array[$j][]=$file;
      $array[$j][]=$btn_add_member;
      $array[$j][]=$projects;
      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_profile.$btn_qr_code.$btn_edit.$btn_delete;
      $array[$j][]=$row->work_type;
      $array[$j][]=$row->labour_type;
      $array[$j][]=$row->fixed_wage;
      $array[$j][]=$row->labour_name;
      $array[$j][]=$row->labour_group;
      $array[$j][]=$row->assigned_projects;
      $array[$j][]=$row->photo;
      $array[$j][]=$row->active_status;
      $array[$j][]=$row->file_attachment;


      $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_labour_payment_summary(){

    $json_data=array();
    $j=$show_worked_only=0;
    $total_overtime=$total_worked_days=$total_basic_wage=$total_overtime_wage=$total_extra_wage=$total_op_balance=$total_wage_amount=$total_paid_amount=$total_balance_amount=0;
    $data=array();
    $data['l.delete_status'] = 0;
    if($this->config->item('user_data_access_view_all')!=1){
      // $data['l.created_by'] = $this->session->userdata('user_id');
    }
    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))');
    }
    if(isset($_POST['labour']) && $_POST['labour']!='' && $_POST['labour']!='all'){
      $data['l.labour_id'] = $_POST['labour'];
    }
    if(isset($_POST['work_type']) && $_POST['work_type']!='' && $_POST['work_type']!='all'){
      $data['l.work_type'] = $_POST['work_type'];
    }
    if(isset($_POST['labour_group_head']) && $_POST['labour_group_head']!='' && $_POST['labour_group_head']!='all'){
      $data['l.labour_group'] = $this->Labour->select_labours("l.labour_group",array("l.labour_id"=>$_POST['labour_group_head']))->row()->labour_group;
    }
    if(isset($_POST['worked_only']) && $_POST['worked_only']!='' && $_POST['worked_only']==1){
      $show_worked_only = 1;
    }
    $result	= $this->Labour->select_labours("l.*,wt.type_name,u.user_alias",$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):
      $labour_type_name = '';
      if($row->labour_type==0){
        // $labour_name .= "<br/>Individual";
      }else{
        if($row->group_position==1){
          $labour_type_name = "<br/><span style='margin-top: 5px' class='m-badge m-badge--success m-badge--wide'> Team Leader</span>";
        }else{
          $labour_type_name = "<br/><span style='margin-top: 5px' class='m-badge m-badge--info m-badge--wide'> Team Member</span>";
        }
      }
      $wage_data = $payment_data =  array();

      //profile filters
      $date_filter_applied = 0;
      if(isset($_POST['month']) && $_POST['month']!=''){
        $start_date=date('Y-m', strtotime($_POST['month']));
        $wage_data["lw.work_date >="] = $start_date."-01";
        $wage_data['lw.work_date !='] = '0000-00-00';
        $payment_data['ats.tr_date >='] = $start_date."-01";
        $date_filter_applied = 1;

        $end_date=date('Y-m', strtotime($_POST['month']));
        $wage_data['lw.work_date <='] = $end_date."-".date('t',strtotime($_POST['month']));
        $wage_data['lw.work_date !='] = '0000-00-00';
        $payment_data['ats.tr_date <='] = $end_date."-".date('t',strtotime($_POST['month']));
        $date_filter_applied = 1;
      }
      if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
        $start_date=date('Y-m-d', strtotime($_POST['start_date']));
        $wage_data['lw.work_date >='] = $start_date;
        $wage_data['lw.work_date !='] = '0000-00-00';
        $payment_data['ats.tr_date >='] = $start_date;
        $date_filter_applied = 1;
      }
      if(isset($_POST['end_date']) && $_POST['end_date']!='' && $_POST['end_date']!='all'){
        $end_date=date('Y-m-d', strtotime($_POST['end_date']));
        $wage_data['lw.work_date <='] = $end_date;
        $wage_data['lw.work_date !='] = '0000-00-00';
        $payment_data['ats.tr_date <='] = $end_date;
        $date_filter_applied = 1;
      }
      if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
        $wage_data['lw.work_id'] = $_POST['work'];
      }
      if($this->config->item('Labour_group_member_payment')==0 && $row->labour_type==1 && $row->group_position==1){
        $wage_data['l.labour_group'] = $row->labour_group;
      }else{
        $wage_data['lw.labour_id'] = $row->labour_id;
      }

      $worked_days = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.work_days),0) as total",$wage_data)->row()->total,2);
      $overtime = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.overtime_hours),0) as total",$wage_data)->row()->total,2);
      $basic_wage = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.work_days*lw.wage_per_day),0) as total",$wage_data)->row()->total,$this->config->item('Currency_amount_decimals_2'));
      $overtime_wage = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.overtime_wage),0) as total",$wage_data)->row()->total,$this->config->item('Currency_amount_decimals_2'));
      $extra_wage = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.extra_wage),0) as total",$wage_data)->row()->total,$this->config->item('Currency_amount_decimals_2'));
      $total_wage = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total",$wage_data)->row()->total,$this->config->item('Currency_amount_decimals_2'));

      $total_paid = $total_opening_wage_paid = $op_balance = 0;
      if($this->config->item('Labour_group_member_payment')==0 && $row->labour_type==1 && $row->group_position==1){
        $labour_data_where['l.labour_group'] = $row->labour_group;
        $total_opening_balance = $this->Labour->select_labours_2("COALESCE(SUM(l.opening_balance),0) as total",$labour_data_where)->row()->total;
      }else{
        $total_opening_balance = $row->opening_balance;
      }

      if((isset($_POST['work']) && $_POST['work']=='all') || (!isset($_POST['work']))){
        if($this->config->item('Labour_group_member_payment')==0 && $row->labour_type==1 && $row->group_position==1){
          $payment_data['l.labour_group'] = $row->labour_group;
        }else{
          $payment_data['l.labour_id'] = $row->labour_id;
        }

        $payment_data['ats.tr_type'] = 'labour_transaction';
        $payment_data['ats.reference_type'] = 'labour';
        $total_paid = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payment_data,'labour')->row()->total_amount;

        $opening_payment_data = $payment_data;
        unset($opening_payment_data['ats.tr_date >=']);
        unset($opening_payment_data['ats.tr_date <=']);
        if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
          $start_date=date('Y-m-d', strtotime($_POST['start_date']));
          $opening_payment_data['ats.tr_date <'] = $start_date;
        }
        if(isset($_POST['month']) && $_POST['month']!=''){
          $start_date=date('Y-m', strtotime($_POST['month']));
          $opening_payment_data['ats.tr_date <'] = $start_date."-01";
        }
        $total_opening_wage_paid = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$opening_payment_data,'labour')->row()->total_amount;



        if($date_filter_applied==1){
          $opening_wage_where = $wage_data;
          unset($opening_wage_where['lw.work_date <=']);
          unset($opening_wage_where['lw.work_date >=']);
          if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
            $start_date=date('Y-m-d', strtotime($_POST['start_date']));
            $opening_wage_where['lw.work_date <'] = $start_date;
          }
          if(isset($_POST['month']) && $_POST['month']!=''){
            $start_date=date('Y-m', strtotime($_POST['month']));
            $opening_wage_where['lw.work_date <'] =  $start_date."-01";
          }
          $total_opening_wage = $this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total",$opening_wage_where)->row()->total;
          $total_opening_wage_to_pay = $total_opening_wage + $total_opening_balance;

          $op_balance = $total_opening_wage_to_pay - $total_opening_wage_paid;
        }else{
          $op_balance = $total_opening_balance;
        }

        $total_wage_to_pay = $total_wage + $op_balance;
        $total_balance = $total_wage_to_pay-$total_paid;
      }else{
        $total_wage_to_pay = $total_wage;
        $total_balance = 0;
        $op_balance = $total_opening_balance;
      }

      if($row->photo!=''){
        $image = base_url()."uploads/labours/".$row->photo;
      }else{
        $image = base_url()."uploads/labours/default.png";
      }

      $labour_name = '<a href="' . base_url() . 'labours/profile/' . $row->labour_id . '"><div class="d-flex align-items-center">
      <div class="symbol symbol-60 symbol-xxl-100 mr-3 align-self-start align-self-xxl-center">
      <div class="symbol-label" style="background-image:url('.$image.')"></div>
      <i class="symbol-badge bg-success"></i>
      </div>
      </a>
      <div>
      <a href="' . base_url() . 'labours/profile/' . $row->labour_id . '" class="font-weight-bolder font-size-h5 text-dark-75 text-hover-primary">' . $row->labour_name . '</a>
      '.$labour_type_name.'
      </div>
      </div>';

      if(($show_worked_only==1 && $worked_days>0) || $show_worked_only==0){
        $array[$j][]=$row->labour_id;
        $array[$j][]=$labour_name;
        $array[$j][]=$row->labour_contact;
        $array[$j][]=$row->type_name;
        $array[$j][]=$row->daily_wage;
        $array[$j][]=$this->config->item('currency_format')->formatCurrency($op_balance,$this->config->item('Currency_currency_shortname'));
        $array[$j][]=$worked_days;
        $array[$j][]=$overtime;
        $array[$j][]=$this->config->item('currency_format')->formatCurrency($basic_wage,$this->config->item('Currency_currency_shortname'));
        $array[$j][]=$this->config->item('currency_format')->formatCurrency($overtime_wage,$this->config->item('Currency_currency_shortname'));
        $array[$j][]=$this->config->item('currency_format')->formatCurrency($extra_wage,$this->config->item('Currency_currency_shortname'));;
        $array[$j][]=$this->config->item('currency_format')->formatCurrency($total_wage_to_pay,$this->config->item('Currency_currency_shortname'));;
        $array[$j][]=$this->config->item('currency_format')->formatCurrency($total_paid,$this->config->item('Currency_currency_shortname'));;
        $array[$j][]=sprintf("%+d",$total_balance);
        if($this->session->userdata('user_role')!='auditor' || $this->session->userdata('user_data_permission')['adding']==1){
          $array[$j][]='<a  data-bill-type="labour"  id="btn_add_bill_payment" href="#bill_payment_add_modal" data-toggle="modal" class="btn m-btn--gradient-from-success m-btn--gradient-to-info  m-btn  m-btn--icon m-btn--air m-btn--pill">
          <span><i class="la la-plus"></i><span>Add Payment</span></span></a>';
        }else{
          $array[$j][]='';
        }
        if($total_balance>0){
          $array[$j][]=1;
        }elseif($total_balance<0){
          $array[$j][]=2;
        }else{
          $array[$j][]=0;
        }

        $total_op_balance+=$op_balance;
        $total_worked_days+=$worked_days;
        $total_overtime+=$overtime;
        $total_basic_wage+=$basic_wage;
        $total_overtime_wage+=$overtime_wage;
        $total_extra_wage+=$extra_wage;
        $total_wage_amount+=$total_wage_to_pay;
        $total_paid_amount+=$total_paid;
        $total_balance_amount+=$total_balance;

        $j++;
      }


    endforeach;

    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]="<strong>".$this->config->item('currency_format')->formatCurrency($total_op_balance,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$total_worked_days."</strong>";
      $array[$j][]="<strong>".$total_overtime."</strong>";
      $array[$j][]="<strong>".$this->config->item('currency_format')->formatCurrency($total_basic_wage,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('currency_format')->formatCurrency($total_overtime_wage,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('currency_format')->formatCurrency($total_extra_wage,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('currency_format')->formatCurrency($total_wage_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('currency_format')->formatCurrency($total_paid_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".sprintf("%+d",$total_balance_amount)."</strong>";
      $array[$j][]="";
      $array[$j][]="";
    }

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function select_labour_insurance_fd_summary(){

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

    if(isset($_POST['labour']) && $_POST['labour']!='' && $_POST['labour']!='all'){
      $data['l.labour_id'] = $_POST['labour'];
    }
    $result	= $this->Labour->select_labours("l.*,wt.type_name,u.user_alias",$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):
      $labour_type_name = '';
      if($row->labour_type==0){
        // $labour_name .= "<br/>Individual";
      }else{
        if($row->group_position==1){
          $labour_type_name = "<br/><span style='margin-top: 5px' class='m-badge m-badge--success m-badge--wide'> Team Leader</span>";
        }else{
          $labour_type_name = "<br/><span style='margin-top: 5px' class='m-badge m-badge--info m-badge--wide'> Team Member</span>";
        }
      }
      $wage_data = $payment_data =  array();

      $total_work_days_2 = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(CEILING(lw.work_days)),0) as total",array("lw.labour_id"=>$row->labour_id))->row()->total,2);
      $total_insurance_payable = $this->config->item('Labour_labour_insurance_amount')*$total_work_days_2;
      $total_fd_payable = $this->config->item('Labour_labour_fd_amount')*$total_work_days_2;
      $insurance_paid_where['l.labour_id'] = $fd_paid_where['l.labour_id'] = $row->labour_id;
      $insurance_paid_where['ats.reference_type'] = $fd_paid_where['ats.reference_type'] = 'labour';
      $insurance_paid_where['ats.tr_type'] = $fd_paid_where['ats.tr_type'] = 'labour_insurance_fd_transaction';
      $insurance_paid_where['ats.tr_other_data'] = 'insurance';
      $fd_paid_where['ats.tr_other_data'] = 'fd';
      $total_insurance_paid = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$insurance_paid_where,'labour_insurance_fd')->row()->total_amount;
      $total_fd_paid = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$fd_paid_where,'labour_insurance_fd')->row()->total_amount;

      $labour_name = '<a href="' . base_url() . 'labours/profile/' . $row->labour_id . '"><div class="d-flex align-items-center">
      <div class="symbol symbol-60 symbol-xxl-100 mr-3 align-self-start align-self-xxl-center">

      <i class="symbol-badge bg-success"></i>
      </div>
      </a>
      <div>
      <a href="' . base_url() . 'labours/profile/' . $row->labour_id . '" class="font-weight-bolder font-size-h5 text-dark-75 text-hover-primary">' . $row->labour_name . '</a>
      '.$labour_type_name.'
      </div>
      </div>';

      $btn_add_payment='<a  data-bill-type="labour"  id="btn_add_bill_payment" href="#bill_payment_add_modal" data-toggle="modal" class="btn m-btn--gradient-from-success m-btn--gradient-to-info  m-btn  m-btn--icon m-btn--air m-btn--pill">
      <span><i class="la la-plus"></i><span>Add Payment</span></span></a>';

      $array[$j][]= $j+1;
      $array[$j][]=$row->labour_id;
      $array[$j][]=$labour_name;
      $array[$j][]=$row->type_name;
      $array[$j][]=$total_work_days_2;
      $array[$j][]=$this->config->item('currency_format')->formatCurrency($total_insurance_payable,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$this->config->item('currency_format')->formatCurrency($total_insurance_paid,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$this->config->item('currency_format')->formatCurrency($total_insurance_payable-$total_insurance_paid,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$this->config->item('currency_format')->formatCurrency($total_fd_payable,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$this->config->item('currency_format')->formatCurrency($total_fd_paid,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$this->config->item('currency_format')->formatCurrency($total_fd_payable-$total_fd_paid,$this->config->item('Currency_currency_shortname'));
      $array[$j][]='';

      $j++;

    endforeach;

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

  public function assign_to_project()
  {
    $work_id = $this->security->xss_clean($this->input->post('work'));
    $selected_labours = $this->security->xss_clean($this->input->post('selected_labours'));
    $unchecked_labours = $this->security->xss_clean($this->input->post('unchecked_labours'));

    $unchecked_labours_array = explode(',', $unchecked_labours);
    foreach ($unchecked_labours_array as $key => $value) {

      $this->db->where("FIND_IN_SET($work_id, l.assigned_projects)");
      $labour_data = $this->Labour->select_labours("*",array('l.labour_id' => $value ));
      if($labour_data->num_rows()>0){
        $projects = $labour_data->row()->assigned_projects;
        $projects_array = explode(',', $projects);

        while(($i = array_search($work_id, $projects_array)) !== false) {
          unset($projects_array[$i]);
        }

        $data_uncheck['assigned_projects'] = implode(',', $projects_array);

        $data_uncheck['labour_id'] = $value;
        $result = $this->Labour->update_labour($data_uncheck);

      }
    }

    if (!empty($selected_labours)) {
      foreach ($selected_labours as $key => $value) {
        $this->db->where("FIND_IN_SET($work_id, l.assigned_projects)");
        $labour_data = $this->Labour->select_labours("*",array('l.labour_id' => $value ));
        if($labour_data->num_rows()==0){
          $assigned_projects = $this->Labour->select_labours("*",array('l.labour_id' => $value ))->row()->assigned_projects;
          if($assigned_projects==''){
            $data['assigned_projects'] = $work_id;
          }else{
            $data['assigned_projects'] = $assigned_projects.','.$work_id;
          }
          $data['labour_id'] = $value;
          $result = $this->Labour->update_labour($data);
        }
      }
    }else{
      $result = 1;
    }

    $flash_data['status'] = $result;
    if($flash_data['status'] == 1){

      $flash_data['flashdata_msg'] = 'Labours Assigned 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()
  {
    $data2['labour_name'] = $this->security->xss_clean($this->input->post('name'));
    $count = $this->Labour->select_labours("",$data2)->num_rows();
    $data2['labour_contact'] = $this->security->xss_clean($this->input->post('contact_no'));
    $data2['labour_type'] = $this->security->xss_clean($this->input->post('labour_type'));
    if($data2['labour_type']==1){
      $data2['labour_group'] = $this->security->xss_clean($this->input->post('labour_group'));
      $data2['group_position'] = 0;
    }
    $data2['fixed_wage'] = $this->security->xss_clean($this->input->post('fixed_wage'));
    $data2['work_type'] = $this->security->xss_clean($this->input->post('work_type'));
    $data2['daily_wage'] = $this->security->xss_clean($this->input->post('daily_wage'));
    $data2['overtime_rate_per_hr'] = $this->security->xss_clean($this->input->post('overtime_rate'));
    $data2['ta_per_day'] = $this->security->xss_clean($this->input->post('ta_amount'));
    $data2['opening_balance'] = $this->security->xss_clean($this->input->post('op_balance'));
    $data2['address'] = $this->security->xss_clean($this->input->post('address'));
    $data2['aadhar_no'] = $this->security->xss_clean($this->input->post('aadhar_no'));
    $data2['labour_contact_2'] = $this->security->xss_clean($this->input->post('contact_no_2'));
    $data2['created_date'] = date('Y-m-d H:i:s');
    $data2['created_by'] = $this->session->userdata('user_id');
    $file_error = 0;
    if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
      //      File Upload
      $config['upload_path']   = 'uploads/labours/';
      $config['allowed_types'] = 'jpg|jpeg|png';
      $config['max_size']      = 3000;
      $config['encrypt_name']    = TRUE;
      $this->load->library('upload', $config);
      if ( ! $this->upload->do_upload('uploaded_file')) {
        $error = array('error' => $this->upload->display_errors());
        $file_error = 1;
        $flash_data['flashdata_msg'] = $error['error'];
        $flash_data['flashdata_type'] = "warning";
        $flash_data['flashdata_title'] = "Uploaded File Error";
        $flash_data['status'] = 2;
      }else {
        $file_data = $this->upload->data();
        $data2['photo'] = $file_data['file_name'];
        $this->resizeImage("labours",$file_data['file_name']);
      }
    }
    if (isset($_FILES['uploaded_file_2']) && $_FILES['uploaded_file_2']["size"] > 0) {
      //      File Upload
      $config2['upload_path']   = 'uploads/labours/';
      $config2['allowed_types'] = 'jpg|jpeg|png|pdf';
      $config['max_size']      = 1000;
      $config2['overwrite']      = FALSE;
      $config2['encrypt_name']    = TRUE;
      $this->load->library('upload', $config2,'uploaded_file_2');
      $this->uploaded_file_2->initialize($config2);
      $upload_uploaded_file_2 = $this->uploaded_file_2->do_upload('uploaded_file_2');
      $file_data2 = $this->uploaded_file_2->data();
      $data2['file_attachment'] = $file_data2['file_name'];
    }
    if($file_error==0){
      if($count==0) {
        $result2 = $this->Labour->create_labour($data2);
        $flash_data['status'] = $result2['status'];
        if ($result2['status'] == 1) {
          $flash_data['flashdata_msg'] = 'Labour Added Successfully!.';
          $flash_data['message'] = 'Labour 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['message'] = '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.. Labour with Same Name Already Exist!';
        $flash_data['message'] = 'Sorry.. Labour with Same Name Already Exist!';
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Duplication !!';
      }
    }

    echo(json_encode($flash_data));
  }
  public function create_group()
  {
    // Team Leader Details
    $data2['labour_name'] = $this->security->xss_clean($this->input->post('name'));
    $count = $this->Labour->select_labours("",$data2)->num_rows();
    $data2['labour_contact'] = $this->security->xss_clean($this->input->post('contact_no'));
    $data2['labour_type'] = $data3['labour_type'] = $this->security->xss_clean($this->input->post('labour_type'));
    $data2['fixed_wage'] = $data3['fixed_wage'] = $this->security->xss_clean($this->input->post('fixed_wage'));
    $data2['work_type'] = $this->security->xss_clean($this->input->post('work_type'));
    $data2['daily_wage'] = $this->security->xss_clean($this->input->post('daily_wage'));
    $data2['opening_balance'] = $this->security->xss_clean($this->input->post('op_balance'));
    $data2['created_date'] = $data3['created_date'] = date('Y-m-d H:i:s');
    $data2['created_by'] = $data3['created_by'] = $this->session->userdata('user_id');
    $data2['address'] = $this->security->xss_clean($this->input->post('address'));
    $data2['aadhar_no'] = $this->security->xss_clean($this->input->post('aadhar_no'));
    $data2['labour_contact_2'] = $this->security->xss_clean($this->input->post('contact_no_2'));
    $previous_group_id =  $this->Labour->select_labours_max("labour_group");
    if($previous_group_id->num_rows()==1){
      $data2['labour_group'] = ($previous_group_id->row()->labour_group)+1;
    }else{
      $data2['labour_group'] = 1;
    }
    $data3['labour_group'] = $data2['labour_group'];
    $data2['group_position'] = 1;//Team Leaded
    $file_error = 0;
    if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
      //      File Upload
      $config['upload_path']   = 'uploads/labours/';
      $config['allowed_types'] = 'jpg|jpeg|png';
      $config['max_size']      = 3000;
      $config['encrypt_name']    = TRUE;
      $this->load->library('upload', $config);
      if ( ! $this->upload->do_upload('uploaded_file')) {
        $error = array('error' => $this->upload->display_errors());
        $file_error = 1;
        $flash_data['flashdata_msg'] = $error['error'];
        $flash_data['flashdata_type'] = "warning";
        $flash_data['flashdata_title'] = "Uploaded File Error";
        $flash_data['status'] = 2;
      }else {
        $file_data = $this->upload->data();
        $data2['photo'] = $file_data['file_name'];
        $this->resizeImage("labours",$file_data['file_name']);
      }
    }
    if (isset($_FILES['uploaded_file_2']) && $_FILES['uploaded_file_2']["size"] > 0) {
      //      File Upload
      $config2['upload_path']   = 'uploads/labours/';
      $config2['allowed_types'] = 'jpg|jpeg|png|pdf';
      $config['max_size']      = 1000;
      $config2['overwrite']      = FALSE;
      $config2['encrypt_name']    = TRUE;
      $this->load->library('upload', $config2,'uploaded_file_2');
      $this->uploaded_file_2->initialize($config2);
      $upload_uploaded_file_2 = $this->uploaded_file_2->do_upload('uploaded_file_2');
      $file_data2 = $this->uploaded_file_2->data();
      $data2['file_attachment'] = $file_data2['file_name'];
    }
    if($file_error==0){
      if($count==0) {
        $result2 = $this->Labour->create_labour($data2);
        $flash_data['status'] = $result2['status'];
        if ($result2['status'] == 1) {
          $member_duplication=0;
          // Add Team Members
          $labour_array=$newArraylabour=array();
          if($this->input->post('labour')){
            $labour_array = $this->input->post('labour');
          }
          $labour_array_length = sizeof($labour_array);
          //      Convert to New Formatted Array
          foreach (array_keys($labour_array) as $fieldKey) {
            foreach ($labour_array[$fieldKey] as $key=>$value) {
              $newArraylabour[$key][$fieldKey] = $value;
            }
          }
          foreach ($newArraylabour as $row) {
            $data3['group_position'] = 0;//Team Member
            $data3['labour_name'] = $row['name'];
            $count = $this->Labour->select_labours("",array("labour_name"=>$data3['labour_name'] ))->num_rows();
            $data3['labour_contact'] = $row['phone'];
            $data3['work_type'] = $row['work_type'];
            $data3['daily_wage'] = $row['daily_wage'];
            $data3['opening_balance'] = $row['op_balance'];
            if($count==0){
              $result3 = $this->Labour->create_labour($data3);
            }else{
              $member_duplication++;
            }
          }

          $flash_data['flashdata_msg'] = 'Labour Group Added Successfully!.';
          if($member_duplication>0){
            $flash_data['flashdata_msg'].="Some Members Not Added Because of Name Duplication!!";
          }
          $flash_data['message'] = $flash_data['flashdata_msg'];
          $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['message'] = '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.. Team Head Name is Already Exist in Labour Database!';
        $flash_data['message'] = 'Sorry.. Team Head Name is Already Exist in Labour Database!';
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Duplication !!';
      }
    }
    $this->session->set_flashdata($flash_data);
    redirect(base_url(). 'labours','refresh');
  }
  public function resizeImage($directory,$filename)
  {
    $source_path = FCPATH.'/uploads/'.$directory."/". $filename;
    $target_path = FCPATH.'/uploads/'.$directory."/";
    $config_manip = array(
      'image_library' => 'gd2',
      'source_image' => $source_path,
      'new_image' => $target_path,
      'maintain_ratio' => TRUE,
      // 'quality' => '60%',
      'width' => 150,
      'height' => 200,
    );

    $this->load->library('image_lib', $config_manip);
    if (!$this->image_lib->resize()) {
      echo $this->image_lib->display_errors();
    }
    $this->image_lib->clear();
  }
  public function update()
  {
    $data2['labour_id'] = $this->security->xss_clean($this->input->post('labour_id'));
    $data2['labour_name'] = $this->security->xss_clean($this->input->post('name'));
    // $data2['labour_type'] = $this->security->xss_clean($this->input->post('labour_type_edit'));
    $data2['fixed_wage'] = $this->security->xss_clean($this->input->post('wage_fixed_edit'));
    $data2['labour_contact'] = $this->security->xss_clean($this->input->post('contact_no'));
    $data2['work_type'] = $this->security->xss_clean($this->input->post('work_type'));
    $data2['daily_wage'] = $this->security->xss_clean($this->input->post('daily_wage'));
    $data2['active_status'] = $this->security->xss_clean($this->input->post('active_status_edit'));
    $data2['overtime_rate_per_hr'] = $this->security->xss_clean($this->input->post('overtime_rate'));
    if($data2['fixed_wage']==0){
      $data2['daily_wage'] = 0;
    }
    $data2['ta_per_day'] = $this->security->xss_clean($this->input->post('ta_amount'));
    $data2['opening_balance'] = $this->security->xss_clean($this->input->post('op_balance'));
    $data2['address'] = $this->security->xss_clean($this->input->post('address'));
    $data2['aadhar_no'] = $this->security->xss_clean($this->input->post('aadhar_no'));
    $data2['labour_contact_2'] = $this->security->xss_clean($this->input->post('contact_no_2'));
    $data2['updated_date'] = date('Y-m-d H:i:s');
    $data2['updated_by'] = $this->session->userdata('user_id');
    $file_error = 0;
    if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
      //      File Upload
      $config['upload_path']   = 'uploads/labours/';
      $config['allowed_types'] = 'jpg|jpeg|png';
      $config['max_size']      = 3000;
      $config['encrypt_name']    = TRUE;
      $this->load->library('upload', $config);
      if ( ! $this->upload->do_upload('uploaded_file')) {
        $error = array('error' => $this->upload->display_errors());
        $file_error = 1;
        $flash_data['flashdata_msg'] = $error['error'];
        $flash_data['flashdata_type'] = "warning";
        $flash_data['flashdata_title'] = "Uploaded File Error";
        $flash_data['status'] = 2;
      }else {
        $file_data = $this->upload->data();
        $data2['photo'] = $file_data['file_name'];
        $this->resizeImage("labours",$file_data['file_name']);
      }
    }
    if (isset($_FILES['uploaded_file_2']) && $_FILES['uploaded_file_2']["size"] > 0) {
      //      File Upload
      $config2['upload_path']   = 'uploads/labours/';
      $config2['allowed_types'] = 'jpg|jpeg|png|pdf';
      $config['max_size']      = 1000;
      $config2['overwrite']      = FALSE;
      $config2['encrypt_name']    = TRUE;
      $this->load->library('upload', $config2,'uploaded_file_2');
      $this->uploaded_file_2->initialize($config2);
      $upload_uploaded_file_2 = $this->uploaded_file_2->do_upload('uploaded_file_2');
      $file_data2 = $this->uploaded_file_2->data();
      $data2['file_attachment'] = $file_data2['file_name'];
    }
    if($file_error==0){
      $count = $this->Labour->select_labours("",array("labour_id !="=>$data2['labour_id'],"labour_name"=>$data2['labour_name']))->num_rows();
      if($count==0) {
        $result2 = $this->Labour->update_labour($data2);
        $flash_data['status'] = $result2;
        if ($result2 == 1) {
          $flash_data['flashdata_msg'] = 'Labour Details Updated Successfully!.';
          $flash_data['flashdata_type'] = 'success';
          $flash_data['alert_type'] = 'success';
          $flash_data['flashdata_title'] = 'Success !';

          if($data2['fixed_wage']==1 && $this->input->post('change_basic_wage_previous') && $this->input->post('change_basic_wage_previous')==1 && $this->input->post('labour_wage_edit_from_date') && $this->input->post('labour_wage_edit_from_date')!=''){
            // Update Wage in Wage Slip From Date
            $wage_from_date = date('Y-m-d',strtotime($this->input->post('labour_wage_edit_from_date')));
            $wage_slip_where['lw.labour_id'] = $data2['labour_id'];
            $wage_slip_where["STR_TO_DATE(lw.work_date,'%Y-%m-%d') >="]= $wage_from_date;
            $wage_slips = $this->Labour_wages->select_labour_wages("lw.*",$wage_slip_where,"","","","","",'all')->result();
            foreach ($wage_slips as $key => $value) {
              $wage_slip_update['wage_id'] = $value->wage_id;
              $wage_slip_update['wage_per_day'] = $data2['daily_wage'];
              $wage_slip_update['overtime_wage'] = $value->overtime_wage;
              if($value->overtime_type=='hour'){
                $wage_slip_update['overtime_hourly_rate'] = $data2['overtime_rate_per_hr'];
                $wage_slip_update['overtime_wage'] = $wage_slip_update['overtime_hourly_rate']*$value->overtime_hours;
              }
              $wage_slip_update['total_wage'] = ($wage_slip_update['wage_per_day']*$value->work_days*$value->no_of_labours)+$wage_slip_update['overtime_wage']+$value->extra_wage+$value->ta_wage;
              $result3 = $this->Labour_wages->update_labour_wage($wage_slip_update);
            }
          }
        } 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.. Labour with Same Name Already Exist!';
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Duplication !!';
      }
    }
    echo(json_encode($flash_data));
  }
  public function select($type=""){
    $data = array();
    if(isset($_POST['labour_id']) && $_POST['labour_id']!=""){
      $data['labour_id'] = $_POST['labour_id'];
    }
    if(isset($_POST['work_type']) && $_POST['work_type']!="" && $_POST['work_type']!="all"){
      $data['l.work_type'] = $_POST['work_type'];
    }
    if(isset($_POST['labour_group']) && $_POST['labour_group']!=""){
      $data['labour_group'] = $_POST['labour_group'];
    }
    if($type=="member_payment" && $this->config->item('Labour_group_member_payment')==0){
      $this->db->where('(l.labour_type=0 or (l.labour_type=1 and group_position=1))');
    }
    if($this->config->item('Labour_projet_assigning')==1 && isset($_POST['work_id']) && $_POST['work_id']!='' && $_POST['work_id']!='all'){
      $work_id = $_POST['work_id'];
      if(isset($_POST['assign_type']) && $_POST['assign_type']!=""){
        // Not Assigned Labours
        $this->db->where("NOT FIND_IN_SET($work_id, l.assigned_projects)");
      }else{
        // Assigned Labours
        $this->db->where("FIND_IN_SET($work_id, l.assigned_projects)");
      }
    }
    $result	= $this->Labour->select_labours("",$data,array("l.labour_group",'asc'));
    if($result->num_rows()>0) {
      foreach ($result->result() as $row):
        $id[] = $row->labour_id;
        $name[] = $row->labour_name;
        $labour_type[] = $row->labour_type;
        $labour_group[] = $row->labour_group;
        $group_position[] = $row->group_position;
        $work_type[] = $row->type_name;
        $contact[]  = $row->labour_contact;
        $daily_wage[]  = $row->daily_wage;
        $overtime_rate_per_hr[]  = $row->overtime_rate_per_hr;
        $fixed_wage[]  = $row->fixed_wage;
        $ta_per_day[]  = $row->ta_per_day;
        $opening_balance  = $row->opening_balance;
        if($row->labour_type==0 || ($row->labour_type==1 && $row->group_position==1 && $this->config->item('Labour_group_member_payment')==0) || ($row->labour_type==1 && $this->config->item('Labour_group_member_payment')==1)){
          if($row->labour_type==1 && $row->group_position==1 && $this->config->item('Labour_group_member_payment')==0){
            $total_to_pay = $this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total_amount",array("l.labour_group"=>$row->labour_group))->row()->total_amount;
          }else{
            $total_to_pay = $this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total_amount",array("lw.labour_id"=>$row->labour_id))->row()->total_amount;
          }
          $payment_data['l.labour_id'] = $row->labour_id;
          $payment_data['ats.tr_type'] = 'labour_transaction';
          $payment_data['ats.reference_type'] = 'labour';
          $total_paid = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payment_data,'labour')->row()->total_amount;
          $current_balance[]  = round(($total_to_pay+$opening_balance-$total_paid),$this->config->item('Currency_amount_decimals_2'));
        }else{
          $current_balance[]  = 0;
        }
      endforeach;
      echo json_encode(array("count" => $result->num_rows(),"id" => $id,"labour_type" => $labour_type,"group_position" => $group_position,"name" => $name,"work_type" => $work_type,"contact" => $contact,"fixed_wage" => $fixed_wage,"daily_wage" => $daily_wage,"current_balance" => $current_balance,"labour_group" => $labour_group,"overtime_rate_per_hr"=>$overtime_rate_per_hr,"ta_per_day"=>$ta_per_day));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }
  public function select_details($type=''){
    $data=array();
    if(isset($_POST['labour_id']) && $_POST['labour_id']!=""){
      $data['labour_id'] = $_POST['labour_id'];
    }
    $result	= $this->Labour->select_labours("",$data);
    if($result->num_rows()==1) {
      $row = $result->row();

      $json_data['count'] = $result->num_rows();
      $json_data['id'] = $row->labour_id;
      $json_data['name'] = $row->labour_name;
      $json_data['labour_type'] = $row->labour_type;
      $json_data['labour_group'] = $row->labour_group;
      $json_data['group_position'] = $row->group_position;
      $json_data['work_type'] = $row->type_name;
      $json_data['contact']  = $row->labour_contact;
      $json_data['fixed_wage'] = $row->fixed_wage;
      $json_data['overtime_rate_per_hr'] = $row->overtime_rate_per_hr;
      $json_data['daily_wage'] = $row->daily_wage;
      $json_data['ta_amount'] = $row->ta_per_day;
      $json_data['opening_balance']  = $row->opening_balance;
      $json_data['total_work_days'] = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.work_days),0) as total",array("lw.labour_id"=>$row->labour_id))->row()->total,2);
      $json_data['total_work_days_2'] = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(CEILING(lw.work_days)),0) as total",array("lw.labour_id"=>$row->labour_id))->row()->total,2);
      $json_data['total_wage_earned'] = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total_amount",array("lw.labour_id"=>$row->labour_id))->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));
      $json_data['total_to_pay'] = $json_data['total_wage_earned'] + $json_data['opening_balance'];
      $payment_data['l.labour_id'] = $row->labour_id;
      $payment_data['ats.tr_type'] = 'labour_transaction';
      $payment_data['ats.reference_type'] = 'labour';
      $json_data['total_paid'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payment_data,'labour')->row()->total_amount;
      if($this->config->item('Labour_labour_insurance_fd')==1){
        $json_data['total_insurance_payable'] = $this->config->item('Labour_labour_insurance_amount')*$json_data['total_work_days_2'];
        $json_data['total_fd_payable'] = $this->config->item('Labour_labour_fd_amount')*$json_data['total_work_days_2'];
        $insurance_paid_where['l.labour_id'] = $fd_paid_where['l.labour_id'] = $row->labour_id;
        $insurance_paid_where['ats.reference_type'] = $fd_paid_where['ats.reference_type'] = 'labour';
        $insurance_paid_where['ats.tr_type'] = $fd_paid_where['ats.tr_type'] = 'labour_insurance_fd_transaction';
        $insurance_paid_where['ats.tr_other_data'] = 'insurance';
        $fd_paid_where['ats.tr_other_data'] = 'fd';
        $json_data['total_insurance_paid'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$insurance_paid_where,'labour_insurance_fd')->row()->total_amount;
        $json_data['total_fd_paid'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$fd_paid_where,'labour_insurance_fd')->row()->total_amount;
        $json_data['total_insurance_balance'] = $json_data['total_insurance_payable'] - $json_data['total_insurance_paid'];
        $json_data['total_fd_balance'] = $json_data['total_fd_payable'] - $json_data['total_fd_paid'];
      }
      $json_data['current_balance']  = round($json_data['total_to_pay']-$json_data['total_paid'],$this->config->item('Currency_amount_decimals_2'));
      // Group Details For Team Leader
      if($row->labour_type==1 && $row->group_position==1){
        $json_data['total_members'] = $this->Labour->select_labours_2("l.labour_id",array("l.labour_group"=>$row->labour_group))->num_rows();
        $json_data['opening_balance_group'] = $this->Labour->select_labours_2("COALESCE(SUM(l.opening_balance),0) as total",array("l.labour_group"=>$row->labour_group))->row()->total;
        $json_data['total_work_days_group'] = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.work_days),0) as total",array("l.labour_group"=>$row->labour_group))->row()->total,2);
        $json_data['total_wage_earned_group'] = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total_amount",array("l.labour_group"=>$row->labour_group))->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));
        $json_data['total_to_pay_group'] = $json_data['total_wage_earned_group'] + $json_data['opening_balance_group'];

        $payment_data_2['l.labour_group'] = $row->labour_group;
        $payment_data_2['ats.tr_type'] = 'labour_transaction';
        $payment_data_2['ats.reference_type'] = 'labour';
        $json_data['total_paid_group'] = round($this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payment_data_2,'labour')->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));
        $json_data['current_balance']  = $json_data['current_balance_group']  = round($json_data['total_to_pay_group']-$json_data['total_paid_group'],$this->config->item('Currency_amount_decimals_2'));
      }

      if($type=='summary'){
        $json_data['opening_balance'] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($json_data['opening_balance'],$this->config->item('Currency_currency_shortname'));
        $json_data['total_wage_earned'] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($json_data['total_wage_earned'],$this->config->item('Currency_currency_shortname'));
        $json_data['total_to_pay'] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($json_data['total_to_pay'],$this->config->item('Currency_currency_shortname'));
        $json_data['total_paid'] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($json_data['total_paid'],$this->config->item('Currency_currency_shortname'));
        $json_data['current_balance'] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($json_data['current_balance'],$this->config->item('Currency_currency_shortname'));
      }

      echo json_encode($json_data);
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }
  public function select_group_details($type=''){
    $data=array();
    if(isset($_POST['labour_group_head']) && $_POST['labour_group_head']!=""){
      $data['l.labour_group'] = $this->Labour->select_labours("l.labour_group",array("l.labour_id"=>$_POST['labour_group_head']))->row()->labour_group;
      $payment_data['l.labour_group'] = $data['l.labour_group'];
    }
    $json_data['total_labours'] = $this->Labour->select_labours("labour_id",$data)->num_rows();
    $json_data['opening_balance'] = $this->Labour->select_labours("COALESCE(SUM(l.opening_balance),0) as total",$data)->row()->total;
    $json_data['total_labours_worked'] = $this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.no_of_labours),0) as total",$data)->row()->total;
    $json_data['total_work_days'] = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.work_days),0) as total",$data)->row()->total,2);
    $json_data['total_wage_earned'] = $this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total_amount",$data)->row()->total_amount;
    $json_data['total_to_pay'] = $json_data['total_wage_earned'] + $json_data['opening_balance'];
    $payment_data['ats.tr_type'] = 'labour_transaction';
    $payment_data['ats.reference_type'] = 'labour';
    $json_data['total_paid'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payment_data,'labour')->row()->total_amount;
    $json_data['current_balance']  = $json_data['total_to_pay']-$json_data['total_paid'];
    $json_data['count'] = 1;

    if($type=='summary'){
      $json_data['opening_balance'] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($json_data['opening_balance'],$this->config->item('Currency_currency_shortname'));
      $json_data['total_wage_earned'] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($json_data['total_wage_earned'],$this->config->item('Currency_currency_shortname'));
      $json_data['total_to_pay'] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($json_data['total_to_pay'],$this->config->item('Currency_currency_shortname'));
      $json_data['total_paid'] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($json_data['total_paid'],$this->config->item('Currency_currency_shortname'));
      $json_data['current_balance'] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($json_data['current_balance'],$this->config->item('Currency_currency_shortname'));
    }

    echo json_encode($json_data);

  }
  public function delete()
  {
    $data2['labour_id'] = $this->security->xss_clean($this->input->post('labour_id'));
    $data2['delete_status'] = 1;

    $result2 = $this->Labour->update_labour($data2);
    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['flashdata_msg'] = 'Labour Profile 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 !!';
    }

    echo(json_encode($flash_data));
  }

  public function create_attendance()
  {

    $data2['date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('work_date'))));
    $data2['project_id'] = $this->security->xss_clean($this->input->post('work'));
    $data2['created_date'] = date('Y-m-d H:i:s');
    $data2['created_by'] = $this->session->userdata('user_id');

    $attendance_duplication=$attendance_success=$transaction_success=0;
    //      Add Team Members
    $attendance_array=$newArraywageslip=array();
    if($this->input->post('attendance')){
      $attendance_array = $this->input->post('attendance');
    }
    $attendance_array_length = sizeof($attendance_array);
    //      Convert to New Formatted Array
    foreach (array_keys($attendance_array) as $fieldKey) {
      foreach ($attendance_array[$fieldKey] as $key=>$value) {
        $newArrayattendance[$key][$fieldKey] = $value;
      }
    }
    foreach ($newArrayattendance as $row) {
      $data3 = array();
      $status = 0;
      $data3['la.date'] = $data2['date'];
      $data2['labour_id'] = $data3['la.labour_id'] = $row['labour_id'];
      if(isset($row['attendance_status']) && $row['attendance_status']=='on'){
        // $data3['la.project_id'] = $data2['project_id'];
        $count = $this->Labour->select_labour_attendance("",$data3)->num_rows();
        if($row['start_time']!=''){
          $data2['start_time'] = date('H:i:s',strtotime($row['start_time']));
        }
        if($row['end_time']!=''){
          $data2['end_time'] = date('H:i:s',strtotime($row['end_time']));
        }

        if($count==0) {
          $result2 = $this->Labour->create_labour_attendance($data2);
          $status = $result2['status'];
          if ($result2['status'] == 1) {
            $attendance_success++;
          }
        }else{
          $attendance_duplication++;
        }
      }else{
        $status = 1;
      }
    }

    if ($attendance_success>0) {
      $flash_data['flashdata_msg'] = $attendance_success.' Labour Attendance Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      if($attendance_duplication>0){
        $flash_data['flashdata_msg'] .= $attendance_duplication.' Labour Attendance Not Added Because of Attendance on Same Date Already Exist!';
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Success, Duplications Found!';
      }
    }else{
      if($attendance_duplication>0){
        $flash_data['flashdata_msg'] = $attendance_duplication.' Labour Attendance Not Added Because of Attendance on Same Date Already Exist!';
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Success, Duplications Found!';
      }else{
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['message'] = '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'];

    $this->session->set_flashdata($flash_data);
    redirect(base_url(). 'labours/attendance','refresh');
  }
  public function update_attendance()
  {
    $data2['attendance_id'] = $data3['la.attendance_id !='] = $this->security->xss_clean($this->input->post('attendance_id'));
    $data2['date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('work_date'))));
    $data2['project_id'] = $this->security->xss_clean($this->input->post('work'));

    $data3['la.date'] = $data2['date'];
    $data2['labour_id'] = $data3['la.labour_id'] = $this->security->xss_clean($this->input->post('labour'));
    $count = $this->Labour->select_labour_attendance("",$data3)->num_rows();
    if($this->input->post('start_time')!=''){
      $data2['start_time'] = date('H:i:s',strtotime($this->input->post('start_time')));
    }else{
      $data2['start_time'] = '00:00:00';
    }
    if($this->input->post('end_time')!=''){
      $data2['end_time'] = date('H:i:s',strtotime($this->input->post('end_time')));
    }else{
      $data2['end_time'] = '00:00:00';
    }
    if($count==0) {
      $result2 = $this->Labour->update_labour_attendance($data2);
      $flash_data['status'] = $result2;
      if($result2==1){
        $flash_data['flashdata_msg'] = ' Labour Attendance 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['message'] = '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'] = 'Labour Attendance Not Added Because of Attendance on Same Date Already Exist for Selected Labour!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Success, Duplications Found!';
      $flash_data['status'] = 2;
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function delete_attendance()
  {
    $data2['attendance_id'] = $this->security->xss_clean($this->input->post('attendance_id'));
    $data2['delete_status'] = 1;
    $result2 = $this->Labour->update_labour_attendance($data2);
    $flash_data['status'] = $result2;
    if($result2==1){
      $flash_data['flashdata_msg'] = ' Labour Attendance 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['message'] = '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_labour_attendance($list_type=''){

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

    $data=array();
    if(isset($_POST['labour']) && $_POST['labour']!='' && $_POST['labour']!='all'){
      $data['l.labour_id'] = $_POST['labour'];
    }

    if(isset($_POST['work_type']) && $_POST['work_type']!='' && $_POST['work_type']!='all'){
      $data['l.work_type'] = $_POST['work_type'];
    }
    if(isset($_POST['labour_group_head']) && $_POST['labour_group_head']!='' && $_POST['labour_group_head']!='all'){
      $data['l.labour_group'] = $this->Labour->select_labours("l.labour_group",array("l.labour_id"=>$_POST['labour_group_head']))->row()->labour_group;
    }

    //profile filters

    if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
      $start_date=date('Y-m-d', strtotime($_POST['start_date']));
      $this->db->where("la.date >=",$start_date);
      $this->db->where("la.date !=",'0000-00-00');
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!='' && $_POST['end_date']!='all'){
      $end_date=date('Y-m-d', strtotime($_POST['end_date']));
      $this->db->where("la.date <=",$end_date);
      $this->db->where("la.date !=",'0000-00-00');
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['la.project_id'] = $_POST['work'];
    }

    if($this->config->item('user_data_access_view_all')!=1){
      $data['la.created_by'] = $this->session->userdata('user_id');
    }

    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['la.created_by'] = $_POST['user_id'];
    }

    $btn_delete=$btn_edit='';
    $previous_labour_group=0;
    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(la.date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(la.date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['la.project_id'] = $_POST['work'];
    }
    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    $result	= $this->Labour->select_labour_attendance("la.*,wt.type_name,l.labour_group,l.labour_name,wt.type_name,u.user_alias,wc.work_name",$data,"","","","","");
    foreach($result->result() as $row):
      $sl_no++;
      $btn_edit = $btn_delete = '';
      if($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="attendance_delete_btn" href="#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>';
        $btn_edit='<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>';
      }
      if($list_type!="nospace" && (($row->labour_group!=0 && $row->labour_group!=$previous_labour_group) || ($row->labour_group==0))){
        // Add a Blank Row
        $array[$j][]="";
        $array[$j][]="";
        $array[$j][]="";
        $array[$j][]="";
        $array[$j][]="";
        $array[$j][]="";
        $array[$j][]="";
        $array[$j][]="";
        $array[$j][]="";
        $array[$j][]="";
        $j++;
      }
      $previous_labour_group = $row->labour_group;

      $array[$j][]=$row->attendance_id;
      $array[$j][]=$sl_no;
      $array[$j][]=date('d-m-Y',strtotime($row->date));
      $array[$j][]='<a href="'.base_url().'work/profile/'.$row->project_id.'">'.$row->work_name.'</a>';
      $array[$j][]='<a href="' . base_url() . 'labours/profile/' . $row->labour_id . '">' . $row->labour_name . '</a>';
      if($row->start_time!='00-00-00'){
        $array[$j][]=date('h:i A',strtotime($row->start_time));
      }else{
        $array[$j][]='';
      }
      if($row->end_time!='00-00-00'){
        $array[$j][]=date('h:i A',strtotime($row->end_time));
      }else{
        $array[$j][]='';
      }
      $array[$j][]=$btn_edit.$btn_delete;
      $array[$j][]=$row->labour_id;
      $array[$j][]=$row->project_id;



      $j++;
    endforeach;


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