<?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 Bills 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->library('Bills_management','bills_management');

    $this->load->library('Projects_management','projects_management');

  }
  public function index_get()
  {
    //     Default Method
    $this->select_bills_get();
  }

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

      $subcontract_data_type='';
      $bill_data['bill_type'] = $this->post('bill_type');
      if($bill_data['bill_type']=='expense'){
        $expense_type = $this->post('expense_type');
        if($expense_type=='work'){
          $bill_data['work_id'] = $this->post('work_id');
        }else{
          $bill_data['work_id'] = 0;
        }
        $bill_data['bill_expense_type'] = $expense_type;
        $bill_data['bill_credit_ac'] = $this->post('expense_head');
      }elseif($bill_data['bill_type']=='subcontract'){
        $bill_data['subcontract_id'] = $this->post('contract_id');
        $bill_data['bill_credit_ac'] = "8"; //Subcontract Payments
        // Select Work
        $bill_data['work_id'] = $this->Subcontracts->select_subcontract("sc.work_id",array("sc.contract_id"=>$bill_data['subcontract_id']))->row()->work_id;
        $bill_data['project_stage_id'] = $this->projects_management->get_project_stage_id($bill_data['work_id']);
      }
      if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
        $bill_data['entry_approval_status'] = 0;
      }
      $bill_data['bill_date'] = date('Y-m-d',strtotime($this->post('bill_date')));
      $bill_data['bill_no'] = $this->post('bill_no');
      $bill_data['bill_gross_amount'] = $this->post('payable_amount');
      $bill_data['bill_tax_amount'] = $bill_data['bill_tds_amount'] = 0;
      if($this->post('bill_tax_amount')){
        $bill_data['bill_tax_amount'] = $this->post('bill_tax_amount');
      }
      if($this->post('tax_percent')){
        $tax_data = $this->Settings->select_tax_types('*',array("tax_id"=>$this->post('tax_percent')))->row();
        $bill_data['bill_tax_percent'] = $this->post('tax_percent');
        $bill_data['bill_tax_amount'] = $bill_data['bill_gross_amount']*$tax_data->tax_percentage/100;
      }
      if($this->post('bill_gross_amount')){
        $bill_data['bill_gross_amount'] = $this->post('bill_gross_amount');
      }
      if($this->post('bill_tds_amount')){
        $bill_data['bill_tds_amount'] = $this->post('bill_tds_amount');
      }
      $bill_data['bill_amount'] = $bill_data['bill_gross_amount'] + $bill_data['bill_tax_amount'];
      $bill_data['bill_payable_amount'] = $bill_data['bill_amount'];
      // $bill_data['bill_description'] = $this->post('bill_description');
      if($this->post('consignee')){
        $bill_data['bill_consignee_name'] = $this->post('consignee');
      }
      if($this->post('bill_remarks')){
        $bill_data['bill_remarks'] = $this->post('bill_remarks');
      }

      if($this->post('image')){
        $bill_data['bill_attachment'] = date('dmY-His') . '.png';
        $Image1_Data = $this->post('image');
        $Image1_Path = "uploads/bills/".$bill_data['bill_attachment'];
        file_put_contents($Image1_Path,base64_decode($Image1_Data));
      }

      $bill_data['created_date'] = date('Y-m-d H:i:s');
      $bill_data['created_by'] = $this->post('user_id');

      $bill_result =  $this->Bills->create_bills($bill_data);
      $flash_data['status'] = $bill_result['status'];
      if ($flash_data['status'] == 1) {
        $message = [
          'status' => TRUE,
          'message' => 'Bill Created Successfully'
        ];

        if($this->post('paid_amount')>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("acc_head_id",$account_heads_where)->row();
          $transaction_data['tr_debit_acc'] = $account_heads_data->acc_head_id;

          $transaction_data['reference_id'] = $bill_result['insert_id'];
          $transaction_data['reference_type'] = $bill_data['bill_type']."_bill";
          $transaction_data['tr_type'] = $bill_data['bill_type']."_bill_transaction";
          $transaction_data['tr_date'] = date('Y-m-d',strtotime($this->post('paid_date')));
          // $transaction_data['tr_debit_acc'] = $this->post('debit_acc');
          $transaction_data['tr_credit_acc'] = $bill_data['bill_credit_ac'];
          $transaction_data['tr_description'] = ucwords($bill_data['bill_type'])." Bill Transaction";
          $transaction_data['tr_amount'] = $this->post('paid_amount');
          $transaction_data['tr_mode'] = $this->post('payment_mode');
          // $transaction_data['tr_reference_no'] = $this->post('reference_no');
          // if($this->post('reference_date')!=''){
          //   $transaction_data['tr_reference_date'] = date('Y-m-d',strtotime($this->post('reference_date')));
          // }
          // $transaction_data['tr_remarks'] = $this->post('tr_remarks');
          $transaction_data['created_date'] = date('Y-m-d H:i:s');
          $transaction_data['created_by'] = $this->post('user_id');
          $transaction_result =  $this->Account->create_account_transaction($transaction_data);
          if($transaction_result['status']==1){
            $message = [
              'status' => TRUE,
              'message' => 'Bill & Transaction Created Successfully'
            ];
          }else{
            $message = [
              'status' => TRUE,
              'message' => 'Bill Created Successfully, Transaction Creation Failed!'
            ];
          }
        }
        // Calculate & Update Bill Total
        $this->bills_management->calculate_bill_total($bill_result['insert_id']);
        $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 update_bill_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && $this->post('bill_id')!="" && $this->post('bill_id') !== NULL ) {

      $bill_data['bill_id'] = $this->post('bill_id');
      $bill_data['bill_type'] = $this->post('bill_type');
      if($bill_data['bill_type']=='expense'){
        $expense_type = $this->post('expense_type');
        if($expense_type=='work'){
          $bill_data['work_id'] = $this->post('work_id');
        }else{
          $bill_data['work_id'] = 0;
        }
        $bill_data['bill_credit_ac'] = $this->post('expense_head');
      }elseif($bill_data['bill_type']=='subcontract'){
        $bill_data['subcontract_id'] = $this->post('contract_id');
        $bill_data['bill_credit_ac'] = "8"; //Subcontract Payments
        // Select Work
        $bill_data['work_id'] = $this->Subcontracts->select_subcontract("sc.work_id",array("sc.contract_id"=>$bill_data['subcontract_id']))->row()->work_id;
      }
      $bill_data['bill_date'] = date('Y-m-d',strtotime($this->post('bill_date')));
      $bill_data['bill_no'] = $this->post('bill_no');
      $bill_data['bill_gross_amount'] = $this->post('payable_amount');
      $bill_data['bill_tax_amount'] = $bill_data['bill_tds_amount'] = 0;
      if($this->post('tax_percent')){
        $tax_data = $this->Settings->select_tax_types('*',array("tax_id"=>$this->post('tax_percent')))->row();
        $bill_data['bill_tax_percent'] = $this->post('tax_percent');
        $bill_data['bill_tax_amount'] = $bill_data['bill_gross_amount']*$tax_data->tax_percentage/100;
      }
      if($this->post('bill_gross_amount')){
        $bill_data['bill_gross_amount'] = $this->post('bill_gross_amount');
      }
      if($this->post('bill_tax_amount')){
        $bill_data['bill_tax_amount'] = $this->post('bill_tax_amount');
      }
      if($this->post('bill_tds_amount')){
        $bill_data['bill_tds_amount'] = $this->post('bill_tds_amount');
      }
      $bill_data['bill_amount'] = $bill_data['bill_gross_amount'] + $bill_data['bill_tax_amount'];
      $bill_data['bill_payable_amount'] = $bill_data['bill_amount'];
      if($this->post('consignee')){
        $bill_data['bill_consignee_name'] = $this->post('consignee');
      }
      if($this->post('bill_remarks')){
        $bill_data['bill_remarks'] = $this->post('bill_remarks');
      }
      $bill_data['updated_date'] = date('Y-m-d H:i:s');
      $bill_data['updated_by'] = $this->post('user_id');

      $bill_result =  $this->Bills->update_bills($bill_data);
      $flash_data['status'] = $bill_result;
      if ($flash_data['status'] == 1) {
        $message = [
          'status' => TRUE,
          'message' => 'Bill 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_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
      }

      // Calculate & Update Bill Total
      $this->bills_management->calculate_bill_total($bill_data['bill_id']);
      $this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code

    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Bill ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function delete_bill_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && $this->post('bill_id')!="" && $this->post('bill_id') !== NULL ) {

      $bill_data['bill_id'] = $this->post('bill_id');
      $bill_data['delete_status'] = 1;

      $bill_result =  $this->Bills->update_bills($bill_data);
      $flash_data['status'] = $bill_result;
      if ($flash_data['status'] == 1) {
        $message = [
          'status' => TRUE,
          'message' => 'Bill 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_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
      }
      // Calculate & Update Bill Total
      $this->bills_management->calculate_bill_total($bill_data['bill_id']);
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Bill ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }

  public function select_bills_get($reference_type,$bill_type="")
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL) {

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $data['b.created_by'] = $user_id;
      if($this->get('work_id')){
        $data['b.work_id'] = $this->get('work_id');
      }
      if($reference_type=='expense'){
        $data['b.bill_type'] = 'expense';
        if($bill_type=='office'){
          $data['b.work_id'] = 0;
        }else{
          $data['b.work_id !='] = 0;
        }
        $result	= $this->Bills->select_bills("b.*,tt.tax_percentage,ah1.acc_head_name as expense_head_name,u.user_alias,wc.work_name",$data,'','','',$this->config->item('select_data_entry_approval'));
      }
      $total_amount = 0;
      if ($result->num_rows() > 0) {
        $message = array();
        $j = 0;
        foreach ($result->result() as $row):

          if($reference_type=='expense'){
            if($row->work_id!=0){
              $expense_type="Work Expense";
            }else{
              $expense_type="Office Expense";
            }

            if($row->bill_payment_status==1){
              $bill_payment_status="Paid";
            }elseif($row->bill_payment_status==2){
              $bill_payment_status="Partially Paid";
            }else{
              $bill_payment_status="Not Paid";
            }

            if($row->bill_attachment!=''){
              $bill_attachment=base_url().'uploads/bills/'.$row->bill_attachment;
            }else{
              $bill_attachment="";
            }

            $message[$j]['bill_id']=$row->bill_id;
            $message[$j]['bill_date']=date('d-m-Y',strtotime($row->bill_date));
            $message[$j]['bill_date_2']=date('M d, Y',strtotime($row->bill_date));
            $message[$j]['expense_type']=$expense_type;
            $message[$j]['expense_head_name']=$row->expense_head_name;
            $message[$j]['bill_no']=$row->bill_no;
            $message[$j]['consignee']=$row->bill_consignee_name;
            $message[$j]['gross_amount']=$row->bill_gross_amount;
            $message[$j]['tax_percent']=$row->bill_tax_percent;
            $message[$j]['tax_percentage']=$row->tax_percentage;
            $message[$j]['tax_amount']=$row->bill_tax_amount;
            $message[$j]['payable_amount']=round($row->bill_payable_amount,$this->config->item('Currency_amount_decimals_2'));
            $message[$j]['total_paid']=round($row->bill_total_paid,$this->config->item('Currency_amount_decimals_2'));
            $message[$j]['balance_amount']=round($row->bill_balance_amount,$this->config->item('Currency_amount_decimals_2'));
            $message[$j]['payment_status']=$bill_payment_status;
            $message[$j]['remarks']=$row->bill_remarks;
            $message[$j]['work_name']=$row->work_name;
            $message[$j]['created_by']=$row->user_alias;
            $message[$j]['created_date']=date('d-m-Y',strtotime($row->created_date));
            $message[$j]['expense_head_id']=$row->bill_credit_ac;
            $message[$j]['work_id']=$row->work_id;
            $message[$j]['payment_status_flag']=$row->bill_payment_status;
            $message[$j]['bill_attachment']=$bill_attachment;
            $message[$j]['entry_approval_status']=$row->entry_approval_status;

            $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 Bills 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_bill_details_get($reference_type)
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL && $this->get('bill_id')!="" && $this->get('bill_id') !== NULL) {

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $data['b.created_by'] = $user_id;
      if($this->get('bill_id')){
        $data['b.bill_id'] = $this->get('bill_id');
      }
      if($reference_type=='expense'){
        $data['b.bill_type'] = 'expense';
        $result	= $this->Bills->select_bills("b.*,tt.tax_percentage,ah1.acc_head_name as expense_head_name,u.user_alias,wc.work_name",$data,'','','',$this->config->item('select_data_entry_approval'));
      }
      $total_amount = 0;
      if ($result->num_rows() > 0) {

        foreach ($result->result() as $row):
          $tr_reference_type = "";
          if($reference_type=='expense'){
            $tr_reference_type = $reference_type."_bill";
            if($row->work_id!=0){
              $expense_type="Work Expense";
            }else{
              $expense_type="Office Expense";
            }

            if($row->bill_payment_status==1){
              $bill_payment_status="Paid";
            }elseif($row->bill_payment_status==2){
              $bill_payment_status="Partially Paid";
            }else{
              $bill_payment_status="Not Paid";
            }

            $json_data['bill_id']=$row->bill_id;
            $json_data['bill_date']=date('d-m-Y',strtotime($row->bill_date));
            $json_data['expense_type']=$expense_type;
            $json_data['expense_head_name']=$row->expense_head_name;
            $json_data['bill_no']=$row->bill_no;
            $json_data['consignee']=$row->bill_consignee_name;
            $json_data['tax_percent']=$row->bill_tax_percent;
            $json_data['tax_percentage']=$row->tax_percentage;
            $json_data['payable_amount']=$row->bill_payable_amount;
            $json_data['total_paid']=$row->bill_total_paid;
            $json_data['balance_amount']=$row->bill_balance_amount;
            $json_data['payment_status']=$bill_payment_status;
            $json_data['remarks']=$row->bill_remarks;
            $json_data['work_name']=$row->work_name;
            $json_data['created_by']=$row->user_alias;
            $json_data['created_date']=date('d-m-Y',strtotime($row->created_date));
            $json_data['expense_head_id']=$row->bill_credit_ac;
            $json_data['work_id']=$row->work_id;
            $json_data['payment_status_flag']=$row->bill_payment_status;

          }
          $bill_transactions = $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,", array("ats.reference_id" => $row->bill_id, "ats.reference_type" => $tr_reference_type),$tr_reference_type);
          $transactions = array();
          $j = 0;
          foreach ($bill_transactions->result() as $row):

            $transactions[$j]['transaction_id'] = $row->transaction_id;
            $transactions[$j]['tr_date'] = date('d-m-Y',strtotime($row->tr_date));
            $transactions[$j]['tr_amount']=$row->tr_amount;
            $transactions[$j]['debit_account']=$row->debit_account;
            // $transactions[$j]['tr_reference_no'] = $row->tr_reference_no;
            // $transactions[$j]['tr_remarks'] = $row->tr_remarks;
            $transactions[$j]['tr_debit_acc']=$row->tr_debit_acc;
            $transactions[$j]['created_user']=$row->created_user;
            $transactions[$j]['entry_approval_status']=$row->tr_entry_approval_status;

            $j++;

          endforeach;

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

}
