<?php

defined('BASEPATH') OR exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
require APPPATH . 'libraries/REST_Controller.php';

class Travel_allowance extends REST_Controller {

  function __construct()
  {
    parent::__construct();
    // Construct the parent class
    header('Content-type: application/json');
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
    $method = $_SERVER['REQUEST_METHOD'];
    if($method == "OPTIONS") {
      die();
    }

    ini_set('max_execution_time', 5000);
    ini_set("memory_limit", "-1");
    ini_set("allow_url_fopen", "1");


    //      Load Models
    $this->load->model('User_model', 'User');
    $this->load->model('Work_model', 'Work');
    $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');

  }
  public function index_get()
  {
    //     Default Method
    $this->select_ta_get();
  }
  public function create_ta_post()
  {
    $ta_data['vehicle_type'] = $this->post('ta_vehicle');
    $ta_data['ta_from'] = $this->post('ta_from');
    $ta_data['ta_to'] = $this->post('ta_to');
    $ta_data['kms'] = $this->post('ta_km');
    $ta_data['amount'] = $this->post('ta_amount');
    $ta_data['ta_remarks'] = $this->post('remarks');
    $ta_data['user_id'] = $ta_data['created_by'] = $this->post('user_id');
    $ta_data['employee_id'] = $this->Employee->select_employee("e.employee_id",array("e.user_id"=>$ta_data['user_id']))->row()->employee_id;
    $ta_data['ta_date'] = date('Y-m-d');
    if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
      $ta_data['entry_approval_status'] = 0;
    }

    $ta_data_where = $ta_data;
    unset($ta_data_where['employee_id']);
    unset($ta_data_where['user_id']);
    unset($ta_data_where['created_by']);
    unset($ta_data_where['vehicle_type']);
    $ta_data_where['ta.created_by'] = $ta_data['user_id'];
    $ta_data_where['ta.employee_id'] = $ta_data['employee_id'];
    $ta_data_where['ta.vehicle_type'] = $ta_data['vehicle_type'];

    if($this->post('image')){
      $new_filename = date('dmY-His') . '.png';
      $ImageData = $this->post('image');
      $ImagePath = "uploads/ta/".$new_filename;

      file_put_contents($ImagePath,base64_decode($ImageData));
      $ta_data['image'] = $new_filename;
    }


