<?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 Stock 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('Stock_model', 'Stock');
    $this->load->library('Stock_management','stock_management');
    $this->load->library('Projects_management','projects_management');
  }
  public function index_get()
  {
    //     Default Method
    $this->current_stock_get();
  }

  //  Get Stock List
  public function current_stock_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL) {
      $error = 0;
      $data=array();
      if($this->get('location_id') !== NULL && $this->get('location_id')!=""){
        $data['sr.location_id'] = $this->get('location_id');
      }else{
        if($this->get('work_id')!="" && $this->get('work_id') !== NULL){
          //          Select Stock of this Work
          $data['sl.work_id'] = $this->get('work_id');
        }else{
          $error = 1;
          $message = [
            'status' => FALSE,
            'message' => 'Required Parameters Missing . Work ID'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
        }
      }

      if($error==0){
        // Select All Available Materials in Stock
        // $this->db->where('sr.total_balance_qty >',0);
        $materials	= $this->Stock->select_stock_register("GROUP_CONCAT(sr.stock_id) AS stock_ids,sr.stock_id,sr.purchase_supplier_id,sr.unit_price,s.supplier_name,sr.unit,sr.material_id,mu.unit_name,mu.unit_id,m.item_code,m.material_name,sr.location_id,sl.location_name,sl.location_type,sl.work_id,sr.purchase_item_id",$data,array('sr.material_id','sr.unit','sr.purchase_supplier_id','sr.unit_price','sr.location_id'));
        if ($materials->num_rows() > 0) {
          $message = array();
          $j = 0;
          foreach ($materials->result() as $row):

            $data['sr.material_id'] = $row->material_id;
            $data['sr.location_id'] = $row->location_id;
            $data['sr.unit'] = $row->unit;
            $data['sr.purchase_supplier_id'] = $row->purchase_supplier_id;
            $data['sr.unit_price like'] = $row->unit_price;
            $this->db->where('sr.stock_id IN (' . $row->stock_ids . ')');
            $available_stock_qty = round($this->Stock->select_stock_register("COALESCE(SUM(sr.total_balance_qty),0) as total", $data)->row()->total, 0);

            if($available_stock_qty>0){
              $message[$j]['stock_id'] = $row->stock_id;
              $message[$j]['material_id'] = $row->material_id;
              $message[$j]['unit_id'] = $row->unit;
              $message[$j]['unit_name'] = $row->unit_name;
              $message[$j]['stock_name'] = $row->material_name;
              // $message[$j]['available_qty'] = (float)$available_stock_qty;
              $message[$j]['available_qty'] = $available_stock_qty;
              $message[$j]['location_id'] = $row->location_id;
              $message[$j]['location_name'] =  $row->location_name;

              $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 {
          if($this->get('location_id') !== NULL && $this->get('location_id')!=""){
            $message = [
              'status' => FALSE,
              'message' => 'No Material Stock Found in Selected Location'
            ];
          }else{
            $message = [
              'status' => FALSE,
              'message' => 'No Material Stock Found in Your Work Site'
            ];
          }
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
        }
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  //  Stock Locations
  public function locations_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL && $this->get('work_id')!="" && $this->get('work_id') !== NULL) {

      $data=array();
      //          Select All Locations Except of this Work
      $data['sl.work_id !='] = $this->get('work_id');
      // $data['sl.location_type'] = 'ware_house';
      // Get Location Id of this Work Id
      $where['sl.work_id'] = $this->get('work_id');

      $loc_data = $this->Stock->select_stock_locations("sl.*",$where);
      if($loc_data->num_rows()==1){

        $locations	= $this->Stock->select_stock_locations("sl.*",$data);
        if ($locations->num_rows() > 0) {
          $message = array();
          $j = 0;
          foreach ($locations->result() as $row):

            if($row->location_type=='work_site'){
              $location_type="Work Site";
            }else{
              $location_type="Ware House";
            }

            $message[$j]['location_id'] = $row->location_id;
            $message[$j]['location_name'] = $row->location_name." [".$location_type."]";
            $message[$j]['location_ype'] = $location_type;

            $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 Stock Locations Found'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
        }
      }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' => '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 consumption_post()
  {

    $json_data = $this->post('items');
    $items = json_decode($json_data, true);
    if (!empty($items)) {
      $stock_cons_data = $this->Stock->select_stock_consumption("MAX(cons_group_id) as last_group_id");
      if($stock_cons_data->num_rows()==1){
        $data['cons_group_id'] = ($stock_cons_data->row()->last_group_id)+1;
      }else{
        $data['cons_group_id'] = 1;
      }
      $data['created_by'] = $this->post('user_id');
      $data['work_id'] = $this->post('work_id');
      $data['project_stage_id'] = $this->projects_management->get_project_stage_id($data['work_id']);

      if($this->post('date') && $this->post('date')!=''){
        $data['consumption_date'] = date('Y-m-d',strtotime($this->post('date')));
      }else{
        $data['consumption_date'] = date('Y-m-d');
      }
      $data['created_date'] = date('Y-m-d H:i:s');
      $data['remarks'] = "";
      if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
        $data['entry_approval_status'] = 0;
      }
      if($data['created_by']!="" && is_numeric($data['created_by'])) {
        $items_count = sizeof($items);
        for ($i = 0; $i < $items_count; $i++) {
          $stock_id = $items[$i]['stock_id'];
          $stock_details = $this->Stock->select_stock_register("sr.purchase_supplier_id,sr.unit_price",array("sr.stock_id"=>$stock_id))->row();
          $data2['purchase_supplier_id'] = $stock_details->purchase_supplier_id;
          $data2['unit_price'] = $stock_details->unit_price;
          $data2['location_id'] = $items[$i]['location_id'];
          $data2['material_id'] = $items[$i]['material_id'];
          $data2['unit_id']  = $items[$i]['unit_id'];
          $total_stock_consumed_qty = $items[$i]['quantity'];
          // Get Stock ID From Stock Register for this Material
          $stock_register = $this->Stock->select_stock_register("stock_id,total_balance_qty", array("sr.location_id"=>$data2['location_id'],"sr.material_id"=>$data2['material_id'],"sr.unit"=>$data2['unit_id'],"sr.purchase_supplier_id"=>$data2['purchase_supplier_id'],"sr.unit_price like"=>$data2['unit_price'],"sr.total_balance_qty >"=>0));
          $remaining_qty = $total_stock_consumed_qty;
          foreach ($stock_register->result() as $key => $value) {
            if($remaining_qty>0){
              $available_stock_item_qty = $value->total_balance_qty;
              if($remaining_qty>$available_stock_item_qty){
                $data['consumption_qty']  = $available_stock_item_qty;
              }else{
                $data['consumption_qty']  = $remaining_qty;
              }

              $remaining_qty = $remaining_qty-$data['consumption_qty'];

              $data['stock_id'] = $value->stock_id;
              // Update Stock Consumption
              $result = $this->Stock->insert_stock_consumption($data);
              //  Update Stock Register
              $result2 = $this->stock_management->calculate_stock_balance($data['stock_id']);
            }
          }

        }

        $message = [
          'status' => TRUE,
          'message' => 'Material Consumption Saved Successfully'
        ];
        $this->response($message, REST_Controller::HTTP_CREATED); // 201

      }else{
        $message = [
          "status" => FALSE,
          "message" => "User ID Required"
        ];
        $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
    }
  }
  public function consumption_history_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL && $this->get('work_id')!="" && $this->get('work_id') !== NULL) {

      $data=array();
      $data['sc.created_by'] = $this->get('user_id');
      $data['sc.work_id'] = $this->get('work_id');
      $consumption	= $this->Stock->select_stock_consumption("COALESCE(SUM(sc.consumption_qty),0) as total_consumed_qty,sc.*,sr.unit_price,sr.material_id,m.material_name,mu.unit_name,sr.unit,sr.location_id,u.user_alias as created_user,wc.work_name",$data,array("sc.consumption_date","sc.cons_group_id","sr.material_id","sr.unit"),$this->config->item('select_data_entry_approval'));
      if ($consumption->num_rows() > 0) {
        $message = array();
        $j = 0;
        foreach ($consumption->result() as $row):
          if($row->cons_id!=''){
            $message[$j]['id'] = $row->cons_id;
            $message[$j]['date'] = date('d-m-Y',strtotime($row->consumption_date));
            $message[$j]['material'] = $row->material_name;
            $message[$j]['unit'] = $row->unit_name;
            $message[$j]['consumed_qty'] = $row->total_consumed_qty;
            $message[$j]['entry_approval_status']=$row->entry_approval_status;

            $j++;
          }

        endforeach;
        if(sizeof($message)>0){
          $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 Stock Consumptions Found'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
        }
      } else {
        $message = [
          'status' => FALSE,
          'message' => 'No Stock Consumptions 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 transfer_post()
  {

    $json_data = $this->post('items');
    $items = json_decode($json_data, true);
    if (!empty($items)) {
      $stock_trans_data = $this->Stock->select_stock_transfers("MAX(trans_group_id) as last_group_id");
      if($stock_trans_data->num_rows()==1){
        $data['trans_group_id'] = ($stock_trans_data->row()->last_group_id)+1;
      }else{
        $data['trans_group_id'] = 1;
      }
      $data['transfer_date'] = date('Y-m-d',strtotime($this->post('date')));
      $data['created_by'] = $this->post('user_id');
      if($this->config->item('Mobile_App_enable_data_entry_approval')==1){
        $data['entry_approval_status'] = 0;
        $stock_data['entry_approval_status'] = 0;
      }
      $work_id = $this->post('work_id');
      // 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['transferred_to_loc_id'] = $loc_data->row()->location_id;

        $bill_data['transferred_to_loc_id'] = $data['transferred_to_loc_id'];
        $bill_data['transferred_from_loc_id'] = $items[0]['location_id'];
        $bill_data['bill_date'] = date('Y-m-d',strtotime($this->post('date')));
        $bill_data['created_date'] = date('Y-m-d H:i:s');
        $bill_data['created_by'] = $this->post('user_id');
        $bill_result = $this->Stock->insert_stock_transfer_bill($bill_data);

        $data['transfer_bill_id'] = $bill_result['insert_id'];

        $work_data_1=$this->Work->select_work("w.work_id",array("work_id"=>$data['transferred_to_loc_id']));
        if($work_data_1->num_rows()==1){
          $data['transfer_to_project_stage_id'] = $data['transferred_to_loc_id'];
        }

        $data['created_date'] = date('Y-m-d H:i:s');
        $data['remarks'] = "";

        $items_count = sizeof($items);
        for ($i = 0; $i < $items_count; $i++) {
          $stock_id = $items[$i]['stock_id'];
          $stock_details = $this->Stock->select_stock_register("sr.purchase_supplier_id,sr.unit_price",array("sr.stock_id"=>$stock_id))->row();
          $data['transferred_from_loc_id'] = $items[$i]['location_id'];

          $work_data_2=$this->Work->select_work("w.work_id",array("work_id"=>$data['transferred_from_loc_id']));
          if($work_data_2->num_rows()==1){
            $data['transfer_from_project_stage_id'] = $data['transferred_from_loc_id'];
          }
          if($this->config->item('Stock_stock_register_material_based_only')!=1){
            $data2['purchase_supplier_id'] = $stock_details->purchase_supplier_id;
            $data2['unit_price'] = $stock_details->unit_price;
          }
          $data2['material_id'] = $items[$i]['material_id'];
          $data2['unit_id']  = $items[$i]['unit_id'];
          $total_stock_transferred_qty = $items[$i]['quantity'];
          // Get Stock ID From Stock Register for this Material
          if($this->config->item('Stock_stock_register_material_based_only')==1){
            $stock_register = $this->Stock->select_stock_register("sr.*", array("sr.location_id" => $data['transferred_from_loc_id'], "sr.material_id" => $data2['material_id'], "sr.unit" => $data2['unit_id'],  "sr.total_balance_qty >" => 0));
          }else{
            $stock_register = $this->Stock->select_stock_register("sr.*", array("sr.location_id" => $data['transferred_from_loc_id'], "sr.material_id" => $data2['material_id'], "sr.unit" => $data2['unit_id'], "sr.purchase_supplier_id" => $data2['purchase_supplier_id'], "sr.unit_price like" => $data2['unit_price'], "sr.total_balance_qty >" => 0));
          }
          $remaining_qty = $total_stock_transferred_qty;
          foreach ($stock_register->result() as $key => $value) {
            if($remaining_qty>0){
              $available_stock_item_qty = $value->total_balance_qty;
              if($remaining_qty>$available_stock_item_qty){
                $data['transferred_qty']  = $available_stock_item_qty;
              }else{
                $data['transferred_qty']  = $remaining_qty;
              }

              $remaining_qty = $remaining_qty-$data['transferred_qty'];
              $data['transferred_from_stock_id'] = $value->stock_id;

              // Insert Transferred Stock as New Stock Entry
              $stock_data['location_id'] = $data['transferred_to_loc_id'];
              $stock_data['purchase_supplier_id'] = $value->purchase_supplier_id;
              $stock_data['stock_name'] = $value->stock_name;
              $stock_data['material_id'] = $value->material_id;
              $stock_data['unit'] = $value->unit;
              $stock_data['unit_price'] = $value->unit_price;
              $stock_data['total_transferred_in_qty'] = $data['transferred_qty'];
              $stock_data['created_date'] = date('Y-m-d H:i:s');
              $stock_data['created_by'] = $this->post('user_id');
              $result3 = $this->Stock->insert_stock_register($stock_data);

              $data['transferred_to_stock_id'] = $result3['insert_id'];
              // Update Stock Consumption
              $result = $this->Stock->insert_stock_transfer($data);
              //  Update Stock Register
              $this->stock_management->calculate_stock_balance($data['transferred_from_stock_id']);
              //  Update Stock Register
              $this->stock_management->calculate_stock_balance($result3['insert_id']);

              $this->stock_management->calculate_stock_transfer_bill($bill_result['insert_id']);
            }
          }
        }
        $message = [
          'status' => TRUE,
          'message' => 'Stock Transfer Saved Successfully'
        ];
        $this->response($message, REST_Controller::HTTP_CREATED); // 201
      }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
    }
  }
  public function transfer_history_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL && $this->get('work_id')!="" && $this->get('work_id') !== NULL) {

      $data=array();
      $data['st.created_by'] = $this->get('user_id');
      $data['sl2.work_id'] = $this->get('work_id');
      $transfer	= $this->Stock->select_stock_transfers("COALESCE(SUM(st.transferred_qty),0) as total_transferred_qty,st.*,sr1.unit_price,sr1.material_id,m.material_name,mu.unit_name,sr1.unit,sl1.location_name as transferred_from_loc_name,sl2.location_name as transferred_to_loc_name,u.user_alias as created_user",$data,array("st.transfer_date","st.trans_group_id","sr1.material_id","sr1.unit"),$this->config->item('select_data_entry_approval'));
      if ($transfer->num_rows() > 0) {
        $message = array();
        $j = 0;
        foreach ($transfer->result() as $row):
          if($row->transfer_id!=''){
            $message[$j]['id'] = $row->transfer_id;
            $message[$j]['date'] = date('d-m-Y',strtotime($row->transfer_date));
            $message[$j]['material'] = $row->material_name;
            $message[$j]['unit'] = $row->unit_name;
            $message[$j]['transferred_qty'] = $row->total_transferred_qty;
            $message[$j]['transferred_from'] = $row->transferred_from_loc_name;
            $message[$j]['entry_approval_status']=$row->entry_approval_status;

            $j++;
          }

        endforeach;

        if(sizeof($message)>0){
          $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 Stock Transfers Found'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
        }
      } else {
        $message = [
          'status' => FALSE,
          'message' => 'No Stock Transfers 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
    }
  }
}
