<?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 Accounts 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('Client_model', 'Client');
    $this->load->model('Supplier_model', 'Supplier');
    $this->load->model('Purchase_bill_model', 'Purchases');
    $this->load->model('Purchase_order_model', 'Purchase_order');
    $this->load->model('Material_model', 'Material');
    $this->load->model('Subcontracts_model', 'Subcontracts');
    $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->model('Employees_model', 'Employee');
    $this->load->library('Bills_management', 'bills_management');
    $this->load->library('Accounts_management', 'accounts_management');
    $this->load->library('Projects_management', 'projects_management');
    $this->load->library('Supplier_management', 'supplier_management');
  }
  public function index_get()
  {
    //     Default Method
    $this->transaction_select_get();
  }

  public function transaction_create_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL ) {

      $transaction_data['tr_type'] = $this->post('tr_type');
      $transaction_data['reference_id'] = $this->post('reference_id');
      $transaction_data['reference_type'] = $this->post('reference_type');
      $transaction_data['tr_description'] = ucwords(str_replace('_',' ',$transaction_data['tr_type']));
      $transaction_data['created_date'] = date('Y-m-d H:i:s');
      $transaction_data['created_by'] = $this->post('user_id');
      if($this->post('remarks')){
        $transaction_data['tr_remarks'] = $this->post('remarks');
      }
      if($transaction_data['tr_type']=='client_payment_transaction'){

        $account_heads_where['ah.delete_status'] = 0;
        $account_heads_where['ah.acc_user_id'] = $this->post('user_id');
        $account_heads_data	= $this->Account->select_account_heads("acc_head_id",$account_heads_where)->row();
        $transaction_data['tr_credit_acc'] = $account_heads_data->acc_head_id;
        // $transaction_data['tr_credit_acc'] = $this->post('credit_acc');
        $transaction_data['tr_debit_acc'] = 2;//Client Payment Receipts
        $transaction_data['tr_amount'] = $this->post('received_amount');
        $transaction_data['tr_date'] = date('Y-m-d',strtotime($this->post('received_date')));
        $transaction_data['tr_reference_no'] = $this->post('receipt_no');

        if($this->post('received_from')){
          $transaction_data['tr_other_data'] = $this->post('received_from');
        }
        if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
          $transaction_data['tr_entry_approval_status'] = 0;
        }
      }else{
        if($transaction_data['tr_type']=='purchase_bill_transaction' || $transaction_data['tr_type']=='purchase_order_transaction'){
          $transaction_data['tr_credit_acc'] = 5;//Supplier Payments
          if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
            $transaction_data['tr_entry_approval_status'] = 0;
          }
        }elseif($transaction_data['tr_type']=='expense_bill_transaction' || $transaction_data['tr_type']=='subcontract_bill_transaction'){
          if($transaction_data['tr_type']=='expense_bill_transaction'){
            $bill_type='expense_bill';
          }else{
            $bill_type='subcontract_bill';
          }
          $bill_details	= $this->Bills->select_bills("b.bill_type,b.bill_credit_ac",array("b.bill_id"=>$transaction_data['reference_id']),$bill_type)->row();
          $transaction_data['tr_credit_acc'] = $bill_details->bill_credit_ac;
          if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
            $transaction_data['tr_entry_approval_status'] = 0;
          }
        }elseif($transaction_data['tr_type']=='labour_transaction'){
          $transaction_data['tr_credit_acc'] = 7;//Labour Payments
          if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
            $transaction_data['tr_entry_approval_status'] = 0;
          }
        }elseif($transaction_data['tr_type']=='salary_slip_transaction'){
          $transaction_data['tr_credit_acc'] = 10;//Salary Payments
        }elseif($transaction_data['tr_type']=='user_payment_receipt_transaction'){
          $transaction_data['tr_credit_acc'] = 9;//User Payments
        }elseif($transaction_data['tr_type']=='subcontract_bill_transaction' || $transaction_data['tr_type']=='subcontract_advance_transaction'){
          $transaction_data['tr_credit_acc'] = 8; //Subcontract Payments
          if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
            $transaction_data['tr_entry_approval_status'] = 0;
          }
        }

        if(($transaction_data['tr_type'] == 'expense_bill_transaction' || $transaction_data['tr_type'] == 'purchase_bill_transaction' || $transaction_data['tr_type'] == 'loan_transaction' || $transaction_data['tr_type'] == 'loan_receipt_transaction') && $this->config->item('Mobile_App_enable_data_entry_approval')==1 && $this->config->item('User_enable_data_entry_approval_2_level')==1 && $this->session->userdata('user_role_id')>2){
          $transaction_data['tr_entry_approval_status_2'] = 0;
        }

        $account_heads_where['ah.delete_status'] = 0;
        $account_heads_where['ah.acc_user_id'] = $this->post('user_id');
        $account_heads_data	= $this->Account->select_account_heads("ah.acc_head_id",$account_heads_where)->row();
        $transaction_data['tr_debit_acc'] = $account_heads_data->acc_head_id;
        $transaction_data['tr_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->post('paid_date'))));
        // $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->post('debit_acc'));
        $transaction_data['tr_amount'] = $this->security->xss_clean($this->post('paid_amount'));
        $transaction_data['tr_mode'] = $this->security->xss_clean($this->post('payment_mode'));
        if($this->post('remarks')!=''){
          $transaction_data['tr_remarks'] = $this->post('remarks');
        }
        if($this->post('reference_date')!=''){
          $transaction_data['tr_reference_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->post('reference_date'))));
        }
        if($this->post('reference_no')!=''){
          $transaction_data['tr_reference_no'] = $this->post('tr_reference_no');
        }
      }
      $transaction_result =  $this->Account->create_account_transaction($transaction_data);

      if($transaction_result['status'] == 1) {
        if($transaction_data['tr_type'] =='expense_bill_transaction' || $transaction_data['tr_type']=='subcontract_bill_transaction'){
          $this->bills_management->calculate_bill_total($transaction_data['reference_id']);
        }
        $message = [
          'status' => TRUE,
          'message' => 'Transaction Added 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 . User ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function transaction_update_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && $this->post('transaction_id')!="" && $this->post('transaction_id') !== NULL ) {

      $transaction_data['transaction_id'] = $this->post('transaction_id');
      $transaction_data['tr_type'] = $this->post('tr_type');
      $transaction_data['reference_id'] = $this->post('reference_id');
      $transaction_data['reference_type'] = $this->post('reference_type');
      $transaction_data['tr_description'] = ucwords(str_replace('_',' ',$transaction_data['tr_type']));
      $transaction_data['updated_date'] = date('Y-m-d H:i:s');
      $transaction_data['updated_by'] = $this->post('user_id');
      if($this->post('remarks')){
        $transaction_data['tr_remarks'] = $this->post('remarks');
      }
      if($transaction_data['tr_type']=='client_payment_transaction'){
        $account_heads_where['ah.delete_status'] = 0;
        $account_heads_where['ah.acc_user_id'] = $this->post('user_id');
        $account_heads_data	= $this->Account->select_account_heads("acc_head_id",$account_heads_where)->row();
        $transaction_data['tr_credit_acc'] = $account_heads_data->acc_head_id;
        // $transaction_data['tr_credit_acc'] = $this->post('credit_acc');
        $transaction_data['tr_debit_acc'] = 2;//Client Payment Receipts
        $transaction_data['tr_amount'] = $this->post('received_amount');
        $transaction_data['tr_date'] = date('Y-m-d',strtotime($this->post('received_date')));
        $transaction_data['tr_reference_no'] = $this->post('receipt_no');
      }else{
        if($transaction_data['tr_type']=='purchase_bill_transaction' || $transaction_data['tr_type']=='purchase_order_transaction'){
          $transaction_data['tr_credit_acc'] = 5;//Supplier Payments
        }elseif($transaction_data['tr_type']=='expense_bill_transaction' || $transaction_data['tr_type']=='subcontract_bill_transaction'){
          $bill_details	= $this->Bills->select_bills("b.bill_type,b.bill_credit_ac",array("b.bill_id"=>$transaction_data['reference_id']))->row();
          $transaction_data['tr_credit_acc'] = $bill_details->bill_credit_ac;
        }elseif($transaction_data['tr_type']=='labour_transaction'){
          $transaction_data['tr_credit_acc'] = 7;//Labour Payments
        }elseif($transaction_data['tr_type']=='salary_slip_transaction'){
          $transaction_data['tr_credit_acc'] = 10;//Salary Payments
        }elseif($transaction_data['tr_type']=='user_payment_receipt_transaction'){
          $transaction_data['tr_credit_acc'] = 9;//User Payments
        }elseif($transaction_data['tr_type']=='subcontract_bill_transaction' || $transaction_data['tr_type']=='subcontract_advance_transaction'){
          $transaction_data['tr_credit_acc'] = 8; //Subcontract Payments
        }
        $account_heads_where['ah.delete_status'] = 0;
        $account_heads_where['ah.acc_user_id'] = $this->post('user_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['tr_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->post('paid_date'))));
        // $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->post('debit_acc'));
        $transaction_data['tr_amount'] = $this->security->xss_clean($this->post('paid_amount'));
        $transaction_data['tr_mode'] = $this->security->xss_clean($this->post('payment_mode'));

        if($this->post('reference_date')!=''){
          $transaction_data['tr_reference_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->post('reference_date'))));
        }
        if($this->post('reference_no')!=''){
          $transaction_data['tr_reference_no'] = $this->post('tr_reference_no');
        }
      }
      $transaction_result =  $this->Account->update_account_transaction($transaction_data);

      if($transaction_result == 1) {
        if($transaction_data['tr_type'] =='expense_bill_transaction' || $transaction_data['tr_type']=='subcontract_bill_transaction'){
          $this->bills_management->calculate_bill_total($transaction_data['reference_id']);
        }
        $message = [
          'status' => TRUE,
          'message' => 'Transaction Details 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 . User ID, Transaction ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function transaction_delete_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && $this->post('transaction_id')!="" && $this->post('transaction_id') !== NULL ) {

      $transaction_data['transaction_id'] = $this->post('transaction_id');
      $transaction_data['delete_status'] = 1;
      $transaction_details = $this->Account->select_account_transaction("ats.*",array("ats.transaction_id"=>$transaction_data['transaction_id']))->row();

      $transaction_result =  $this->Account->update_account_transaction($transaction_data);

      if($transaction_result == 1) {
        if($transaction_details->tr_type =='purchase_bill_transaction'){
          $this->bills_management->calculate_purchase_bill_total($transaction_details->reference_id);
        }elseif($transaction_details->tr_type =='expense_bill_transaction' || $transaction_details->tr_type=='subcontract_bill_transaction'){
          $this->bills_management->calculate_bill_total($transaction_details->reference_id);
        }elseif($transaction_details->tr_type =='salary_slip_transaction'){
          $this->bills_management->calculate_salary_slip_total($transaction_details->reference_id);
        }elseif($transaction_details->tr_type =='vehicle_work_slip_transaction'){
          $this->bills_management->calculate_vehicle_work_slip_total($transaction_details->reference_id);
        }

        $message = [
          'status' => TRUE,
          'message' => 'Transaction 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 . User ID, Transaction ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function transaction_select_get($reference_type)
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL) {

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $data['ats.created_by'] = $user_id;
      if($reference_type=='client_payment'){
        $data['ats.tr_type'] = $reference_type."_transaction";
        $data['ats.reference_type'] = 'project';
        $select_columns = "c.client_id,c.client_name,wc.work_id,wc.work_name";
      }else{
        $data['ats.reference_type'] = $reference_type;
        $data['ats.tr_type'] = $reference_type."_transaction";
      }
      if($this->get('work_id')){
        $data['ats.reference_id'] = $this->get('work_id');
      }
      $entry_approval_status = $this->config->item('select_data_entry_approval');
      $result	= $this->Account->select_account_transaction("ats.*,ah1.acc_head_name as debit_account,ah2.acc_head_name as credit_account,u1.user_alias as created_user,".$select_columns,$data,$reference_type,'','','',$entry_approval_status);
      $total_amount = 0;
      if ($result->num_rows() > 0) {
        $message = array();
        $j = 0;
        foreach ($result->result() as $row):

          $message[$j]['transaction_id'] = $row->transaction_id;
          $message[$j]['tr_date'] = date('d-m-Y',strtotime($row->tr_date));
          $message[$j]['client_name'] = $row->client_name;
          $message[$j]['work_name'] = $row->work_name;
          $message[$j]['work_id'] = $row->work_id;
          $message[$j]['tr_amount']=$row->tr_amount;
          $message[$j]['credit_account']=$row->credit_account;
          $message[$j]['tr_reference_no'] = $row->tr_reference_no;
          $message[$j]['tr_remarks'] = $row->tr_remarks;
          $message[$j]['tr_credit_acc']=$row->tr_credit_acc;
          $message[$j]['created_user']=$row->created_user;
          $message[$j]['entry_approval_status']=$row->tr_entry_approval_status;
          $total_amount += $row->tr_amount;

          $j++;
        endforeach;
        $json_data['status'] = TRUE;
        $json_data['total_amount'] = $total_amount;
        $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 Transactions Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function select_ledger_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL) {
      $start_date = $end_date = '';
      if($this->post('start_date')!="" && $this->post('start_date') !== NULL) {
        $start_date = date("Y-m-d",strtotime($this->post('start_date')));
      }
      if($this->post('end_date')!="" && $this->post('end_date') !== NULL) {
        $end_date = date("Y-m-d",strtotime($this->post('end_date')));
      }
      $message=$data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->post('user_id');
      $user_details = $this->User->select_user("",array("user_id"=>$user_id));
      $account_heads_where['ah.delete_status'] = 0;
      $account_heads_where['ah.acc_user_id'] = $user_id;
      $account_heads_data	= $this->Account->select_account_heads("acc_head_id,acc_head_name",$account_heads_where);
      if ($account_heads_data->num_rows() == 1) {

        $account = 'acchead_' . $account_heads_data->row()->acc_head_id;
        $ledger_data = $this->accounts_management->get_account_statement('ledger',$account,$start_date,$end_date,$user_details->row()->role_name,$user_id,'Petty Cash');
        foreach ($ledger_data as $key => $value) {
          $message[$key] = $value;
        }
        $message['total_balance'] = $message['total_debit'] = $message['total_credit'] = 0;

        // if($start_date==''){
        //   $op_balance[0]['date'] = '';
        //   $op_balance[0]['account'] = $account_details->acc_head_name;
        //   $op_balance[0]['description'] = "A/C Opening Balance";
        //   $op_balance[0]['debit'] = '';
        //   $op_balance[0]['credit'] = $account_heads_data->row()->op_balance;
        //
        //   $message['total_balance']+=$value['credit'];
        //   $message['total_credit']+=$value['credit'];
        // }else{
        //   $op_balance[0]['date'] = '';
        //   $op_balance[0]['account'] = $account_details->acc_head_name;
        //   $op_balance[0]['description'] = "Current Opening Balance";
        //   $op_balance[0]['debit'] = '';
        //   $op_balance[0]['credit'] = $account_heads_data->row()->op_balance;
        //
        //   $message['total_balance']+=$value['credit'];
        //   $message['total_credit']+=$value['credit'];
        // }

        // merge both array
        // $mergeArr = array_merge( $arr1, $arr2 );
        if(isset($message['transactions'])){
          foreach ($message['transactions'] as $key => $value) {
            $message['transactions'][$key]['date'] = date('d-m-Y',strtotime($value['date']));
            if($value['debit']!=''){
              $message['total_balance']-=$value['debit'];
              $message['total_debit']+=$value['debit'];
            }elseif($value['credit']!=''){
              $message['total_balance']+=$value['credit'];
              $message['total_credit']+=$value['credit'];
            }
            $value['debit'] = round($value['debit'],$this->config->item('Currency_amount_decimals_2'));
            $value['credit'] = round($value['credit'],$this->config->item('Currency_amount_decimals_2'));
          }
        }
        $message['total_debit'] = number_format($message['total_debit'], $this->config->item('Currency_amount_decimals_2'));
        $message['total_credit'] = number_format($message['total_credit'], $this->config->item('Currency_amount_decimals_2'));
        $message['total_balance'] = number_format($message['total_balance'], $this->config->item('Currency_amount_decimals_2'));

        $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' => 'User Details Not Found'
        ];
        $this->response($message, REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }

}
