<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Labour_wages 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->model('Bills_model', 'Bills');
    $this->load->library('Bills_management','bills_management');

    $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()
  {
    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['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'] = 'labour_wages_view';
    $this->load->view('Index', $this->page_data);
  }
  public function monthly_summary()
  {
    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['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'] = 'labour_monthly_summary';
    $this->load->view('Index', $this->page_data);
  }
  public function add_group()
  {
    $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("",array("labour_type"=>1,"labour_group !="=>0,"group_position"=>1))->result();

    $this->page_data['page_name'] = 'labour_wages_add_group';
    $this->load->view('Index', $this->page_data);
  }
  public function add_quick()
  {
    $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("",array("labour_type"=>1,"labour_group !="=>0,"group_position"=>1))->result();

    $this->page_data['page_name'] = 'labour_wages_add_quick';
    $this->load->view('Index', $this->page_data);
  }
  public function add_quick_payment()
  {
    $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("",array("labour_type"=>1,"labour_group !="=>0,"group_position"=>1))->result();

    $this->page_data['page_name'] = 'labour_payment_add_quick';
    $this->load->view('Index', $this->page_data);
  }
  public function select_labour_wages($page_data_type='',$list_type=''){

    $json_data=array();
    $j=$sl_no=0;
    $total_overtime_duration=$total_food_allowance=$total_work_days=$total_wage_per_day=$total_extra_wage=$total_ta_wage=$total_overtime_wage=$total_wage_amount=$total_no_of_labours=0;
    $data=$array=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;
    }
    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("lw.work_date >=",$start_date);
      $this->db->where("lw.work_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("lw.work_date <=",$end_date);
      $this->db->where("lw.work_date !=",'0000-00-00');
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['lw.work_id'] = $_POST['work'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $this->db->where_in('lw.work_id',explode(',',$_POST['work_ids']));
    }
    if(isset($_POST['stage_id']) && $_POST['stage_id']!='' && $_POST['stage_id']!='all'){
      $data['lw.project_stage_id'] = $_POST['stage_id'];
    }
    if($this->config->item('user_data_access_view_all')!=1){
      $data['lw.created_by'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['lw.created_by'] = $_POST['user_id'];
    }
    // $labours	= $this->Labour->select_labours("",$data,array("labour_group","desc"),array("group_position","desc"),"","","")->result();
    $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(lw.work_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(lw.work_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['lw.work_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)");
    }
    $entry_approval = 1;
    if($this->config->item('User_enable_data_entry_approval')==1){//webapp users approval
      $entry_approval = 'all';
    }
    if($page_data_type=='approval_entries'){
      $entry_approval = 'all';
      $data['u.user_role >'] =2;
      if(isset($_POST['approval_status']) && $_POST['approval_status']!='' && $_POST['approval_status']!='all'){
        $entry_approval = $_POST['approval_status'];
      }
    }

    $result	= $this->Labour_wages->select_labour_wages("lw.*,wt.type_name,l.labour_group,l.labour_name,wt.type_name,u.user_alias,wc.work_name,u.user_role as created_user_role_id",$data,"","","","","",$entry_approval);
    if($result->num_rows()>0){
      foreach($result->result() as $row):
        $sl_no++;
        $btn_edit = $btn_delete = '';
        if(($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_id')==$row->created_by) && ($this->config->item('User_enable_data_entry_approval')!=1 || $row->entry_approval_status!=1 || $this->session->userdata('user_role')=='admin')) {
          $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="labour_wage_delete_btn" href="#labour_wage_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="labour_wage_edit_btn" href="#labour_wage_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_approve = $entry_approval_status = '';
        if(($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')=='accounts_manager' && $row->created_user_role_id>2 && (($this->config->item('User_enable_data_entry_approval_2_level')==0 && $row->created_user_role_id != 16) || $this->config->item('User_enable_data_entry_approval_2_level')==1))) && $page_data_type=='approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval')==1){
          $btn_approve = '<a style="margin-left: 5px;margin-right: 5px" data-type="labour_wage" data-approval-status="'.$row->entry_approval_status.'" data-id="'.$row->wage_id.'" id="btn_data_entry_approval" href="#data_entry_approve_modal" data-toggle="modal" class="btn btn-sm btn-warning m-btn m-btn--icon  m-btn--pill m-btn--air">
          <i class="la la-check-circle"></i> / <i class="la la-times-circle"></i>
          </a>';
        }
        if(($page_data_type=='approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval')==1) || $this->config->item('User_enable_data_entry_approval')==1){
          if($row->entry_approval_status==1){
            $entry_approval_status="<br/><span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Approved</span>";
          }elseif($row->entry_approval_status==2){
            $entry_approval_status="<br/><span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> Rejected</span>";
          }else{
            $entry_approval_status="<br/><span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> Pending</span>";
          }
        }
        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][]="";
          $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++;
        }
        $previous_labour_group = $row->labour_group;

        $array[$j][]=$sl_no;
        $array[$j][]=$row->wage_id;
        $array[$j][]='<a href="' . base_url() . 'labours/profile/' . $row->labour_id . '">' . $row->labour_name . '</a>';
        $array[$j][]=$row->type_name;
        $array[$j][]=date('d-m-Y',strtotime($row->work_date));
        $array[$j][]=date('l',strtotime($row->work_date));
        $array[$j][]="<span class='m-badge m-badge--primary m-badge--wide'><i class='la la-calendar-check-o'></i> On Duty</span>";
        $array[$j][]='<a href="'.base_url().'work/profile/'.$row->work_id.'">'.$row->work_name.'</a>';
        $array[$j][]=$row->work_days;
        $array[$j][]=$row->no_of_labours;
        $array[$j][]=$row->wage_per_day;
        $array[$j][]=$row->overtime_hourly_rate;
        $array[$j][]=$row->overtime_hours;
        $array[$j][]=$row->overtime_wage;
        $array[$j][]=$row->extra_wage;
        $array[$j][]=$row->ta_wage;
        $array[$j][]=$row->food_allowance;
        $array[$j][]=$row->total_wage;
        $array[$j][]=$row->remarks;
        $array[$j][]=$row->user_alias.$entry_approval_status;
        if ($this->config->item('UI_hide_created_date_field')==0){
          $array[$j][]=date('d-m-Y',strtotime($row->created_date));
        }else{
          $array[$j][]='';
        }
        $array[$j][]=$btn_edit.$btn_delete.$btn_approve;
        $array[$j][]=$row->labour_id;
        $array[$j][]=$row->work_id;
        $array[$j][]=$row->overtime_hourly_rate;
        $array[$j][] = $row->entry_approval_status;

        $total_work_days+=$row->work_days;
        $total_wage_per_day+=$row->wage_per_day;
        $total_overtime_wage+=$row->overtime_wage;
        $total_extra_wage+=$row->extra_wage;
        $total_ta_wage+=$row->ta_wage;
        $total_food_allowance+=$row->food_allowance;
        $total_wage_amount+=$row->total_wage;
        $total_no_of_labours+=$row->no_of_labours;
        $total_overtime_duration+=$row->overtime_hours;

        $j++;
      endforeach;
    }
    if(sizeof($array)>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]="<strong>".$total_work_days."</strong>";
      $array[$j][]="<strong>".$total_no_of_labours."</strong>";
      $array[$j][]="<strong>".$total_wage_per_day."</strong>";
      $array[$j][]='';
      $array[$j][]="<strong>".$total_overtime_duration."</strong>";
      $array[$j][]="<strong>".$total_overtime_wage."</strong>";
      $array[$j][]="<strong>".$total_extra_wage."</strong>";
      $array[$j][]="<strong>".$total_ta_wage."</strong>";
      $array[$j][]="<strong>".$total_food_allowance."</strong>";
      $array[$j][]="<strong>".$total_wage_amount."</strong>";
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
    }

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

    $json_data=array();
    $j=0;
    $total_work_days=$total_wage_per_day=$total_extra_wage=$total_overtime_wage=$total_wage_amount=$total_no_of_labours=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;
    }
    $labours	= $this->Labour->select_labours("",$data,array("labour_group","desc"),array("group_position","desc"),"","","")->result();
    $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]));
      // 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);

      $array=array();
      $sl_no=0;
      foreach ($date_period as $key => $value) {
        foreach($labours as $row2):
          $wage_data['lw.labour_id'] = $row2->labour_id;
          $wage_data['lw.work_date'] = $value->format('Y-m-d');
          if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
            $wage_data['lw.work_id'] = $_POST['work'];
          }
          $result	= $this->Labour_wages->select_labour_wages("lw.*,l.labour_name,wt.type_name,u.user_alias,wc.work_name",$wage_data,"","","","","");
          if($result->num_rows()>0){
            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="labour_wage_delete_btn" href="#labour_wage_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="labour_wage_edit_btn" href="#labour_wage_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" && (($row2->labour_group!=0 && $row2->labour_group!=$previous_labour_group) || ($row2->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][]="";
                $array[$j][]="";
                $array[$j][]="";
                $array[$j][]="";
                $array[$j][]="";
                $array[$j][]="";
                $array[$j][]="";
                $array[$j][]="";
                $array[$j][]="";
                $array[$j][]="";
                $array[$j][]="";
                $j++;
              }
              $previous_labour_group = $row2->labour_group;

              $array[$j][]=$sl_no;
              $array[$j][]=$row->wage_id;
              $array[$j][]='<a href="' . base_url() . 'labours/profile/' . $row2->labour_id . '">' . $row2->labour_name . '</a>';
              $array[$j][]=$row2->type_name;
              $array[$j][]=date('d-m-Y',strtotime($value->format('Y-m-d')));
              $array[$j][]=date('l',strtotime($value->format('Y-m-d')));
              $array[$j][]="<span class='m-badge m-badge--primary m-badge--wide'><i class='la la-calendar-check-o'></i> On Duty</span>";
              $array[$j][]='<a href="'.base_url().'work/profile/'.$row->work_id.'">'.$row->work_name.'</a>';
              $array[$j][]=$row->work_days;
              $array[$j][]=$row->no_of_labours;
              $array[$j][]=$row->wage_per_day;
              $array[$j][]=$row->overtime_wage;
              $array[$j][]=$row->extra_wage;
              $array[$j][]=$row->total_wage;
              $array[$j][]=$row->remarks;
              $array[$j][]=$row->user_alias;
              if ($this->config->item('UI_hide_created_date_field')==0){
                $array[$j][]=date('d-m-Y',strtotime($row->created_date));
              }else{
                $array[$j][]='';
              }
              $array[$j][]=$btn_edit.$btn_delete;
              $array[$j][]=$row->labour_id;
              $array[$j][]=$row->work_id;

              $total_work_days+=$row->work_days;
              $total_wage_per_day+=$row->wage_per_day;
              $total_overtime_wage+=$row->overtime_wage;
              $total_extra_wage+=$row->extra_wage;
              $total_wage_amount+=$row->total_wage;
              $total_no_of_labours+=$row->no_of_labours;

              $j++;
            endforeach;
          }
        endforeach;
      }
    }else{
      $sl_no=0;
      foreach($labours as $row2):
        $wage_data['lw.labour_id'] = $row2->labour_id;
        if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
          $wage_data['lw.work_id'] = $_POST['work'];
        }
        $result	= $this->Labour_wages->select_labour_wages("lw.*,l.labour_name,wt.type_name,u.user_alias,wc.work_name",$wage_data);
        foreach($result->result() as $row):
          $sl_no++;
          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="labour_wage_delete_btn" href="#labour_wage_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="labour_wage_edit_btn" href="#labour_wage_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" && (($row2->labour_group!=0 && $row2->labour_group!=$previous_labour_group) || ($row2->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][]="";
            $array[$j][]="";
            $array[$j][]="";
            $array[$j][]="";
            $array[$j][]="";
            $array[$j][]="";
            $array[$j][]="";
            $array[$j][]="";
            $array[$j][]="";
            $array[$j][]="";
            $array[$j][]="";
            $j++;
          }
          $previous_labour_group = $row2->labour_group;

          $array[$j][]=$sl_no;
          $array[$j][]=$row->wage_id;
          $array[$j][]='<a href="' . base_url() . 'labours/profile/' . $row->labour_id . '">' . $row->labour_name . '</a>';
          $array[$j][]=$row->type_name;
          $array[$j][]=date('d-m-Y',strtotime($row->work_date));
          $array[$j][]=date('l',strtotime($row->work_date));
          $array[$j][]="<span class='m-badge m-badge--primary m-badge--wide'><i class='la la-calendar-check-o'></i> On Duty</span>";
          $array[$j][]='<a href="'.base_url().'work/profile/'.$row->work_id.'">'.$row->work_name.'</a>';
          $array[$j][]=$row->work_days;
          $array[$j][]=$row->no_of_labours;
          $array[$j][]=$row->wage_per_day;
          $array[$j][]=$row->overtime_wage;
          $array[$j][]=$row->extra_wage;
          $array[$j][]=$row->total_wage;
          $array[$j][]=$row->remarks;
          $array[$j][]=$row->user_alias;
          if ($this->config->item('UI_hide_created_date_field')==0){
            $array[$j][]=date('d-m-Y',strtotime($row->created_date));
          }else{
            $array[$j][]='';
          }
          $array[$j][]=$btn_edit.$btn_delete;
          $array[$j][]=$row->labour_id;
          $array[$j][]=$row->work_id;

          $total_work_days+=$row->work_days;
          $total_wage_per_day+=$row->wage_per_day;
          $total_overtime_wage+=$row->overtime_wage;
          $total_extra_wage+=$row->extra_wage;
          $total_wage_amount+=$row->total_wage;
          $total_no_of_labours+=$row->no_of_labours;

          $j++;
        endforeach;
      endforeach;
    }


    $array[$j][]='';
    $array[$j][]='';
    $array[$j][]='';
    $array[$j][]='';
    $array[$j][] = '';
    $array[$j][] = '';
    $array[$j][]='';
    $array[$j][]="<strong>Total</strong>";
    $array[$j][]="<strong>".$total_work_days."</strong>";
    $array[$j][]="<strong>".$total_no_of_labours."</strong>";
    $array[$j][]="<strong>".$total_wage_per_day."</strong>";
    $array[$j][]="<strong>".$total_overtime_wage."</strong>";
    $array[$j][]="<strong>".$total_extra_wage."</strong>";
    $array[$j][]="<strong>".$total_wage_amount."</strong>";
    $array[$j][]='';
    $array[$j][]='';
    $array[$j][]='';
    $array[$j][]='';
    $array[$j][]='';
    $array[$j][]='';


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

    $json_data=array();
    $j=$sl_no=0;
    $total_overtime_hours = $total_overtime_wage = $total_work_days=$total_wage_per_day=$total_extra_wage=$total_overtime_wage=$total_wage_amount=$total_no_of_labours=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;
    }
    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("lw.work_date >=",$start_date);
      $this->db->where("lw.work_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("lw.work_date <=",$end_date);
      $this->db->where("lw.work_date !=",'0000-00-00');
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['lw.work_id'] = $_POST['work'];
    }
    if($this->config->item('user_data_access_view_all')!=1){
      $data['lw.created_by'] = $this->session->userdata('user_id');
    }
    // $labours	= $this->Labour->select_labours("",$data,array("labour_group","desc"),array("group_position","desc"),"","","")->result();
    $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(lw.work_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(lw.work_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['lw.work_id'] = $_POST['work'];
    }
    $result	= $this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.work_days),0) as total_days,COALESCE(SUM(lw.overtime_hours),0) as total_overtime_hours,COALESCE(SUM(lw.overtime_wage),0) as total_overtime_wage,COALESCE(SUM(lw.work_days),0) as total_days,COALESCE(SUM(lw.no_of_labours),0) as total_labours,COALESCE(SUM(lw.total_wage),0) as grand_total_wage,l.labour_name,lw.labour_id,wc.work_name,lw.work_id",$data,"","","lw.labour_id,lw.work_id","","");
    if($result->num_rows()>0){
      foreach($result->result() as $row):
        $sl_no++;

        $array[$j][]=$sl_no;
        $array[$j][]=$row->work_name;
        $array[$j][]='<strong><a href="'.base_url().'work/profile/'.$row->work_id.'">'.$row->work_name.'</a></strong>';
        $array[$j][]='<a href="' . base_url() . 'labours/profile/' . $row->labour_id . '">' . $row->labour_name . '</a>';
        $array[$j][] = round($row->total_days,2);
        $array[$j][] = $row->total_labours;
        $array[$j][] = $row->total_overtime_hours;
        $array[$j][] = $row->total_overtime_wage;
        $array[$j][]= round($row->grand_total_wage,$this->config->item('Currency_amount_decimals_2'));
        $array[$j][]='';

        $total_work_days+=$row->total_days;
        $total_no_of_labours+=$row->total_labours;
        $total_wage_amount+=$row->grand_total_wage;
        $total_overtime_hours += $row->total_overtime_hours;
        $total_overtime_wage += $row->total_overtime_wage;

        $j++;
      endforeach;

      // Project Wise Total
      $result2	= $this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.no_of_labours),0) as total_labours,COALESCE(SUM(lw.work_days),0) as total_days,COALESCE(SUM(lw.overtime_hours),0) as total_overtime_hours,COALESCE(SUM(lw.overtime_wage),0) as total_overtime_wage,COALESCE(SUM(lw.total_wage),0) as grand_total_wage,wc.work_name,lw.work_id",$data,"","","lw.work_id","","");
      foreach($result2->result() as $row):
        $sl_no++;

        $array[$j][]='';
        $array[$j][]=$row->work_name;
        $array[$j][]='<strong><a href="'.base_url().'work/profile/'.$row->work_id.'">'.$row->work_name.'</a></strong>';
        $array[$j][]='<strong>Total</strong>';
        $array[$j][] ='<strong>'.round($row->total_days,2).'</strong>';
        $array[$j][] ='<strong>'.$row->total_labours.'</strong>';
        $array[$j][] ='<strong>'.$row->total_overtime_hours.'</strong>';
        $array[$j][] ='<strong>'.$row->total_overtime_wage.'</strong>';
        $array[$j][] ='<strong>'.round($row->grand_total_wage,$this->config->item('Currency_amount_decimals_2')).'</strong>';
        $array[$j][]='';

        $j++;
      endforeach;
    }

    $array[$j][]='';
    $array[$j][]="<span style='color:#e0e0e0 !important'>zzz</span> Summary";
    $array[$j][]="Summary";
    $array[$j][]="<strong>Total</strong>";
    $array[$j][]="<strong>".round($total_work_days,2)."</strong>";
    $array[$j][]="<strong>".$total_no_of_labours."</strong>";
    $array[$j][]="<strong>".$total_overtime_hours."</strong>";
    $array[$j][]="<strong>".$total_overtime_wage."</strong>";
    $array[$j][]="<strong>".round($total_wage_amount,$this->config->item('Currency_amount_decimals_2'))."</strong>";
    $array[$j][]='';


    $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
  }

  public function create()
  {
    $data2['labour_id'] = $data3['lw.labour_id'] = $this->security->xss_clean($this->input->post('labour'));
    $data2['work_date'] = $data3['lw.work_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('work_date'))));
    $data2['work_id'] = $this->security->xss_clean($this->input->post('work'));
    if($this->config->item('Labour_wage_slip_allow_multiple_day_by_site')==1){
      $data3['lw.work_id'] = $data2['work_id'];
    }
    $data2['project_stage_id'] = $this->projects_management->get_project_stage_id($data2['work_id']);

    $count = $this->Labour_wages->select_labour_wages("",$data3)->num_rows();
    $data2['work_days'] = $this->security->xss_clean($this->input->post('no_of_days'));
    $data2['no_of_labours'] = $this->security->xss_clean($this->input->post('no_of_labours'));
    if($data2['no_of_labours'] == 0 || $data2['no_of_labours'] == '' ){
      $data2['no_of_labours']=1;
    }
    $data2['wage_per_day'] = $this->security->xss_clean($this->input->post('wage_per_day'));
    $data2['overtime_type'] = $this->config->item('Labour_wage_overtime_calculation');
    if($data2['overtime_type']=='hour'){
      $data2['overtime_hours'] = $this->security->xss_clean($this->input->post('overtime_duration'));
      $data2['overtime_hourly_rate'] = $this->security->xss_clean($this->input->post('overtime_rate'));
    }
    $data2['overtime_wage'] = $this->security->xss_clean($this->input->post('overtime_wage'));
    $data2['extra_wage'] = $this->security->xss_clean($this->input->post('extra_wage'));
    $data2['ta_wage'] = $this->security->xss_clean($this->input->post('ta_wage'));
    if($this->input->post('food_allowance')){
      $data2['food_allowance'] = $this->security->xss_clean($this->input->post('food_allowance'));
    }
    $data2['total_wage'] = $this->security->xss_clean($this->input->post('total_wage'));
    $data2['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data2['created_date'] = date('Y-m-d H:i:s');
    $data2['created_by'] = $this->session->userdata('user_id');
    if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
      $data2['entry_approval_status'] = 0;
    }
    if($count==0) {
      $result2 = $this->Labour_wages->create_labour_wage($data2);
      $flash_data['status'] = $result2['status'];
      if ($result2['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Labour Wage Slip Added Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';

        // Insert IF Payment Exist
        if($this->security->xss_clean($this->input->post('paid_amount'))>0){
          $transaction_data['reference_id'] = $this->security->xss_clean($this->input->post('labour'));
          $transaction_data['reference_type'] = "labour";
          $transaction_data['tr_type'] = "labour_transaction";
          $transaction_data['tr_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('paid_date'))));
          $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
          $transaction_data['tr_credit_acc'] = 7;//labour wage payments
          $transaction_data['tr_description'] = "Labour Wage Transaction";
          $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('paid_amount'));
          $transaction_data['tr_mode'] = $this->security->xss_clean($this->input->post('payment_mode'));
          $transaction_data['tr_reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
          if($this->input->post('reference_date')!=''){
            $transaction_data['tr_reference_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('reference_date'))));
          }
          $transaction_data['tr_remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
          $transaction_data['created_date'] = date('Y-m-d H:i:s');
          $transaction_data['created_by'] = $this->session->userdata('user_id');
          if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
            $transaction_data['tr_entry_approval_status'] = 0;
          }
          $transaction_result =  $this->Account->create_account_transaction($transaction_data);
          $flash_data['flashdata_msg'] = 'Labour Wage Slip & Transaction Added Successfully!.';
        }

      } 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;
      if($this->config->item('Labour_wage_slip_allow_multiple_day_by_site')==1){
        $flash_data['flashdata_msg'] = 'Sorry.. Labour Wage Slip on Same Date & Project Already Exist!';
      }else{
        $flash_data['flashdata_msg'] = 'Sorry.. Labour Wage Slip on Same Date 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 create_group()
  {

    $data2['work_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('work_date'))));
    $data2['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data2['created_date'] = date('Y-m-d H:i:s');
    $data2['created_by'] = $this->session->userdata('user_id');
    if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
      $data2['entry_approval_status'] = 0;
    }
    $transaction_message="";
    $transaction_data['reference_type'] = "labour";
    $transaction_data['tr_type'] = "labour_transaction";
    $transaction_data['tr_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('paid_date'))));
    $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
    $transaction_data['tr_credit_acc'] = 7;//labour wage payments
    $transaction_data['tr_description'] = "Labour Wage Transaction";
    $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');
    if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
      $transaction_data['tr_entry_approval_status'] = 0;
    }
    $transaction_data['created_by'] = $this->session->userdata('user_id');

    $wage_duplication=$wage_success=$transaction_success=0;
    //      Add Team Members
    $wage_slip_array=$newArraywageslip=array();
    if($this->input->post('wage_slip')){
      $wage_slip_array = $this->input->post('wage_slip');
    }
    $wage_slip_array_length = sizeof($wage_slip_array);
    //      Convert to New Formatted Array
    foreach (array_keys($wage_slip_array) as $fieldKey) {
      foreach ($wage_slip_array[$fieldKey] as $key=>$value) {
        $newArraywageslip[$key][$fieldKey] = $value;
      }
    }
    foreach ($newArraywageslip as $row) {
      $data3 = array();
      $status = 0;
      $data3['lw.work_date'] = $data2['work_date'];
      $data2['labour_id'] = $data3['lw.labour_id'] = $row['labour_id'];
      if(isset($row['work_status']) && $row['work_status']=='on'){
        $data2['work_id'] = $row['work'];
        if($this->config->item('Labour_wage_slip_allow_multiple_day_by_site')==1){
          $data3['lw.work_id'] = $data2['work_id'];
        }
        $count = $this->Labour_wages->select_labour_wages("",$data3)->num_rows();
        $data2['work_days'] = $row['no_of_days'];
        $data2['no_of_labours'] = $row['no_of_labours'];
        $data2['wage_per_day'] = $row['basic_wage'];
        $data2['overtime_wage'] = $row['overtime'];
        $data2['extra_wage'] = $row['extra'];
        $data2['ta_wage'] = $row['ta'];
        $data2['total_wage'] = $row['total_wage'];
        if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
          $data2['entry_approval_status'] = 0;
        }
        if($count==0) {
          $result2 = $this->Labour_wages->create_labour_wage($data2);
          $status = $result2['status'];
          if ($result2['status'] == 1) {
            $wage_success++;
          }
        }else{
          $wage_duplication++;
        }
      }else{
        $status = 1;
      }
      //          Insert Payment
      if($status==1 && $row['total_paid']>0){

        $transaction_data['tr_amount'] = $row['total_paid'];
        $transaction_data['reference_id'] = $row['labour_id'];
        $transaction_result =  $this->Account->create_account_transaction($transaction_data);
        if($transaction_result['status']==1){
          $transaction_success++;
        }

      }

    }

    if ($wage_success>0) {
      if($transaction_success>0){
        $transaction_message = 'And '.$transaction_success.' Transactions ';
      }
      $flash_data['flashdata_msg'] = $wage_success.' Labour Wage Slip '.$transaction_message.' Added Successfully!.';
      if($wage_duplication>0){
        if($this->config->item('Labour_wage_slip_allow_multiple_day_by_site')==1){
          $flash_data['flashdata_msg'] .= $wage_duplication.' Labour Wage Slip Not Added Because of Wage Slip on Same Date & Project Already Exist!';
        }else{
          $flash_data['flashdata_msg'] .= $wage_duplication.' Labour Wage Slip Not Added Because of Wage Slip 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_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      }
      $flash_data['message'] = $flash_data['flashdata_msg'];

    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred / Wage Slip on Same Date Already Exist. Please Try Again!';
      $flash_data['message'] = 'Sorry.. There Have been Some Error Occurred / Wage Slip on Same Date Already Exist. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }

    $this->session->set_flashdata($flash_data);
    redirect(base_url(). 'labour_wages','refresh');
  }
  public function create_quick()
  {

    $data2['work_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('work_date'))));
    if($this->input->post('remarks')){
      $data2['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    }
    $data2['work_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');
    if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
      $data2['entry_approval_status'] = 0;
    }
    $wage_duplication=$wage_success=$transaction_success=0;
    //      Add Team Members
    $wage_slip_array=$newArraywageslip=array();
    if($this->input->post('wage_slip')){
      $wage_slip_array = $this->input->post('wage_slip');
    }
    $wage_slip_array_length = sizeof($wage_slip_array);
    //      Convert to New Formatted Array
    foreach (array_keys($wage_slip_array) as $fieldKey) {
      foreach ($wage_slip_array[$fieldKey] as $key=>$value) {
        $newArraywageslip[$key][$fieldKey] = $value;
      }
    }
    foreach ($newArraywageslip as $row) {
      $data3 = array();
      $status = 0;
      if(isset($row['labour_id'])){
        $data3['lw.work_date'] = $data2['work_date'];
        $data2['labour_id'] = $data3['lw.labour_id'] = $row['labour_id'];
        if(isset($row['work_status']) && $row['work_status']=='on'){
          $data2['work_id'] = $data2['work_id'];
          if($this->config->item('Labour_wage_slip_allow_multiple_day_by_site')==1){
            $data3['lw.work_id'] = $data2['work_id'];
          }
          $count = $this->Labour_wages->select_labour_wages("",$data3)->num_rows();
          $data2['work_days'] = $row['no_of_days'];
          $data2['no_of_labours'] = 1;
          $data2['wage_per_day'] = $row['basic_wage'];
          $data2['overtime_type'] = $this->config->item('Labour_wage_overtime_calculation');
          if($data2['overtime_type']=='hour'){
            $data2['overtime_hours'] = $row['overtime_duration'];
            $data2['overtime_hourly_rate'] = $row['overtime_rate'];
          }
          $data2['overtime_wage'] = $row['overtime'];
          $data2['extra_wage'] = $row['extra_wage'];
          $data2['ta_wage'] = $row['ta'];
          $data2['food_allowance'] = $row['food_allowance'];
          $data2['total_wage'] = $row['total_wage'];

          if($count==0) {
            $result2 = $this->Labour_wages->create_labour_wage($data2);
            $status = $result2['status'];
            if ($result2['status'] == 1) {
              $wage_success++;
            }
          }else{
            $wage_duplication++;
          }
        }else{
          $status = 1;
        }
      }
    }

    if ($wage_success>0) {
      $flash_data['flashdata_msg'] = $wage_success.' Labour Wage Slip Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      if($wage_duplication>0){
        if($this->config->item('Labour_wage_slip_allow_multiple_day_by_site')==1){
          $flash_data['flashdata_msg'] .= $wage_duplication.' Labour Wage Slip Not Added Because of Wage Slip on Same Date & Project Already Exist!';
        }else{
          $flash_data['flashdata_msg'] .= $wage_duplication.' Labour Wage Slip Not Added Because of Wage Slip on Same Date Already Exist!';
        }
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Success, Duplications Found!';
      }
    }else{
      if($wage_duplication>0){
        if($this->config->item('Labour_wage_slip_allow_multiple_day_by_site')==1){
          $flash_data['flashdata_msg'] .= $wage_duplication.' Labour Wage Slip Not Added Because of Wage Slip on Same Date & Project Already Exist!';
        }else{
          $flash_data['flashdata_msg'] .= $wage_duplication.' Labour Wage Slip Not Added Because of Wage Slip 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(). 'labour_wages','refresh');
  }
  public function create_quick_payment()
  {
    $tr_group_last_id = $this->Account->select_account_transaction("max(ats.tr_group_id) as max_tr_group_id");
    if($tr_group_last_id->num_rows()==1){
      $transaction_data['tr_group_id'] = ($tr_group_last_id->row()->max_tr_group_id)+1;
    }else{
      $transaction_data['tr_group_id'] = 1;
    }
    $transaction_data['reference_type'] = "labour";
    $transaction_data['tr_type'] = "labour_transaction";
    $transaction_data['tr_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('paid_date'))));
    $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
    $transaction_data['tr_credit_acc'] = 7;//labour wage payments
    $transaction_data['tr_description'] = "Labour Wage Transaction";
    $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;
    }


    $payment_array=$newArraypayment=array();
    if($this->input->post('payment_data')){
      $payment_array = $this->input->post('payment_data');
    }
    $payment_array_length = sizeof($payment_array);
    foreach (array_keys($payment_array) as $fieldKey) {
      foreach ($payment_array[$fieldKey] as $key=>$value) {
        $newArraypayment[$key][$fieldKey] = $value;
      }
    }
    $success = 0;
    foreach ($newArraypayment as $row) {
      $status = 0;
      if($row['paid_amount']>0 && isset($row['work_status']) && $row['work_status']=='on'){
        $transaction_data['reference_id'] = $row['labour_id'];
        $transaction_data['tr_amount'] = $row['paid_amount'];
        $transaction_result =  $this->Account->create_account_transaction($transaction_data);
        $status = $transaction_result['status'];
        if ($transaction_result['status'] == 1) {
          $success++;
        }
      }
    }

    if ($success>0) {
      $flash_data['status'] = 1;
      $flash_data['flashdata_msg'] = $success.' Labour Payment Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }else{
      $flash_data['status'] = 2;
      $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(). 'labour_wages','refresh');
  }
  public function update()
  {
    $data3['lw.labour_id'] = $this->security->xss_clean($this->input->post('labour'));
    $data2['wage_id'] =$data3['lw.wage_id !='] = $this->security->xss_clean($this->input->post('wage_id'));
    $data2['work_date'] = $data3['lw.work_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('work_date'))));
    $data2['work_id'] = $this->security->xss_clean($this->input->post('work'));
    if($this->config->item('Labour_wage_slip_allow_multiple_day_by_site')==1){
      $data3['lw.work_id'] = $data2['work_id'];
    }
    $count = $this->Labour_wages->select_labour_wages("",$data3)->num_rows();
    $data2['work_days'] = $this->security->xss_clean($this->input->post('no_of_days'));
    $data2['no_of_labours'] = $this->security->xss_clean($this->input->post('no_of_labours'));
    if($data2['no_of_labours'] == 0 || $data2['no_of_labours'] == '' ){
      $data2['no_of_labours']=1;
    }
    $data2['wage_per_day'] = $this->security->xss_clean($this->input->post('wage_per_day'));
    $data2['overtime_type'] = $this->config->item('Labour_wage_overtime_calculation');
    if($data2['overtime_type']=='hour'){
      $data2['overtime_hours'] = $this->security->xss_clean($this->input->post('overtime_duration'));
      $data2['overtime_hourly_rate'] = $this->security->xss_clean($this->input->post('overtime_rate'));
    }
    $data2['overtime_wage'] = $this->security->xss_clean($this->input->post('overtime_wage'));
    $data2['extra_wage'] = $this->security->xss_clean($this->input->post('extra_wage'));
    $data2['ta_wage'] = $this->security->xss_clean($this->input->post('ta_wage'));
    if($this->input->post('food_allowance')){
      $data2['food_allowance'] = $this->security->xss_clean($this->input->post('food_allowance'));
    }
    $data2['total_wage'] = $this->security->xss_clean($this->input->post('total_wage'));
    $data2['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data2['updated_date'] = date('Y-m-d H:i:s');
    $data2['updated_by'] = $this->session->userdata('user_id');
    if($count==0)
    {
      $result2 = $this->Labour_wages->update_labour_wage($data2);
      $flash_data['status'] = $result2;
      if ($result2 == 1) {
        $flash_data['flashdata_msg'] = 'Labour Wage Slip Updated Successfully!.';
        $flash_data['message'] = 'Labour Wage Slip 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;
      if($this->config->item('Labour_wage_slip_allow_multiple_day_by_site')==1){
        $flash_data['flashdata_msg'] = 'Sorry.. Labour Wage Slip on Same Date & Project Already Exist!';
      }else{
        $flash_data['flashdata_msg'] = 'Sorry.. Labour Wage Slip on Same Date Already Exist!';
      }
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    echo(json_encode($flash_data));
  }
  public function delete()
  {
    $data2['wage_id'] = $this->security->xss_clean($this->input->post('wage_id'));
    $data2['delete_status'] = 1;

    $result2 = $this->Labour_wages->update_labour_wage($data2);
    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['flashdata_msg'] = 'Labour Wage SLip Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';

    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }

    echo(json_encode($flash_data));
  }
  public function select(){
    $data['delete_status'] = 0;
    if(isset($_POST['id']) && $_POST['id']!=""){
      $data['labour_id'] = $_POST['id'];
    }
    $result	= $this->Labour->select_labour("",$data);
    if($result->num_rows()>0) {
      foreach ($result->result() as $row):
        $id[] = $row->labour_id;
        $name[] = $row->labour_name;
        $address[]  = $row->labour_address;
      endforeach;
      echo json_encode(array("count" => $result->num_rows(),"id" => $id,"name" => $name,"address" => $address));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }

}
?>
