<?php

require APPPATH . '/libraries/REST_Controller.php';

use Restserver\Libraries\REST_Controller;

class Transferitem extends REST_Controller
{

    /**
     * Get All Data from this method.
     *
     * @return Response
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('counter_model');
        $this->load->model('mcounter_model');
        $this->load->model('transfer_model');
    }

    /**
     * Get All Data from this method.
     *
     * @return Response
     */
    public function index_get($id = 0)
    {
        $t_type = $this->get('t_type');
        if (!empty($id)) {
            
            if($t_type=='Yes'){
                $values = $this->transfer_model->get_trasfer_m_product_list($id);
                $data          = array();
                foreach ($values as $row) {
                    $nestad_data = array();
                    $nestad_data['row_id']  = $row['sti_id'];
                    $nestad_data['product_code']  = $row['product_mat_code'];
                    $nestad_data['product_name']  = $row['product_mat_name'];
                    $nestad_data['unit_code']  = $row['product_mat_unit'];
                    //$nestad_data[]  = $row['uom_cost'];
                    $nestad_data['product_retail_pirce']  = $row['product_retail_pirce'];
                    $nestad_data['quantity']  = $row['quantity'];
                    $nestad_data['product_cost']  = $row['product_cost'];
                    $data[] = $nestad_data;
                }
                
            }else{
                
                $values = $this->transfer_model->get_trasfer_product_list($id);
                $data          = array();
                foreach ($values as $row) {
                    $nestad_data = array();
                    $nestad_data['row_id']  = $row['sti_id'];
                    $nestad_data['product_code']  = $row['product_code'];
                    $nestad_data['product_name']  = $row['product_name'];
                    $nestad_data['unit_code']  = $row['unit_code'];
                    //$nestad_data[]  = $row['uom_cost'];
                    $nestad_data['product_retail_pirce']  = $row['product_retail_pirce'];
                    $nestad_data['quantity']  = $row['quantity'];
                    $nestad_data['product_cost']  = $row['product_cost'];
                    $data[] = $nestad_data;
                }
            }

            
            
        } else {
            $data = $this->db->get("stock_transfer_itemm")->result();
        }
        $response = array(
            'result' => $data,
            'status' => 1,
        );
        $this->response($data, REST_Controller::HTTP_OK);
    }

    public function productsearch_get()
    {
        $search_key_val = $this->get('search_string');
        $this->db->select("o.*,p.product_name,p.product_code");
        $this->db->from('batch_product o');
        $this->db->join("product p", "p.product_id = o.product_id", "inner");
        $this->db->where("o.batch_status", 1);
        $this->db->like('p.product_name', $search_key_val, 'after');
        $this->db->or_like('p.product_code', $search_key_val, 'after');
        //$this->db->or_where("o.batch_status = 1 AND  o.batch_ref_number LIKE '$search_key_val%'");
        $this->db->group_by('o.batch_id');
        $this->db->limit(5);
        $query = $this->db->get();
        $datar = $query->result_array();
        $data = array();
        foreach ($query->result_array() as $r) {
            $stock = $this->counter_model->get_stock_balance_batch('', $r['product_id'], $r['batch_id']);
            $nested_data = array(
                'id' => $r['batch_id'],
                'text' => $r['product_name'] . '(' . $r['product_code'] . ')' . ", BATCH  " . $r['batch_ref_number'] . ", COST RS." . $r['product_cost'] . ", STOCK " . $stock,
            );
            $data[] = $nested_data;
        }

        //return $query->result_array();

        $this->response($data, REST_Controller::HTTP_OK);
    }
    
    

