<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Travel_allowance 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('Supplier_model', 'Supplier');
    $this->load->model('Material_model', 'Material');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Tools_model', 'Tools');
    $this->load->model('Travel_allowance_model', 'Travel_allowance');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Employees_model', 'Employee');

    //        Check User Logged in or Not
    // $allowed_user_roles = array("madmin","admin","supervisor","general_manager");
    // if($this->User->is_logged_in($allowed_user_roles)==false){
    //   redirect(base_url(), 'refresh');
    // }
    //        File Directory
    $this->page_data['directory'] = "travel_allowance";
    $this->page_data['ta_vehicles'] = $this->Travel_allowance->select_ta_vehicles()->result_array();
  }

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

  public function view()
  {
    // Check Module is Enabled or Not
    // if($this->config->item('app_module_tools_management')==0){
    //   redirect(base_url().'dashboard', 'refresh');
    // }
    $data=array();
    $data['u.user_role >'] = 2;
    $this->page_data['users'] = $this->User->select_user("",$data)->result();

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

    $this->page_data['page_name'] = 'ta_list_view';
    $this->load->view('Index', $this->page_data);
  }

  public function create_ta()
  {
    $data['vehicle_type'] = $this->security->xss_clean($this->input->post('vehicle_type'));
    if($this->input->post('vehicle')){
      $data['vehicle_id'] = $this->security->xss_clean($this->input->post('vehicle'));
    }
    $data['project_id'] = $this->security->xss_clean($this->input->post('project'));
    $data['ta_from'] = $this->security->xss_clean($this->input->post('ta_from'));
    $data['ta_to'] = $this->security->xss_clean($this->input->post('ta_to'));
    $data['kms'] = $this->security->xss_clean($this->input->post('ta_km'));
    $data['amount'] = $this->security->xss_clean($this->input->post('ta_amount'));
    $data['ta_remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data['vehicle_no'] = $this->security->xss_clean($this->input->post('vehicle_no'));
    $data['employee_id'] = $this->security->xss_clean($this->input->post('employee_id'));
    if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
      $data['entry_approval_status'] = 0;
    }
    if($this->input->post('ta_date')){
      $data['ta_date'] = date('Y-m-d',strtotime($this->input->post('ta_date')));
    }else{
      $data['ta_date'] = date('Y-m-d');
    }
    $data['created_by'] = $this->session->userdata('user_id');
    $ta_data_where = $data;
    unset($ta_data_where['employee_id']);
    unset($ta_data_where['created_by']);
    unset($ta_data_where['vehicle_type']);
    unset($ta_data_where['vehicle_no']);
    if($this->input->post('vehicle')){
      unset($ta_data_where['vehicle_id']);
      $ta_data_where['ta.vehicle_id'] = $data['vehicle_id'];
    }
    $ta_data_where['ta.vehicle_type'] = $data['vehicle_type'];
    $ta_data_where['ta.vehicle_no'] = $data['vehicle_no'];
    $ta_data_where['ta.employee_id'] = $data['employee_id'];
    $ta_data_where['ta.created_by'] = $this->session->userdata('user_id');
    $count = $this->Travel_allowance->select_ta("ta_id",$ta_data_where)->num_rows();
    if($count==0){
      $data['created_date'] = date('Y-m-d H:i:s');

      $result = $this->Travel_allowance->create_ta($data);
      $flash_data['status'] = $result['status'];
      if ($result['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Travel Allowance Added Successfully!';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';

        // Insert to Account Transaction
        $account_heads_where['ah.delete_status'] = 0;
        $account_heads_where['ah.acc_employee_id'] = $data['employee_id'];
        $account_heads_data	= $this->Account->select_account_heads("acc_head_id",$account_heads_where)->row();
        $transaction_data['tr_debit_acc'] = $account_heads_data->acc_head_id;
        $transaction_data['reference_id'] = $result['insert_id'];
        $transaction_data['reference_type'] = "travel_allowance";
        $transaction_data['tr_type'] = $transaction_data['reference_type']."_transaction";
        $transaction_data['tr_date'] = $data['ta_date'];
        $transaction_data['tr_credit_acc'] = 22;
        $transaction_data['tr_description'] = ucwords(str_replace('_',' ',$transaction_data['tr_type']));
        $transaction_data['tr_amount'] = $data['amount'];
        $transaction_data['tr_mode'] = 'CASH';
        $transaction_data['created_date'] = date('Y-m-d H:i:s');
        $transaction_data['created_by'] = $data['created_by'];
        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);
      } else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else {
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. Same Data Already Entered!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Warning !!';
    }

    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);
  }
  public function update_ta()
  {
    $data['ta_id'] = $this->security->xss_clean($this->input->post('ta_id_edit'));
    $data['vehicle_type'] = $this->security->xss_clean($this->input->post('vehicle_type'));
    if($this->input->post('vehicle')){
      $data['vehicle_id'] = $this->security->xss_clean($this->input->post('vehicle'));
    }
    $data['project_id'] = $this->security->xss_clean($this->input->post('project'));
    $data['ta_from'] = $this->security->xss_clean($this->input->post('ta_from_edit'));
    $data['ta_to'] = $this->security->xss_clean($this->input->post('ta_to_edit'));
    $data['kms'] = $this->security->xss_clean($this->input->post('ta_km_edit'));
    $data['amount'] = $this->security->xss_clean($this->input->post('ta_amount_edit'));
    $data['ta_remarks'] = $this->security->xss_clean($this->input->post('remarks_edit'));
    $data['vehicle_no'] = $this->security->xss_clean($this->input->post('vehicle_no'));
    $data['updated_date'] = date('Y-m-d H:i:s');
    $data['employee_id'] = $this->security->xss_clean($this->input->post('employee_id'));
    $data['updated_by'] = $this->session->userdata('user_id');
    if($this->input->post('ta_date')){
      $data['ta_date'] = date('Y-m-d',strtotime($this->input->post('ta_date')));
    }
    $result = $this->Travel_allowance->update_ta($data);
    $flash_data['status'] = $result;
    if ($result == 1) {
      $flash_data['flashdata_msg'] = 'TA Details Updated Successfully!';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';

      // Select TA transaction & Update
      $ta_transaction_where['ats.reference_type'] = 'travel_allowance';
      $ta_transaction_where['ats.tr_type'] = 'travel_allowance_transaction';
      $ta_transaction_where['ats.reference_id'] = $data['ta_id'];
      $ta_transactions = $this->Account->select_account_transaction("ats.transaction_id", $ta_transaction_where,'travel_allowance')->result();
      foreach ($ta_transactions as $key => $value) {
        $account_heads_where['ah.delete_status'] = 0;
        $account_heads_where['ah.acc_employee_id'] = $data['employee_id'];
        $account_heads_data	= $this->Account->select_account_heads("acc_head_id",$account_heads_where)->row();
        $transaction_data['transaction_id'] = $value->transaction_id;
        $transaction_data['tr_debit_acc'] = $account_heads_data->acc_head_id;
        $transaction_data['tr_date'] = $data['ta_date'];
        $transaction_data['tr_amount'] = $data['amount'];
        $transaction_data['tr_mode'] = 'CASH';
        $this->Account->update_account_transaction($transaction_data);
      }
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);
  }
  public function delete()
  {
    $flash_data = array();
    $data['ta_id'] = $this->security->xss_clean($this->input->post('ta_id_delete'));
    $data['delete_status'] = 1;
    $result = $this->Travel_allowance->update_ta($data);
    $flash_data['status'] = $result;
    if ($result == 1) {
      $flash_data['flashdata_msg'] = 'TA Deleted Successfully!';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';

      // Select TA transaction & Update
      $ta_transaction_where['ats.reference_type'] = 'travel_allowance';
      $ta_transaction_where['ats.tr_type'] = 'travel_allowance_transaction';
      $ta_transaction_where['ats.reference_id'] = $data['ta_id'];
      $ta_transactions = $this->Account->select_account_transaction("ats.transaction_id", $ta_transaction_where,'travel_allowance')->result();
      foreach ($ta_transactions as $key => $value) {
        $transaction_data['transaction_id'] = $value->transaction_id;
        $transaction_data['delete_status'] = 1;
        $this->Account->update_account_transaction($transaction_data);
      }

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

  public function select_ta($page_data_type=''){
    $json_data=array();
    $j=0;
    $data=array();
    if(isset($_POST['vehicle_type']) && $_POST['vehicle_type']!='' && $_POST['vehicle_type']!='all'){
      $data['ta.vehicle_type'] = $_POST['vehicle_type'];
    }
    if(isset($_POST['vehicle']) && $_POST['vehicle']!='' && $_POST['vehicle']!='all'){
      $data['ta.vehicle_id'] = $_POST['vehicle'];
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['ta.project_id'] = $_POST['work'];
    }
    if(isset($_POST['project']) && $_POST['project']!='' && $_POST['project']!='all'){
      $data['ta.project_id'] = $_POST['project'];
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['ta.user_id'] = $_POST['user_id'];
    }
    if(isset($_POST['created_by']) && $_POST['created_by']!='' && $_POST['created_by']!='all'){
      $data['ta.created_by'] = $_POST['created_by'];
    }
    if(isset($_POST['employee_id']) && $_POST['employee_id']!='' && $_POST['employee_id']!='all'){
      $data['ta.employee_id'] = $_POST['employee_id'];
    }
    if (isset($_POST['acc_head_id']) && $_POST['acc_head_id'] != '' && $_POST['acc_head_id'] != 'all') {
      $acc_head_id = $_POST['acc_head_id'];
      $account_heads_where['ah.acc_head_id'] = $_POST['acc_head_id'];
      $account_heads_data	= $this->Account->select_account_heads("acc_head_id,acc_employee_id",$account_heads_where)->row();
      if($account_heads_data->acc_employee_id!=0){
        $data['ta.employee_id'] = $account_heads_data->acc_employee_id;
      }
    }
    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(ta.ta_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(ta.ta_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
      $data['ta.ta_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!='' && $_POST['end_date']!='all'){
      $data['ta.ta_date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    $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['u1.user_role >'] =2;
      if(isset($_POST['approval_status']) && $_POST['approval_status']!='' && $_POST['approval_status']!='all'){
        $entry_approval = $_POST['approval_status'];
      }
    }

    $result = $this->Travel_allowance->select_ta("ta.*,u1.user_alias AS ta_created_by,e.employee_name AS ta_user_name,u1.user_role as created_user_role_id,wc.work_name,v.vehicle_name",$data,'',$entry_approval);
    $result_array=$result->result();
    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();
    $sl_no=0;
    $total_amount = $total_kms = 0;
    foreach($result_array as $row):
      $sl_no++;
      $btn_delete = $btn_edit = $attachment = '';
      if($this->session->userdata('user_role')=='auditor' || $this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_role')=='accounts_manager' || $this->session->userdata('user_id')==$row->created_by) {

        $btn_delete = $btn_edit = '';

        if($this->session->userdata('user_role')!='auditor'){
          $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="ta_delete_btn" href="#ta_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="ta_edit_btn" href="#ta_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>';
        }
        $attachment = '';
        if($row->image!=''){
          $attachment .= '<a target="_blank" href="'.base_url().'uploads/ta/'.$row->image.'"><img style="height: 50px;width: 50px;margin-right:5px" src="'.base_url().'uploads/ta/'.$row->image.'" /></a>';
        }
        if($row->image_end!=''){
          $attachment .= '<a target="_blank" href="'.base_url().'uploads/ta/'.$row->image_end.'"><img target="_blank" href="'.base_url().'uploads/ta/'.$row->image_end.'" style="height: 50px;width: 50px;margin-left:5px" src="'.base_url().'uploads/ta/'.$row->image_end.'" /></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="travel_allowance" data-approval-status="'.$row->entry_approval_status.'" data-id="'.$row->ta_id.'" id="btn_data_entry_approval" href="#data_entry_approve_modal" data-toggle="modal" class="btn btn-sm btn-warning m-btn m-btn--icon  m-btn--pill m-btn--air">
          <i class="la la-check-circle"></i> / <i class="la la-times-circle"></i>
          </a>';
        }
        if(($page_data_type=='approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval')==1) || $this->config->item('User_enable_data_entry_approval')==1){
          if($row->entry_approval_status==1){
            $entry_approval_status="<br/><span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Approved</span>";
          }elseif($row->entry_approval_status==2){
            $entry_approval_status="<br/><span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> Rejected</span>";
          }else{
            $entry_approval_status="<br/><span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> Pending</span>";
          }
        }

        $array[$j][]=$sl_no;
        $array[$j][]=$row->ta_id;
        $array[$j][]=date('d-m-Y',strtotime($row->ta_date));
        $array[$j][]=$row->ta_user_name;
        $array[$j][]=($row->project_id!=0)?$row->work_name:"Office";
        $array[$j][]=$row->vehicle_type;
        $array[$j][]=$row->vehicle_name;
        $array[$j][]=$row->vehicle_no;
        $array[$j][]=$row->ta_from;
        $array[$j][]=$row->ta_to;
        $array[$j][]=$row->kms;
        $array[$j][]=$row->amount;
        $array[$j][]=$row->ta_remarks;
        $array[$j][]=$attachment;
        $array[$j][]=$row->ta_created_by.$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->employee_id;
        $array[$j][]=$row->vehicle_id;
        $array[$j][]=$row->project_id;
        $array[$j][]=$row->entry_approval_status;

        $total_amount+=$row->amount;
        $total_kms+=$row->kms;

        $j++;
      }
    endforeach;
    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="";
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]=$total_kms;
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
    }
    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function select_ta_summary(){
    $json_data=array();
    $j=0;
    $data=$ta_where=array();
    // $data['u.user_role !='] = 1;
    // $data['u.user_role !='] = 2;
    if(isset($_POST['employee_id']) && $_POST['employee_id']!='' && $_POST['employee_id']!='all'){
      $data['e.employee_id'] = $_POST['employee_id'];
    }
    if($this->session->userdata('user_role')!='auditor' && $this->session->userdata('user_role')!='admin' && $this->session->userdata('user_role')!='general_manager'){
      $data['e.user_id'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['vehicle_type']) && $_POST['vehicle_type']!='' && $_POST['vehicle_type']!='all'){
      $ta_where['ta.vehicle_type'] = $_POST['vehicle_type'];
    }
    if(isset($_POST['vehicle']) && $_POST['vehicle']!='' && $_POST['vehicle']!='all'){
      $ta_where['ta.vehicle_id'] = $_POST['vehicle'];
    }
    if(isset($_POST['project']) && $_POST['project']!='' && $_POST['project']!='all'){
      $ta_where['ta.project_id'] = $_POST['project'];
    }
    $start_date=$end_date=date('Y-m-d');
    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]));
      $ta_where["STR_TO_DATE(ta.ta_date,'%Y-%m-%d') <="]= $end_date;
      $ta_where["STR_TO_DATE(ta.ta_date,'%Y-%m-%d') >="]= $start_date;
    }

    $result	= $this->Employee->select_employee("*",$data);
    $result_array=$result->result();
    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();
    $sl_no=0;
    $total_amount = $total_distance = 0;
    foreach($result_array as $row):

      $ta_where['ta.employee_id'] = $row->employee_id;

      $ta_result = $this->Travel_allowance->select_ta("wc.work_name,v.vehicle_no,v.vehicle_name,COALESCE(SUM(ta.amount),0) as total_amount,COALESCE(SUM(ta.kms),0) as total_distance",$ta_where);
      $sl_no++;

      $array[$j][]=$sl_no;
      $array[$j][]=date('d-m-Y',strtotime($start_date))." To ".date('d-m-Y',strtotime($end_date));
      $array[$j][]=$row->employee_name;
      $array[$j][]=strtoupper($_POST['vehicle_type']);
      if(isset($_POST['vehicle']) && $_POST['vehicle']!='' && $_POST['vehicle']!='all'){
        $array[$j][]=$row->vehicle_name."[".$row->vehicle_no."]";
      }else{
        $array[$j][]='ALL';
      }
      if(isset($_POST['project']) && $_POST['project']!='' && $_POST['project']!='all'){
        if($_POST['project']==0){
          $array[$j][]='Office';
        }else{
          $array[$j][]=$row->work_name;
        }
      }else{
        $array[$j][]='ALL';
      }
      $array[$j][]=$ta_result->row()->total_distance;
      $array[$j][]=$ta_result->row()->total_amount;

      $total_amount+=$ta_result->row()->total_amount;
      $total_distance+=$ta_result->row()->total_distance;

      $j++;

    endforeach;
    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>".$total_distance."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
    }
    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
}