    if($this->post('ta_vehicle') && $this->post('ta_vehicle')!="" && $this->post('ta_from') && $this->post('ta_from')!="" && $this->post('ta_to') && $this->post('ta_to')!="" && $this->post('ta_km') && $this->post('ta_km')!="" &&
    $this->post('ta_amount') && $this->post('ta_amount')!="" && $this->post('user_id') && $this->post('user_id')!="") {
      $count = $this->Travel_allowance->select_ta("ta_id",$ta_data_where)->num_rows();
      if($count==0){
        $ta_data['created_date'] = date('Y-m-d H:i:s');
        $result = $this->Travel_allowance->create_ta($ta_data);
        $flash_data['status'] = $result['status'];
        if ($result['status'] == 1) {

          // Insert to Account Transaction
          $account_heads_where['ah.delete_status'] = 0;
          $account_heads_where['ah.acc_employee_id'] = $ta_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'] = $ta_data['ta_date'];
          $transaction_data['tr_credit_acc'] = 22;
          $transaction_data['tr_description'] = ucwords(str_replace('_',' ',$transaction_data['tr_type']));
          $transaction_data['tr_amount'] = $ta_data['amount'];
          $transaction_data['tr_mode'] = 'CASH';
          $transaction_data['created_date'] = date('Y-m-d H:i:s');
          $transaction_data['created_by'] = $ta_data['created_by'];
          if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
            $transaction_data['tr_entry_approval_status'] = 0;
          }
          $transaction_result =  $this->Account->create_account_transaction($transaction_data);

          $message = [
            'status' => TRUE,
            'message' => 'TA Created Successfully'
          ];
          $this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
        }else {
          $message = [
            'status' => FALSE,
            'message' => 'There Has Been Some Error Occurred'
          ];
          $this->response($message, REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
        }
      }else {
        $message = [
          'status' => FALSE,
          'message' => 'Same Data Already Submitted'
        ];
        $this->response($message, REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing !'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function update_ta_post()
  {
    $ta_data['ta_id'] = $this->post('ta_id');
    $ta_data['vehicle_type'] = $this->post('ta_vehicle');
    $ta_data['ta_from'] = $this->post('ta_from');
    $ta_data['ta_to'] = $this->post('ta_to');
    $ta_data['kms'] = $this->post('ta_km');
    $ta_data['amount'] = $this->post('ta_amount');
    $ta_data['ta_remarks'] = $this->post('remarks');
    $ta_data['updated_date'] = date('Y-m-d H:i:s');
    $ta_data['user_id'] = $ta_data['updated_by'] = $this->post('user_id');
    $ta_data['employee_id'] = $this->Employee->select_employee("e.employee_id",array("e.user_id"=>$ta_data['user_id']))->row()->employee_id;
    if($this->post('image_end')){
      $new_filename = date('dmY-His') . '.png';
      $ImageData = $this->post('image_end');
      $ImagePath = "uploads/ta/".$new_filename;

      file_put_contents($ImagePath,base64_decode($ImageData));
      $ta_data['image_end'] = $new_filename;
    }

    if($this->post('ta_id') && $this->post('ta_id')!='' && $this->post('ta_vehicle') && $this->post('ta_vehicle')!="" && $this->post('ta_from') && $this->post('ta_from')!="" && $this->post('ta_to') && $this->post('ta_to')!="" && $this->post('ta_km') && $this->post('ta_km')!="" &&
    $this->post('ta_amount') && $this->post('ta_amount')!="" && $this->post('user_id') && $this->post('user_id')!="") {
      $result = $this->Travel_allowance->update_ta($ta_data);
      $flash_data['status'] = $result;
      if ($result == 1) {
        // 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'] = $ta_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'] = $ta_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_amount'] = $ta_data['amount'];
          $transaction_data['tr_mode'] = 'CASH';
          $this->Account->update_account_transaction($transaction_data);
        }

        $message = [
          'status' => TRUE,
          'message' => 'TA Updated Successfully'
        ];
        $this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
      }
      else {
        $message = [
          'status' => FALSE,
          'message' => 'There Has Been Some Error Occurred'
        ];
        $this->response($message, REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing !'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function delete_ta_post()
  {
    if($this->post('ta_id')!="" && $this->post('ta_id') !== NULL ){
      $ta_data['ta_id'] = $this->post('ta_id');
      $ta_data['delete_status'] = 1;
      $result = $this->Travel_allowance->update_ta($ta_data);
      $flash_data['status'] = $result;
      if ($result == 1) {
        // 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'] = $ta_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);
        }

        $message = [
          'status' => TRUE,
          'message' => 'TA Deleted Successfully'
        ];
        $this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
      }
      else {
        $message = [
          'status' => FALSE,
          'message' => 'There Has Been Some Error Occurred'
        ];
        $this->response($message, REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
      }
    }
    else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing !'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function select_ta_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL){
      //check the current day
      if(date('D')!='Sat')
      {
        //take the last monday
        $start_date = date('Y-m-d',strtotime('last Saturday'));
      }else{
        $start_date = date('Y-m-d');
      }

      //always next saturday
      if(date('D')!='Fri')
      {
        $end_date = date('Y-m-d',strtotime('next Friday'));
      }else{
        $end_date = date('Y-m-d');
      }
      $data["STR_TO_DATE(ta.created_date,'%Y-%m-%d %H:%i:%s') <="]= $end_date." 23:59:00";
      $data["STR_TO_DATE(ta.created_date,'%Y-%m-%d %H:%i:%s') >="]= $start_date." 00:00:00";
      $data['ta.employee_id'] = $this->Employee->select_employee("e.employee_id",array("e.user_id"=>$this->get('user_id')))->row()->employee_id;
      $result = $this->Travel_allowance->select_ta("e.employee_name,ta.*,tv.fixed_rate,u1.user_alias AS ta_created_by",$data,'',$this->config->item('select_data_entry_approval'));
      if ($result->num_rows() > 0) {
        $message = array();
        $j = 0;
        foreach ($result->result() as $row):
          $image_start = $image_end = '';
          if($row->image!=''){
            $image_start = base_url().'uploads/ta/'.$row->image;
          }
          if($row->image_end!=''){
            $image_end = base_url().'uploads/ta/'.$row->image_end;
          }
          $message[$j]['ta_id']=$row->ta_id;
          $message[$j]['user_name']=$row->employee_name;
          $message[$j]['vehicle_type']=$row->vehicle_type;
          $message[$j]['fixed_rate']=$row->fixed_rate;
          $message[$j]['from']=$row->ta_from;
          $message[$j]['to']=$row->ta_to;
          $message[$j]['distance']=$row->kms;
          $message[$j]['ta_amount']=$row->amount;
          $message[$j]['ta_remarks']=$row->ta_remarks;
          $message[$j]['image_start']=$image_start;
          $message[$j]['image_end']=$image_end;
          $message[$j]['created_by']=$row->ta_created_by;
          $message[$j]['created_date']=date('d-m-Y',strtotime($row->created_date));
          if(date('Y-m-d',strtotime($row->created_date))==date('Y-m-d') || date('Y-m-d',strtotime($row->created_date))==date('Y-m-d',strtotime("-1 days"))){
            $message[$j]['editable']=1;
          }else{
            $message[$j]['editable']=0;
          }
          $message[$j]['entry_approval_status']=$row->entry_approval_status;

          $j++;
        endforeach;
        $json_data['status'] = TRUE;
        $json_data['data'] = $message;
        $this->set_response($json_data, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
      } else {
        $message = [
          'status' => FALSE,
          'message' => 'No TA Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing !'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }


}