    /**
     * Get All Data from this method.
     *
     * @return Response
     */
    public function index_post()
    {

        $batch_id = $this->post('product_id');
        $batch_id = $this->post('product_id');
        $odr_id = $this->post('odr_id');
        $req_qty = $this->post('req_qty');
        $sale_cost = $this->post('sale_cost');
        $product_code = $this->post('product_code');
        $t_type = $this->post('t_type');
        if($t_type=='Yes'){
            
            $price_cost = $this->transfer_model->get_m_product_price_cost_new($batch_id);
            $stock = $this->mcounter_model->get_stock_balance_batch('',$price_cost['product_id'], $batch_id);
            if ($stock < $req_qty) {
                $response = array(
                    'msg' => 'OUT OF STOCK',
                    'status' => 0,
                    'rr'=>$price_cost
                );
            } else {
                 $data = array(
                    'stm_id' => $odr_id,
                    'product_id' => $price_cost['product_id'],
                    'quantity' => $req_qty,
                    'product_cost' => $price_cost['product_cost'],
                    'product_retail_pirce' => 0,
                    'product_wholsale_pirce' => 0,
                    'product_credit_pirce' => 0,
                    'product_code' => $price_cost['product_mat_code'],
                    'batch_id' => $batch_id,
                    'batch_code' => $price_cost['batch_ref_number'],
                );
                $result = $this->transfer_model->save_m_trasfer_item($data);
                if ($result === FALSE) {
                    $response = array(
                        'result' => $data,
                        'status' => 0,
                    );
                } else {
                    $response = array(
                        'result' => $data,
                        'status' => 1,
                        'msg' => 'Item successfully added.',
                    );
                }
            }
            $this->response($response, REST_Controller::HTTP_OK);
            
            
        }
        else{
            
            $this->db->select("p.*,p.product_id,p.product_name,p.product_code,p.product_type_id");
            $this->db->from('product p');
            $this->db->where("(p.product_code LIKE '".$product_code."%' ESCAPE '!')");
            $this->db->limit(1);
            $query = $this->db->get();
            if($query->num_rows()==1){
                $product_row = $query->row_array();
                if($product_row['product_type_id']==2){
                     $this->db->select("bfp_id,bfp_batch_code");
                    $this->db->from('batch_final_product');
                    $this->db->where("bfp_id", $batch_id);
                    $query = $this->db->get();
                    $stock = 0;
                    $bfp_batch_code = '';
                    if($query->num_rows()==1){
                        $batch_final_product = $query->row_array();
                        $stock = $this->counter_model->getFinalValueAddedProductStockBalance('', $product_row['product_id'], $batch_final_product['bfp_batch_code']);
                        $bfp_batch_code = $batch_final_product['bfp_batch_code'];
                    }
                    
                    $price_cost = $this->transfer_model->get_product_price_cost_new($product_row['product_id']);

                    //$stock = $this->counter_model->getFinalValueAddedProductStockBalance('', $product_row['product_id'], $batch_id);
                    if ($stock < $req_qty) {
                        $response = array(
                            'msg' => 'OUT OF STOCK',
                            'status' => 0,
                        );
                    } else {
                         $data = array(
                            'stm_id' => $odr_id,
                            'product_id' => $product_row['product_id'],
                            'quantity' => $req_qty,
                            'product_cost' => ($sale_cost)?$sale_cost:0,
                            'product_retail_pirce' => 0,
                            'product_wholsale_pirce' => 0,
                            'product_credit_pirce' => 0,
                            'product_code' => $product_code,
                            'batch_id' => $batch_id,
                            'batch_code' => $bfp_batch_code,
                        );
                        $result = $this->transfer_model->save_trasfer_item($data);
                        if ($result === FALSE) {
                            $response = array(
                                'result' => $data,
                                'status' => 0,
                            );
                        } else {
                            $response = array(
                                'result' => $data,
                                'status' => 1,
                                'msg' => 'Item successfully added.',
                            );
                        }
                    }
                    $this->response($response, REST_Controller::HTTP_OK);
                }else{
                    /*
                    $this->db->select("o.*,p.product_id,p.product_name,p.product_code,p.product_type_id");
                    $this->db->from('production_batch_items o');
                    $this->db->join("product p", "p.product_id = o.pbi_product_id", "inner");
                    //$this->db->where("o.stock_clean", 0);
                    $this->db->where("(p.product_code LIKE '".$product_code."%' ESCAPE '!')");
                    $this->db->where("o.finish_status",1);
                    */
                    
                    $this->db->select("pbi_product_id,pbi_id,pbi_ref_no,pbi_unit_cost");
                    
                    $this->db->from('production_batch_items');
                    $this->db->where("pbi_id", $batch_id);
                    
                    $this->db->limit(1);
                    $query = $this->db->get();
                    $production_batch_items = $query->row_array();
                    
                    //$price_cost = $this->transfer_model->get_product_price_cost_new($production_batch_items['pbi_product_id']);

                    $stock = $this->counter_model->getFinalProductStockBalance('', $production_batch_items['pbi_product_id'], $batch_id);
                    if ($stock < $req_qty) {
                        $response = array(
                            'msg' => 'OUT OF STOCK',
                            'status' => 0,
                        );
                    } else {
                         $data = array(
                            'stm_id' => $odr_id,
                            'product_id' => $production_batch_items['pbi_product_id'],
                            'quantity' => $req_qty,
                            'product_cost' => ($sale_cost)?$sale_cost:$production_batch_items['pbi_unit_cost'],
                            'product_retail_pirce' => 0,
                            'product_wholsale_pirce' => 0,
                            'product_credit_pirce' => 0,
                            'product_code' => $product_code,
                            'batch_id' => $batch_id,
                            'batch_code' => $production_batch_items['pbi_ref_no'],
                        );
                        $result = $this->transfer_model->save_trasfer_item($data);
                        if ($result === FALSE) {
                            $response = array(
                                'result' => $data,
                                'status' => 0,
                            );
                        } else {
                            $response = array(
                                'result' => $data,
                                'status' => 1,
                                'msg' => 'Item successfully added.',
                            );
                        }
                    }
                    $this->response($response, REST_Controller::HTTP_OK);
                    
                }
            }
            
            
        }
        
        
    }

    /**
     * Get All Data from this method.
     *
     * @return Response
     */
    public function index_put($id)
    {
        $input = $this->put();
        $this->db->update('products', $input, array('id' => $id));

        $this->response(['Product updated successfully.'], REST_Controller::HTTP_OK);
    }

    /**
     * Get All Data from this method.
     *
     * @return Response
     */
    public function index_delete($id)
    {
        
        $t_type = $this->delete('t_type');
        $explode = explode("_",$id);
        //$this->delete('id')
         if($explode[1]=='Yes'){
                $result = $this->transfer_model->delete_m_trasfer_item($explode[0]);
              $st = array('status' => 1, 'msg' => 'Transfer item deletedm');
         }else{
             $result = $this->transfer_model->delete_trasfer_item($explode[0]);
              $st = array('status' => 1, 'msg' => 'Transfer item deleted');
         }
        
        
        //$st = array('status' => 1, 'msg' => 'Transfer item deleted');

        //$this->db->delete('products', array('id' => $id));

        $this->response($st, REST_Controller::HTTP_OK);
    }
}
