<?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 Purchase 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('Supplier_model', 'Supplier');
    $this->load->model('Purchase_bill_model', 'Purchases');
    $this->load->model('Purchase_order_model', 'Purchase_order');
    $this->load->model('Purchase_request_model', 'Purchase_request');
    $this->load->model('Material_model', 'Material');
    $this->load->model('Stock_model', 'Stock');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->library('Stock_management','stock_management');
    $this->load->library('Bills_management','bills_management');
    $this->load->library('Projects_management','projects_management');
  }
  public function index_get()
  {
    //      Default Method
    $this->orders_get();
  }
  // Create Purchase Order / Request
  public function create_order_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && $this->post('work_id')!="" && $this->post('work_id') !== NULL) {
      $user_details = $this->User->select_user("",array("user_id"=>$this->post('user_id')));
      if($user_details->row()->branch_id!=0){
        $material_select = 'm.material_unit_price_branch as material_unit_price';
      }else{
        $material_select = 'm.material_unit_price';
      }
      $work_id = $this->post('work_id');
      $project_details = $this->Work->select_work("work_name",array("work_id"=>$work_id));

      $data['project_stage_id'] = $this->projects_management->get_project_stage_id($work_id);

      $data['created_date'] = date('Y-m-d H:i:s');
      $data['created_by'] = $this->post('user_id');
      if($this->post('type')=='order'){
        $data['supplier_id'] = $this->post('supplier');
        $data['vehicle_no'] = $this->post('vehicle_number');
        if($this->post('delivery_date')){
          $data['delivery_date'] = date('Y-m-d H:i:s',strtotime($this->post('delivery_date')));
        }
        if($this->post('invoice_number')){
          $data['reference_no'] = $this->post('invoice_number');
        }
        $data['remarks'] = 'Purchase Slip';
        $data['order_date'] = date('Y-m-d');
        if(isset($_POST['total_billed_amount'])){
          $data['total_billed_amount'] = $this->post('total_billed_amount');
        }
        if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
          $data['entry_approval_status'] = 0;
        }
      }elseif($this->post('type')=='bill'){
        $data['supplier_id'] = $this->post('supplier');
        $data['vehicle_no'] = $this->post('vehicle_number');
        if($this->post('invoice_number')){
          $data['bill_invoice_no'] = $this->post('invoice_number');
        }
        if($this->post('tax_percentage')){
          $data['bill_tax_percent'] = $this->post('tax_percentage');
        }
        $data['remarks'] = 'Purchase Bill';
        $data['purchase_date'] = date('Y-m-d');
        if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
          $data['entry_approval_status'] = 0;
        }
        if($this->post('image')){
          $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));
        }
      }else{
        $data['remarks'] = 'Purchase Request';
        $data['request_date'] = date('Y-m-d');
      }

      $json_data = $this->post('items');
      $items = json_decode($json_data, true);
      if (!empty($items)) {
        // Get Location Id of this Work Id
        $loc_data = $this->Stock->select_stock_locations("sl.*",array("sl.work_id"=>$work_id));
        if($loc_data->num_rows()==1){
          $data['location_id'] = $loc_data->row()->location_id;
          // Create Purchase Order / Request
          if($this->post('type')=='order'){
            $result = $this->Purchase_order->insert_purchase_order($data);
          }elseif($this->post('type')=='bill'){
            $result = $this->Purchases->insert_purchase($data);
          }else{
            $result = $this->Purchase_request->insert_purchase_request($data);
          }
          if($result['status']==1){
            if($this->post('type')=='order'){
              $item_data['order_id'] = $result['insert_id'];
            }elseif($this->post('type')=='bill'){
              $item_data['purchase_id'] = $result['insert_id'];
            }else{
              $item_data['request_id'] = $result['insert_id'];
            }
            $items_count = sizeof($items);
            $total_est_amount = $grand_total_tax_amount = 0;
            for ($i = 0; $i < $items_count; $i++) {
              $material_data = $this->Material->select_material("unit,".$material_select,array('material_id'=>$items[$i]['material_id']))->row();
              $item_data['material_id'] = $items[$i]['material_id'];
              $item_data['unit_id']  = $material_data->unit;
              $item_data['quantity'] = $items[$i]['quantity'];

              if($this->post('type')=='bill'){
                if(isset($items[$i]['item_code'])){
                  $item_data['item_code'] = $items[$i]['item_code'];
                }else{
                  $item_data['item_code'] = '';
                }
                $item_data['tax_percent'] = $item_data['tax_amount'] = $unit_tax_amount = 0;
                $item_data['unit_price']  = $items[$i]['unit_price'];
                if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise'){
                  if(isset($items[$i]['tax_percent'])){
                    $item_data['tax_percent'] = $items[$i]['tax_percent'];
                    $tax_percent = $this->Settings->select_tax_types('*',array("tax_id"=>$item_data['tax_percent']))->row()->tax_percentage;
                  }elseif(isset($data['bill_tax_percent'])){
                    $item_data['tax_percent'] = $tax_percent = $data['bill_tax_percent'];
                  }else{
                    $item_data['tax_percent'] = $tax_percent = 0;
                  }
                  $unit_tax_amount = round($item_data['unit_price']*$tax_percent/100,$this->config->item('Currency_amount_decimals_2'));
                }
                $item_data['tax_amount'] = round($unit_tax_amount*$items[$i]['quantity'],$this->config->item('Currency_amount_decimals_2'));
                $grand_total_tax_amount += $item_data['tax_amount'];
                $item_data['total_amount']  = ($items[$i]['unit_price']*$items[$i]['quantity'])+$item_data['tax_amount'];
                $total_est_amount += ($items[$i]['unit_price']*$items[$i]['quantity']);
              }else{
                $item_data['unit_price']  = $material_data->material_unit_price;
                $item_data['total_amount']  = $item_data['unit_price']*$item_data['quantity'];
                $total_est_amount += $item_data['total_amount'];
              }

              if(isset($items[$i]['description'])){
                $item_data['description'] = $items[$i]['description'];
              }

              if($this->post('type')=='order'){
                $result2 = $this->Purchase_order->create_purchase_order_item($item_data);
              }elseif($this->post('type')=='bill'){
                $result2 = $this->Purchases->create_purchase_item($item_data);
              }else{
                $result2 = $this->Purchase_request->create_purchase_request_item($item_data);
              }
            }
            // Update Total Est Amount
            if($this->post('type')=='order'){
              $order_update_data['order_id'] = $result['insert_id'];
              $order_update_data['total_est_amount'] = $total_est_amount;
              $result3 = $this->Purchase_order->update_purchase_order($order_update_data);
              $success_msg = "Purchase Slip";
            }elseif($this->post('type')=='bill'){
              if($this->post('paid_amount')>0) {
                $transaction_data['reference_id'] = $result['insert_id'];
                $transaction_data['reference_type'] = "purchase_bill";
                $transaction_data['tr_type'] = "purchase_bill_transaction";
                $transaction_data['created_date'] = date('Y-m-d H:i:s');
                $transaction_data['created_by'] = $this->post('user_id');
                $transaction_data['tr_payment_part'] = 1; //Bill Payment
                $transaction_data['tr_amount'] = $this->post('paid_amount');
                $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'] = 5;//Supplier Payments
                $transaction_data['tr_description'] = "Purchase Bill Transaction";
                $transaction_data['tr_mode'] = $this->post('payment_mode');
                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);

              }

              $purchase_update_data['purchase_id'] = $result['insert_id'];
              $purchase_update_data['bill_total_amount'] = $total_est_amount;
              $purchase_update_data['bill_tax_amount'] = $grand_total_tax_amount;
              $purchase_update_data['bill_payable_amount'] = $purchase_update_data['bill_total_amount']+$purchase_update_data['bill_tax_amount'];
              $purchase_update_data['bill_save_status'] = 1;
              $result3 = $this->Purchases->update_purchase($purchase_update_data);
              $this->bills_management->calculate_purchase_bill_total($purchase_update_data['purchase_id']);
              $this->stock_management->update_stock_register($purchase_update_data['purchase_id'],$data['created_by']);
              $success_msg = "Purchase Bill";
            }else{
              $request_update_data['request_id'] = $result['insert_id'];
              $request_update_data['total_est_amount'] = $total_est_amount;
              $result3 = $this->Purchase_request->update_purchase_request($request_update_data);
              $success_msg = "Purchase Request";

              //       Send Push Notification to Project Engineer
              $project_engineers = $this->User->select_user("",array("user_role"=>15))->result();
              foreach($project_engineers as $key=>$value){
                $firebase_data['token'] = $value->firebase_token;
                $firebase_data['title'] = "You Have Some Pending Purchase Request to Approve!";
                $firebase_data['message'] = $user_details->row()->user_alias." Added New Purchase Request in Project: ".$project_details->row()->work_name.". Please Take Action to Approve.";
                $firebase_result = $this->User->push_firebase($firebase_data);
              }
            }


            $message = [
              'status' => TRUE,
              'message' => $success_msg.' Saved Successfully'
            ];
            $this->response($message, REST_Controller::HTTP_CREATED); // 201
          }else{
            $message = [
              "status" => FALSE,
              "message" => "There Has been Some Error Occurred. Please Try Again."
            ];
            $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
          }
        }else{
          $message = [
            "status" => FALSE,
            "message" => "Your Project Site Location Not Added. Please Contact Administrator."
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
        }
      }else{
        $message = [
          'status' => FALSE,
          'message' => 'No Items Uploaded'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Work ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  // Create Purchase Order / Request
  public function update_order_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && ($this->post('type')=='request' || ($this->post('type')!='request' && $this->post('work_id')!="" && $this->post('work_id') !== NULL))) {
      $user_details = $this->User->select_user("",array("user_id"=>$this->post('user_id')));
      if($user_details->row()->branch_id!=0){
        $material_select = 'm.material_unit_price_branch as material_unit_price';
      }else{
        $material_select = 'm.material_unit_price';
      }
      $work_id = $this->post('work_id');
      $project_details = $this->Work->select_work("work_name",array("work_id"=>$work_id));

      $data['updated_date'] = date('Y-m-d H:i:s');
      $data['updated_by'] = $this->post('user_id');
      if($this->post('type')=='order'){
        $data['order_id'] = $this->post('order_id');
        $data['supplier_id'] = $this->post('supplier');
        $data['vehicle_no'] = $this->post('vehicle_number');
        if($this->post('invoice_number')){
          $data['reference_no'] = $this->post('invoice_number');
        }
        // $data['remarks'] = 'Purchase Slip';
        // $data['order_date'] = date('Y-m-d');
        if(isset($_POST['total_billed_amount'])){
          $data['total_billed_amount'] = $this->post('total_billed_amount');
        }

      }elseif($this->post('type')=='bill'){
        $data['purchase_id'] = $this->post('bill_id');
        $data['supplier_id'] = $this->post('supplier');
        $data['vehicle_no'] = $this->post('vehicle_number');
        if($this->post('invoice_number')){
          $data['bill_invoice_no'] = $this->post('invoice_number');
        }
      }else{
        $data['request_id'] = $this->post('request_id');
        // $data['remarks'] = 'Purchase Request';
        // $data['request_date'] = date('Y-m-d');
        if($this->post('approval_status') && $this->post('approval_status')!=''){
          $data['approval_status_1'] = $this->post('approval_status');
          $data['approved_by_1'] = $this->post('user_id');
          $data['approved_date_1'] = date('Y-m-d H:i:s');
        }
      }

      $json_data = $this->post('items');
      $items = json_decode($json_data, true);
      if (!empty($items)) {
        // Update Purchase Order / Request
        if($this->post('type')=='order'){
          $result = $this->Purchase_order->update_purchase_order($data);
        }elseif($this->post('type')=='bill'){
          $result = $this->Purchases->update_purchase($data);
        }else{
          $result = $this->Purchase_request->update_purchase_request($data);
        }
        if($result==1){
          if($this->post('type')=='order'){
            $item_data['order_id'] = $this->post('order_id');
            $existing_items = $this->Purchase_order->select_purchase_order_items("item_id",array("poi.order_id"=>$item_data['order_id']))->result();
          }elseif($this->post('type')=='bill'){
            $item_data['purchase_id'] = $this->post('bill_id');
            $existing_items = $this->Purchases->select_purchase_items("item_id",array("pi.purchase_id"=>$item_data['purchase_id']))->result();
          }else{
            $item_data['request_id'] = $this->post('request_id');
            $existing_items = $this->Purchase_request->select_purchase_request_items("item_id",array("pri.request_id"=>$item_data['request_id']))->result();
          }
          $existing_items_array = array();
          foreach($existing_items as $key=>$value){
            $existing_items_array[] = $value->item_id;
          }

          $items_count = sizeof($items);
          $total_est_amount = 0;
          for ($i = 0; $i < $items_count; $i++) {
            $material_data = $this->Material->select_material("unit,".$material_select,array('material_id'=>$items[$i]['material_id']))->row();
            $item_data['material_id'] = $items[$i]['material_id'];
            $item_data['unit_id']  = $material_data->unit;
            $item_data['quantity'] = $items[$i]['quantity'];
            if($this->post('type')=='bill'){
              $item_data['unit_price']  = $items[$i]['unit_price'];
              $item_data['total_amount']  = $items[$i]['unit_price']*$items[$i]['quantity'];
            }else{
              $item_data['unit_price']  = $material_data->material_unit_price;
              $item_data['total_amount']  = $item_data['unit_price']*$item_data['quantity'];
            }
            if(isset($items[$i]['description'])){
              $item_data['description'] = $items[$i]['description'];
            }
            $total_est_amount += $item_data['total_amount'];
            if($this->post('type')=='order'){
              if(isset($items[$i]['item_id']) && $items[$i]['item_id']!=''){
                // Update Existing Data
                $item_data['item_id'] = $items[$i]['item_id'];
                $item_result =  $this->Purchase_order->update_purchase_order_item($item_data);
                // Delete from Existing Array
                if (($key = array_search($item_data['item_id'], $existing_items_array)) !== false) {
                  unset($existing_items_array[$key]);
                }
              }else{
                // Create New Data
                unset($item_data['item_id']);
                $item_result =  $this->Purchase_order->create_purchase_order_item($item_data);
              }
            }elseif($this->post('type')=='bill'){
              if(isset($items[$i]['item_id']) && $items[$i]['item_id']!=''){
                // Update Existing Data
                $item_data['item_id'] = $items[$i]['item_id'];
                $item_result =  $this->Purchases->update_purchase_item($item_data);
                // Delete from Existing Array
                if (($key = array_search($item_data['item_id'], $existing_items_array)) !== false) {
                  unset($existing_items_array[$key]);
                }
              }else{
                // Create New Data
                unset($item_data['item_id']);
                $item_result =  $this->Purchases->create_purchase_item($item_data);
              }
            }else{
              if(isset($items[$i]['item_id']) && $items[$i]['item_id']!=''){
                // Update Existing Data
                $item_data['item_id'] = $items[$i]['item_id'];
                $item_result =  $this->Purchase_request->update_purchase_request_item($item_data);
                // Delete from Existing Array
                if (($key = array_search($item_data['item_id'], $existing_items_array)) !== false) {
                  unset($existing_items_array[$key]);
                }
              }else{
                // Create New Data
                unset($item_data['item_id']);
                $item_result =  $this->Purchase_request->create_purchase_request_item($item_data);
              }
            }
          }
          // Check existing items array have value, if so, delete those items
          if(sizeof($existing_items_array)>0){
            foreach($existing_items_array as $item_id){
              $item_delete_data['item_id'] = $item_id;
              $item_delete_data['delete_status'] = 1;
              if($this->post('type')=='order'){
                $item_result =  $this->Purchase_order->update_purchase_order_item($item_delete_data);
              }elseif($this->post('type')=='bill'){
                $item_result =  $this->Purchases->update_purchase_item($item_delete_data);
              }else{
                $item_result =  $this->Purchase_request->update_purchase_request_item($item_delete_data);
              }
            }
          }
          // Update Total Est Amount
          if($this->post('type')=='order'){
            $order_update_data['order_id'] = $this->post('order_id');
            $order_update_data['total_est_amount'] = $total_est_amount;
            $result3 = $this->Purchase_order->update_purchase_order($order_update_data);
            $success_msg = "Purchase Slip";
          }elseif($this->post('type')=='bill'){
            $purchase_update_data['purchase_id'] = $this->post('bill_id');
            $purchase_update_data['bill_total_amount'] = $purchase_update_data['bill_payable_amount'] = $total_est_amount;
            $purchase_update_data['bill_save_status'] = 1;
            $result3 = $this->Purchases->update_purchase($purchase_update_data);
            $this->bills_management->calculate_purchase_bill_total($purchase_update_data['purchase_id']);
            $this->stock_management->update_stock_register($purchase_update_data['purchase_id']);
            $success_msg = "Purchase Bill";
          }else{
            $request_update_data['request_id'] = $this->post('request_id');
            $request_update_data['total_est_amount'] = $total_est_amount;
            $result3 = $this->Purchase_request->update_purchase_request($request_update_data);
            $success_msg = "Purchase Request";
          }
          $message = [
            'status' => TRUE,
            'message' => $success_msg.' Details Updated Successfully'
          ];
          $this->response($message, REST_Controller::HTTP_CREATED); // 201
        }else{
          $message = [
            "status" => FALSE,
            "message" => "There Has been Some Error Occurred. Please Try Again."
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
        }
      }else{
        $message = [
          'status' => FALSE,
          'message' => 'No Items Uploaded'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Work ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  // Purchase Order or Request
  public function orders_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL && $this->get('work_id')!="" && $this->get('work_id') !== NULL) {
      $type = 'all';
      if($this->get('type') && $this->get('user_id')!=""){
        if($this->get('type')=='order'){
          $type = 'order';
        }elseif($this->get('type')=='bill'){
          $type = 'bill';
        }elseif($this->get('type')=='request'){
          $type = 'request';
        }
      }
      $user_details = $this->User->select_user("",array("user_id"=>$this->get('user_id')));

      $order_where = $request_where = $bill_where = array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      if($user_details->num_rows()==1 && $user_details->row()->user_role!=15){ //Project Engneer
        $order_where['po.created_by'] = $user_id;
        $request_where['pr.created_by'] = $user_id;
        $bill_where['p.created_by'] = $user_id;
      }
      if($this->get('work_id')){
        $order_where['sl.work_id'] = $this->get('work_id');
        $request_where['sl.work_id'] = $this->get('work_id');
        $bill_where['sl.work_id'] = $this->get('work_id');
      }
      $purchase_order = $this->Purchase_order->select_purchase_order("po.*,u.user_alias,s.supplier_name,s.supplier_id,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$order_where,$this->config->item('select_data_entry_approval'));
      $purchase_bill = $this->Purchases->select_purchase("p.*,u.user_alias,s.supplier_name,s.supplier_id,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$bill_where,$this->config->item('select_data_entry_approval'));
      $purchase_request = $this->Purchase_request->select_purchase_request("pr.*,u.user_alias,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$request_where);
      if ($purchase_order->num_rows() > 0 || $purchase_bill->num_rows() > 0 || $purchase_request->num_rows() > 0) {
        $message = array();
        $j = 0;
        if($type=='all' || $type=='order'){
          foreach ($purchase_order->result() as $row):

            if($row->purchase_bill_id !=0){
              $bill_created_status = 1;
            }else{
              $bill_created_status = 0;
            }

            $message[$j]['order_id'] = $row->order_id;
            $message[$j]['type'] = 'order';
            $message[$j]['order_date'] = date('d-m-Y',strtotime($row->order_date));
            $message[$j]['delivery_date'] = ($row->delivery_date!="0000-00-00 00:00:00")?date('d-m-Y',strtotime($row->delivery_date)):"";
            $message[$j]['supplier_id'] = $row->supplier_id;
            $message[$j]['supplier_name'] = $row->supplier_name;
            $message[$j]['bill_created_status'] = $bill_created_status;
            $message[$j]['work_id'] = $row->work_id;
            $message[$j]['vehicle_no'] = $row->vehicle_no;
            $message[$j]['created_by'] = $row->user_alias;
            $message[$j]['created_date'] = date('d-m-Y',strtotime($row->created_date));
            $message[$j]['approval_status'] = '';
            $message[$j]['corrected_status'] = 0;
            $message[$j]['approval_enabled'] = 0;
            $message[$j]['show_created_user'] = 0;
            $message[$j]['editable_status'] = 0;
            $message[$j]['total_amount'] = $row->total_est_amount;
            $message[$j]['entry_approval_status']=$row->entry_approval_status;

            $j++;
          endforeach;
        }
        if($type=='all' || $type=='bill'){
          foreach ($purchase_bill->result() as $row):

            $message[$j]['order_id'] = $row->purchase_id;
            $message[$j]['type'] = 'bill';
            $message[$j]['order_date'] = date('d-m-Y',strtotime($row->purchase_date));
            $message[$j]['supplier_id'] = $row->supplier_id;
            $message[$j]['supplier_name'] = $row->supplier_name;
            $message[$j]['bill_created_status'] = 0;
            $message[$j]['work_id'] = $row->work_id;
            $message[$j]['vehicle_no'] = $row->vehicle_no;
            $message[$j]['created_by'] = $row->user_alias;
            $message[$j]['created_date'] = date('d-m-Y',strtotime($row->created_date));
            $message[$j]['approval_status'] = '';
            $message[$j]['corrected_status'] = 0;
            $message[$j]['approval_enabled'] = 0;
            $message[$j]['show_created_user'] = 0;
            $message[$j]['editable_status'] = 0;
            $message[$j]['total_amount'] = $row->bill_payable_amount;
            $message[$j]['entry_approval_status']=$row->entry_approval_status;

            $j++;
          endforeach;
        }
        if($type=='all' || $type=='request'){
          foreach ($purchase_request->result() as $row):

            $message[$j]['order_id'] = $row->request_id;
            $message[$j]['type'] = 'request';
            $message[$j]['order_date'] = date('d-m-Y',strtotime($row->request_date));
            $message[$j]['supplier_id'] = '';
            $message[$j]['supplier_name'] = '';
            $message[$j]['bill_created_status'] = 0;
            $message[$j]['work_id'] = $row->work_id;
            $message[$j]['vehicle_no'] = '';
            if($user_details->num_rows()==1 && $user_details->row()->user_role==15){ //Project Engneer
              $message[$j]['show_created_user'] = 1;
            }else{
              $message[$j]['show_created_user'] = 0;
            }
            $message[$j]['created_by'] = $row->user_alias;
            $message[$j]['created_date'] = date('d-m-Y',strtotime($row->created_date));
            if($row->approval_status_1==1){
              $message[$j]['approval_status'] = 'Approved';
            }elseif($row->approval_status_1==2){
              $message[$j]['approval_status'] = 'Rejected';
            }else{
              $message[$j]['approval_status'] = 'Pending';
            }
            if($this->config->item('Purchase_purchase_request_second_approval')==1){
              if($row->approval_status_2==1){
                $message[$j]['approval_status_2'] = 'Approved';
              }elseif($row->approval_status_2==2){
                $message[$j]['approval_status_2'] = 'Rejected';
              }else{
                $message[$j]['approval_status_2'] = 'Pending';
              }
            }
            if($row->corrected_status==1){
              $message[$j]['corrected_status'] = 1;
            }else{
              $message[$j]['corrected_status'] = 0;
            }

            $message[$j]['approval_enabled'] = 0;
            $message[$j]['editable_status'] = 0;
            if($row->approval_status_1==0 && $user_details->num_rows()==1 && $user_details->row()->user_role==15){ //Project Engneer
              $message[$j]['approval_enabled'] = 1;
              $message[$j]['editable_status'] = 1;
            }
            $message[$j]['total_amount'] = 0;
            $message[$j]['entry_approval_status']=1;


            $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 Purchase Slips / Requests Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Work ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  // get order/reuqest details
  public function order_details_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL && $this->get('order_id')!="" && $this->get('order_id') !== NULL) {

      $user_details = $this->User->select_user("",array("user_id"=>$this->get('user_id')));

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      if($this->get('type')!="" && $this->get('type') !== NULL){
        $type = $this->get('type');
      }else{
        $type = 'order';
      }
      $response_msg='';
      if($user_details->num_rows()==1 && $user_details->row()->user_role!=15){ //Project Engneer
        if($type=='order'){
          $data['po.created_by'] = $user_id;
        }elseif($type=='bill'){
          $data['p.created_by'] = $user_id;
        }else{
          $data['pr.created_by'] = $user_id;
        }

        if($this->get('work_id')){
          $data['sl.work_id'] = $this->get('work_id');
        }
      }

      if($type=='order'){
        $data['po.order_id'] = $this->get('order_id');
        $result	= $this->Purchase_order->select_purchase_order("po.*,u.user_alias,s.supplier_name,s.supplier_id,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$data,$this->config->item('select_data_entry_approval'));
      }elseif($type=='bill'){
        $data['p.purchase_id'] = $this->get('order_id');
        $result	= $this->Purchases->select_purchase("p.*,u.user_alias,s.supplier_name,s.supplier_id,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$data,$this->config->item('select_data_entry_approval'));
      }else{
        $data['pr.request_id'] = $this->get('order_id');
        $result	= $this->Purchase_request->select_purchase_request("pr.*,u.user_alias,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$data);
      }
      if ($result->num_rows() == 1) {
        $message = array();
        $j = 0;
        $result_data = $result->row();
        if($type=='order' && $result_data->purchase_bill_id !=0){
          $bill_created_status = 1;
        }else{
          $bill_created_status = 0;
        }
        $items = array();
        if($type=='order'){
          $items_data = $this->Purchase_order->select_purchase_order_items('',array('poi.order_id'=>$result_data->order_id))->result();
        }elseif($type=='bill'){
          $items_data = $this->Purchases->select_purchase_items('',array('p.purchase_id'=>$result_data->purchase_id),'','','',$this->config->item('select_data_entry_approval'))->result();
        }else{
          $items_data = $this->Purchase_request->select_purchase_request_items('',array('pri.request_id'=>$result_data->request_id))->result();
        }
        foreach ($items_data as $key => $value) {
          $items[$j]['item_id'] = $value->item_id;
          $items[$j]['material_id'] = $value->material_id;
          $items[$j]['material_name'] = $value->material_name;
          $items[$j]['unit_id'] = $value->unit_id;
          $items[$j]['unit_name'] = $value->unit_name;
          $items[$j]['quantity'] = $value->quantity;
          $items[$j]['description'] = $value->description;

          $j++;
        }

        if($type=='order'){
          $response_msg = "Purchase Slip";
          $message['order_id'] = $result_data->order_id;
          $message['supplier_id'] = $result_data->supplier_id;
          $message['supplier_name'] = $result_data->supplier_name;
          $message['order_date'] =  date('d-m-Y',strtotime($result_data->order_date));
          $message['vehicle_no'] = $result_data->vehicle_no;
          $message['corrected_status'] = 0;
          $message['approval_status'] = '';
          $message['approval_enabled'] = 0;
          $message['editable_status'] = 0;
          $message['total_amount'] = $result_data->total_est_amount;
          $message['entry_approval_status']=$result_data->entry_approval_status;
        }elseif($type=='bill'){
          $response_msg = "Purchase Bill";
          $message['order_id'] = $result_data->purchase_id;
          $message['supplier_id'] = $result_data->supplier_id;
          $message['supplier_name'] = $result_data->supplier_name;
          $message['order_date'] =  date('d-m-Y',strtotime($result_data->purchase_date));
          $message['vehicle_no'] = $result_data->vehicle_no;
          $message['corrected_status'] = 0;
          $message['approval_status'] = '';
          $message['approval_enabled'] = 0;
          $message['editable_status'] = 0;
          $message['total_amount'] = $result_data->bill_payable_amount;
          $message['entry_approval_status']=$result_data->entry_approval_status;
        }else{
          $response_msg = "Purchase Request";
          $message['order_id'] = $result_data->request_id;
          $message['supplier_id'] = '';
          $message['supplier_name'] = '';
          $message['order_date'] =  date('d-m-Y',strtotime($result_data->request_date));
          $message['vehicle_no'] = '';
          if($result_data->approval_status_1==1){
            $message['approval_status'] = 'Approved';
          }elseif($result_data->approval_status_1==2){
            $message['approval_status'] = 'Rejected';
          }else{
            $message['approval_status'] = 'Pending';
          }
          if($result_data->corrected_status==1){
            $message['corrected_status'] = 1;
          }else{
            $message['corrected_status'] = 0;
          }

          $message['approval_enabled'] = 0;
          $message['editable_status'] = 0;
          if($result_data->approval_status_1==0 && $user_details->num_rows()==1 && $user_details->row()->user_role==15){ //Project Engneer
            $message['approval_enabled'] = 1;
            $message['editable_status'] = 1;
          }
          $message['total_amount'] = 0;
        }
        if($user_details->num_rows()==1 && $user_details->row()->user_role!=15){ //Project Engneer
          $message['show_created_user'] = 1;
        }else{
          $message['show_created_user'] = 0;
        }
        $message['created_by'] = $result_data->user_alias;
        $message['created_date'] = date('d-m-Y',strtotime($result_data->created_date));
        $message['type'] = $type;
        $message['bill_created_status'] = $bill_created_status;
        $message['status'] = TRUE;
        $message['message'] = $response_msg.' Details Retrieved Successfully';
        $message['items'] = $items;
        $message['entry_approval_status']=1;
        $this->set_response($message, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
      } else {
        $message = [
          'status' => FALSE,
          'message' => $response_msg.' Not Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Work ID, Order ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function request_approval_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && $this->post('request_id')!="" && $this->post('request_id') !== NULL && $this->post('approval')!="" && $this->post('approval') !== NULL) {

      $data['request_id'] = $this->post('request_id');
      $data['approval_status_1'] = $this->post('approval');
      $data['updated_date'] = date('Y-m-d H:i:s');
      $data['approved_by_1'] = $this->post('user_id');
      $data['approved_date_1'] = date('Y-m-d H:i:s');

      $result =   $this->Purchase_request->update_purchase_request($data);
      if($data['approval_status_1']==1){
        $response_type="Approved";
      }else{
        $response_type="Rejected";
      }
      if($result == 1) {
        $message = [
          'status' => TRUE,
          'message' => 'Purchase Request '.$response_type.' Succesfully'
        ];
        $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, Request ID, Approval Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }

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

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      if($this->get('supplier_type') && $this->get('supplier_type')!=''){
        $data['supplier_type'] = $this->get('supplier_type');
      }
      $suppliers	= $this->Supplier->select_supplier("*",$data);
      if ($suppliers->num_rows() > 0) {
        $message = array();
        $j = 0;
        foreach ($suppliers->result() as $row):

          $message[$j]['id'] = $row->supplier_id;
          $message[$j]['name'] = $row->supplier_name;
          $message[$j]['address'] = $row->supplier_address;

          $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 Suppliers 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_material_categories_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL) {
      $user_details = $this->User->select_user("",array("user_id"=>$this->get('user_id')));
      if($user_details->row()->branch_id!=0){
        $material_select = 'm.material_unit_price_branch as material_unit_price';
      }else{
        $material_select = 'm.material_unit_price';
      }
      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $categories	= $this->Material->select_category("",$data);
      if ($categories->num_rows() > 0) {
        $message = array();
        $j = 0;
        foreach ($categories->result() as $row):

          $message[$j]['category_id'] = $row->cat_id;
          $message[$j]['category_name'] = $row->cat_name;
          $message[$j]['materials'] = $this->Material->select_material("material_id,material_name,unit_id,unit_name,category as category_id,cat_name as category_name,".$material_select,array("m.category"=>$row->cat_id))->result_array();

          $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 Materials 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_materials_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL) {
      $user_data = $this->User->select_user("",array("user_id"=>$this->get('user_id')));
      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $materials	= $this->Material->select_material("",$data);
      if ($materials->num_rows() > 0) {
        $message = array();
        $j = 0;
        foreach ($materials->result() as $row):

          $message[$j]['material_id'] = $row->material_id;
          $message[$j]['material_name'] = $row->material_name;
          $message[$j]['unit_id'] = $row->unit;
          $message[$j]['unit_name'] = $row->unit_name;
          $message[$j]['category_id'] = $row->category;
          $message[$j]['category_name'] = $row->cat_name;
          $message[$j]['unit_price'] = $row->material_unit_price;
          $message[$j]['item_code'] = $row->item_code;
          $message[$j]['tax_percent'] = $row->material_tax_percent;

          if ($this->config->item('Material_sale_price_category_enable') == 1 && $user_data->num_rows()==1){
            $where_data['mp.material_id'] = $row->material_id;
            $where_data['mp.branch_id'] = $user_data->row()->branch_id;
            $material_sale_price = $this->Material->select_material_prices("",$where_data);
            if($material_sale_price->num_rows()==1){
              $material_sale_price = $material_sale_price->row();
              $message[$j]['sale_price1'] = $material_sale_price->sale_price1;
              $message[$j]['sale_price2'] = $material_sale_price->sale_price2;
              $message[$j]['sale_price3'] = $material_sale_price->sale_price3;
              $message[$j]['sale_price4'] = $material_sale_price->sale_price4;
              $message[$j]['sale_price5'] = $material_sale_price->sale_price5;
              $message[$j]['sale_price6'] = $material_sale_price->sale_price6;
            }else{
              $message[$j]['sale_price1'] = 0;
              $message[$j]['sale_price2'] = 0;
              $message[$j]['sale_price3'] = 0;
              $message[$j]['sale_price4'] = 0;
              $message[$j]['sale_price5'] = 0;
              $message[$j]['sale_price6'] = 0;
            }
          }

          $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 Materials 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 delivery_challans_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL && $this->get('work_id')!="" && $this->get('work_id') !== NULL) {

      $user_details = $this->User->select_user("",array("user_id"=>$this->get('user_id')));
      $data = array();
      $data['pdc.created_by'] = $this->get('user_id');
      $data['sl.work_id'] = $this->get('work_id');
      $delivery_challans = $this->Purchases->select_delivery_challan("pdc.*,po.order_date,u.user_alias,s.supplier_name,s.supplier_id,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,u.user_role as created_user_role_id",$data,$this->config->item('select_data_entry_approval'));
      if ($delivery_challans->num_rows() > 0) {
        $message = array();
        $j = 0;
        foreach ($delivery_challans->result() as $row):

          $message[$j]['challan_id'] = $row->challan_id;
          $message[$j]['challan_date'] = date('d-m-Y',strtotime($row->challan_date));
          $message[$j]['challan_no'] = $row->challan_no;
          $message[$j]['supplier_name'] = $row->supplier_name;
          $message[$j]['work_id'] = $row->work_id;
          $message[$j]['delivery_date'] = date('d-m-Y',strtotime($row->delivery_date));
          $message[$j]['gate_entry'] = $row->gate_entry;
          $message[$j]['qc_stamp'] = $row->qc_stamp;
          $message[$j]['created_by'] = $row->user_alias;
          $message[$j]['created_date'] = date('d-m-Y',strtotime($row->created_date));

          $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 Challans Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Work ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function challan_details_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL && $this->get('challan_id')!="" && $this->get('challan_id') !== NULL) {

      $user_details = $this->User->select_user("",array("user_id"=>$this->get('user_id')));

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');

      $data['pdc.challan_id'] = $this->get('challan_id');
      $result = $this->Purchases->select_delivery_challan("pdc.*,po.order_date,u.user_alias,s.supplier_name,s.supplier_id,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,u.user_role as created_user_role_id",$data,$this->config->item('select_data_entry_approval'));
      if ($result->num_rows() == 1) {
        $message = array();
        $j = 0;
        $result_data = $result->row();
        $items = array();
        $items_data = $this->Purchases->select_delivery_challan_items('',array('pdci.challan_id'=>$result_data->challan_id))->result();
        foreach ($items_data as $key => $value) {
          $items[$j]['item_id'] = $value->item_id;
          $items[$j]['material_id'] = $value->material_id;
          $items[$j]['material_name'] = $value->material_name;
          $items[$j]['unit_id'] = $value->unit_id;
          $items[$j]['unit_name'] = $value->unit_name;
          $items[$j]['quantity'] = $value->delivery_qty;

          $j++;
        }

        $message['challan_id'] = $result_data->challan_id;
        $message['supplier_id'] = $result_data->supplier_id;
        $message['supplier_name'] = $result_data->supplier_name;
        $message['challan_date'] = date('d-m-Y',strtotime($result_data->challan_date));
        $message['challan_no'] = $result_data->challan_no;
        $message['supplier_name'] = $result_data->supplier_name;
        $message['work_id'] = $result_data->work_id;
        $message['delivery_date'] = date('d-m-Y',strtotime($result_data->delivery_date));
        $message['gate_entry'] = $result_data->gate_entry;
        $message['qc_stamp'] = $result_data->qc_stamp;

        $message['status'] = TRUE;
        $message['message'] = 'Challan Details Retrieved Successfully';
        $message['items'] = $items;
        $message['entry_approval_status']=1;
        $this->set_response($message, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
      } else {
        $message = [
          'status' => FALSE,
          'message' => $response_msg.' Not Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Work ID, Order ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function create_delivery_challan_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && $this->post('order_id')!="" && $this->post('order_id') !== NULL) {
      $user_details = $this->User->select_user("",array("user_id"=>$this->post('user_id')));

      $data['order_id'] = $this->post('order_id');
      $data['challan_no'] = $this->post('challan_no');
      $data['challan_date'] = date('Y-m-d',strtotime($this->post('challan_date')));
      $data['delivery_date'] = date('Y-m-d',strtotime($this->post('delivery_date')));
      $data['gate_entry'] = strtoupper($this->post('gate_entry'));
      $data['qc_stamp'] = strtoupper($this->post('qc_stamp'));
      $data['created_date'] = date('Y-m-d H:i:s');
      $data['created_by'] = $this->post('user_id');

      $json_data = $this->post('items');
      $items = json_decode($json_data, true);
      if (!empty($items)) {

        $result = $this->Purchases->insert_delivery_challan($data);

        if($result['status']==1){
          $item_data['challan_id'] = $result['insert_id'];
          $items_count = sizeof($items);
          for ($i = 0; $i < $items_count; $i++) {
            if($items[$i]['quantity']>0){
              $item_data['order_item_id'] = $items[$i]['item_id'];
              $item_data['delivery_qty'] = $items[$i]['quantity'];
              $result2 = $this->Purchases->create_delivery_challan_item($item_data);
            }
          }

          $message = [
            'status' => TRUE,
            'message' => 'Delivery Challan Added Successfully'
          ];
          $this->response($message, REST_Controller::HTTP_CREATED); // 201
        }else{
          $message = [
            "status" => FALSE,
            "message" => "There Has been Some Error Occurred. Please Try Again."
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
        }
      }else{
        $message = [
          'status' => FALSE,
          'message' => 'No Items Uploaded'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Order ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }

}
