<?php

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

use Restserver\Libraries\REST_Controller;

class Transfer 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');
        $this->load->model('stock_counter_model');
        ini_set('upload_max_filesize', '60M');     
        ini_set('max_execution_time', '999');
        ini_set('memory_limit', '128M');
        ini_set('post_max_size', '60M'); 
    }

    /**
     * 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'){
                $data = $this->db->get_where("stock_m_transfer_master", ['stm_id' => $id])->row_array();
            }else{
               $data = $this->db->get_where("stock_transfer_master", ['stm_id' => $id])->row_array(); 
            }
        } else {
            if($t_type=='Yes'){
                $data = $this->db->get("stock_m_transfer_master")->result();
            }else{
                $data = $this->db->get("stock_transfer_master")->result();
            }
            
        }
        $response = array(
            'result' => $data,
            'status' => 1,
        );
        $this->response($response, REST_Controller::HTTP_OK);
    }
    
    
     public function productsearch_get()
    {
        
        $search_key_val = $this->get('search_string');
        $t_type = $this->get('t_type');
        if($t_type=='Yes'){
            $this->db->select("o.*,p.product_mat_id,p.product_mat_name,p.product_mat_code");
            $this->db->from('batch_product o');
            $this->db->join("product_material p", "p.product_mat_id = o.product_id AND p.product_mat_type_id = 1", "inner");
            $this->db->where("o.batch_status",1);
            //$this->db->where("p.product_type",1);
            //$this->db->where("o.stock_clean", 0);
            //$this->db->where("o.finish_status",1);
            $this->db->like('p.product_mat_code', $search_key_val, 'after');//after
            $this->db->or_like('p.product_mat_name', $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(100);
            $query = $this->db->get();
            //echo $this->db->last_query(); die();
            $datar = $query->result_array();
            $data = array();
            foreach ($query->result_array() as $r) {
                $stock = $this->mcounter_model->get_stock_balance_batch('', $r['product_id'], $r['batch_id']);
                if($stock>0){
                    $nested_data = array(
                        'id' => $r['batch_id'],
                        'product_code' => $r['product_mat_code'],
                        'text' => $r['product_mat_name'].'('.$r['product_mat_code'].')'.", BATCH  " . $r['batch_ref_number'] . ", COST RS." . $r['product_cost'] . ", STOCK " . $stock,
                    );
                    $data[] = $nested_data;
                }else{
                   // $data[] = array();
                }
            }
            //return $query->result_array();
            $this->response($data, REST_Controller::HTTP_OK);
            
        }
        else{
            
            $this->db->select("p.product_id,p.product_name,p.product_code,p.product_type_id");
            $this->db->from('product p');
            $this->db->where("(p.product_name` LIKE '%".$search_key_val."%' OR p.product_code LIKE '%".$search_key_val."%')");
            //
            $this->db->limit(1);
            $query = $this->db->get();
            //echo $this->db->last_query();
            
            $data = array();
            
            if($query->num_rows()==1){
                $product_row = $query->row_array();
                if($product_row['product_type_id']==2){
                    $this->db->select("b.bfp_id,b.bfp_batch_code");
                    $this->db->from('production_convert c');
                    //$this->db->join("product p", "c.pc_prodcut_id = p.product_id", "inner");
                    $this->db->join("batch_final_product b", "c.converted_batch_id = b.bfp_id", "left");
                    $this->db->where("b.bfp_status", 1);
                    //$this->db->where("o.finish_status",1);
                    $this->db->limit(100);
                    $query = $this->db->get();
                    //echo $this->db->last_query();
                    $datar = $query->result_array();
                    foreach ($query->result_array() as $r) {
                        $stock = $this->counter_model->getFinalValueAddedProductStockBalance('', $product_row['product_id'], $r['bfp_batch_code']);
                        //$stock = 1;
                        if($stock>0){
                            $nested_data = array(
                                'id' => $r['bfp_id'],
                                'product_code' => $product_row['product_code'],
                                'text' => $product_row['product_name'].'('.$product_row['product_code'].')'.", BATCH  " . $r['bfp_batch_code'] . ", COST RS. 0, STOCK " . $stock,
                            );
                            $data[] = $nested_data;
                        }else{
                           // $data[] = array();
                        }
                    }
                }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_name` LIKE '".$search_key_val."%' ESCAPE '!' OR p.product_code LIKE '".$search_key_val."%' ESCAPE '!')");
                    $this->db->where("o.finish_status",1);
                    $this->db->limit(200);
                    $query = $this->db->get();
                    //echo $this->db->last_query();
                    $datar = $query->result_array();
                    foreach ($query->result_array() as $r) {
                        
                        $stock = $this->counter_model->getFinalProductStockBalance('', $r['pbi_product_id'], $r['pbi_id']);
                        //$stock = 1;
                        if($stock>0){
                            $nested_data = array(
                                'id' => $r['pbi_id'],
                                'product_code' => $r['product_code'],
                                'text' => $r['product_name'].'('.$r['product_code'].')'.", BATCH  " . $r['pbi_ref_no'] . ", COST RS. 0, STOCK " . $stock,
                            );
                            $data[] = $nested_data;
                        }else{
                           // $data[] = array();
                        }
                    }
                }
            }
            
            
            /*
            $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("o.finish_status",1);
            $this->db->where("(p.product_name` LIKE '".$search_key_val."%' ESCAPE '!' OR p.product_code LIKE '".$search_key_val."%' ESCAPE '!')");
            //$this->db->like('p.product_name', $search_key_val, 'after');//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.pbi_id');
            $this->db->limit(50);
            $query = $this->db->get();
            //echo $this->db->last_query();
            $datar = $query->result_array();
            $data = array();
            foreach ($query->result_array() as $r) {
                if($r['product_type_id']==2){
                    $stock = $this->counter_model->getFinalValueAddedProductStockBalance('', $r['pbi_product_id'], $r['pbi_ref_no']);
                    //$stock = 1;
                }else{
                    $stock = $this->counter_model->getFinalProductStockBalance('', $r['pbi_product_id'], $r['pbi_id']);
                }
                //$stock = 1;
                if($stock>0){
                    $nested_data = array(
                        'id' => $r['pbi_id'],
                        'product_code' => $r['product_code'],
                        'text' => $r['product_name'].'('.$r['product_code'].')'.", BATCH  " . $r['pbi_ref_no'] . ", COST RS." . $r['pbi_unit_cost'] . ", STOCK " . $stock,
                    );
                    $data[] = $nested_data;
                }else{
                   // $data[] = array();
                }
            }
    
            //return $query->result_array();
            */
    
            $this->response($data, REST_Controller::HTTP_OK);
        }
        
    }
    

    public function productsearchold_get()
    {
        $search_key_val = $this->get('search_string');
        $this->db->select("o.*,p.product_id,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->where("o.stock_clean", 0);
        //$this->db->where("o.finish_status",1);
        $this->db->like('p.product_name', $search_key_val, 'after');//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(50);
        $query = $this->db->get();
        //echo $this->db->last_query();
        $datar = $query->result_array();
        $data = array();
        foreach ($query->result_array() as $r) {
            $stock = $this->counter_model->get_stock_ledger_balance('', $r['product_id'], $r['batch_id']);
            if($stock>0){
                $nested_data = array(
                    'id' => $r['batch_id'],
                    'product_code' => $r['product_code'],
                    'text' => $r['product_name'].'('.$r['product_code'].')'.", BATCH  " . $r['batch_ref_number'] . ", COST RS." . $r['product_cost'] . ", STOCK " . $stock,
                );
                $data[] = $nested_data;
            }else{
               // $data[] = array();
            }
        }
        //return $query->result_array();
        $this->response($data, REST_Controller::HTTP_OK);
    }


    public function final_get()
    {
        $id=$this->get('id');
        $user_id = $this->get('user_id');
        $t_type = $this->get('t_type');
             $data=array(
	        'stm_status'=>1,
			'stm_final_by'=>$user_id,
			'stm_on'=>date("Y-m-d H:i:s"),
		);
		
		if($t_type=='Yes'){
		    $result=$this->transfer_model->update_m_transfer_master($id,$data);
    		$list=$this->transfer_model->get_m_transfer_list_items($id);
    		foreach($list as $row){
    		     $data=array(
                  'product_id'=>$row['product_id'],
                  'batch_id'=>$row['batch_id'],
                  'quantity'=>($row['quantity']*(-1)),
                  'warehouse_id'=>$row['stm_warehouse_id'],
                  'transaction_type'=>"TRANSFER",
                  'transaction_id'=>$id,
                  'user_id'=>$user_id
                  );
    		    $this->transfer_model->save_stock_lodge($data);
    		}
            $result = $this->transfer_model->get_m_transfer_info($id);
            $result['items'] = $list;
            $st = array('status' => 1, 'msg' => 'TRANSFER COMPLETED','transfer'=>$result);
            $this->response($st, REST_Controller::HTTP_OK);
		}else{
		    $result=$this->transfer_model->update_transfer_master($id,$data);
    		$list=$this->transfer_model->get_transfer_list_items($id);
    		foreach($list as $row){
    		     $data=array(
                  'product_id'=>$row['product_id'],
                  'batch_id'=>$row['batch_id'],
                  'quantity'=>($row['quantity']*(-1)),
                  'warehouse_id'=>$row['stm_warehouse_id'],
                  'transaction_type'=>"TRANSFER",
                  'transaction_id'=>$id,
                  'user_id'=>$user_id
                  );
    		    $this->transfer_model->save_stock_lodge($data);
    		}
            $result = $this->transfer_model->get_transfer_info($id);
            $result['items'] = $list;
            $st = array('status' => 1, 'msg' => 'TRANSFER COMPLETED','transfer'=>$result);
            $this->response($st, REST_Controller::HTTP_OK);
		}
		
    }

    public function remotetransfer_get($value = ''){

        $dbo = $this->load->database('admin', TRUE);
        $dbo->select("s.row_id,s.id");
        $dbo->from('stock_transfer AS s');
        $dbo->where("s.stm_status", 0);
        $q = $dbo->get();
        $datar = $q->result();
        foreach ($datar as $r) {
            
            $this->db->select("s.*");
            $this->db->from('stock_transfer_master AS s');
            $this->db->where("s.stm_id", $r->row_id);
            $this->db->where("s.stm_status", 1);
            $q2 = $this->db->get();
            if($q2->num_rows()==1){
                //echo '<pre>aaaaa ',print_r($q2->row());
            	$dbo->where('id', $r->id);
		        $dbo->update('stock_transfer',array('stm_status'=>1));
            }

        }
        $code     = $this->get('w_id');
        $url ="http://admin.lakalibh.newviableerp.com/api/get_api_transfers?w_id=".$code;
        $ch = curl_init($url);
        $headers = array(
            "Content-Type: application/json"
            );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);
        curl_close($ch);
        //header("Content-type: application/json");
        $objects = json_decode($response);
        //echo '<pre>',print_r($objects);
 
        $totalData=count($objects->transfers);
        $totalFiltered=$totalData;
        $data          = array();
        if (!empty($objects)) {
            foreach ($objects->transfers as $products) {
                $row=array();
                $status='<span class=" btn btn-xs btn-primary"> DRAFT</sapn>';
                if($products->stm_status==1){
                   $status='<span class=" btn btn-xs btn-success"> COMPLETED</sapn>'; 
                }
                
                 $grnstatus='<span class=" btn btn-xs btn-warning"> PENDING</sapn>';
                if($products->stm_receved_status==1){
                   $grnstatus='<span class=" btn btn-xs btn-success"> COMPLETED</sapn>'; 
                }
                
                $row[]               = $products->date_time;
                $row[]               = $products->stm_no;
                $row[]               = $products->stm_ref_no;
                $row[]               = $products->ad_user;
                $row[]               = $products->formname;
                $row[]               = $status;
                $row[]               = $grnstatus;

                $actdes = '';
                
                if($code=='SUPER'){
                    $option_order_details='<li><a  class="btn btn-default " data-toggle="tooltip" data-placement="bottom" title="GRN This Transfer" href="https://super.lakalibh.newviableerp.com/purchases/transfer_details?id='.$products->id.'" ><i class="fa fa-check" aria-hidden="true"> GRN</i></a></li>';
                
                }else{
                  $option_order_details="<li><a  class=\"btn btn-default \" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"GRN This Transfer\"  onClick=\"grn_this_transfer('".$products->id."')\"><i class=\"fa fa-check\" aria-hidden=\"true\"> GRN</i></a></li>";
                  
                }
                
                
                
                $update_action='';
                
                
               $action_option=''; 
              if($products->stm_status==1 || $products->stm_status==1 ){
                  $action_option=$option_order_details;
                }else{
                    $action_option=$option_order_details.$update_action;
                }
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs  dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            '.$action_option.'</ul></div>                      ';
                $row[]               = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
    
    public function remotetransferdata_get()
    {
        $id = $this->get('id');
        
        
        
        $list = $this->transfer_model->get_trasfer_product_list_api($id);
            //$result = $this->Stock_Transfer_Model->get_transfer_info($id,$db_name);
            //$result['items'] = $list;
        $responce =  array(
            "status" => 1,
            "msg" => "Success",
            "products" =>$list
        );
        $st = array('status' => 1, 'msg' => 'TRANSFER COMPLETED','products'=>$list);
        $this->response($st, REST_Controller::HTTP_OK);
    }

    function reomteupdategrn_get()
    {
        $id     = $this->get('id');
        $url ="http://admin.lakalibh.newviableerp.com/api/transfer_grn_update/".$id;
        $ch = curl_init($url);
        $headers = array(
            "Content-Type: application/json"
            );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);
        curl_close($ch);
        //header("Content-type: application/json");
        $object = json_decode($response);
        ///echo '<pre>',print_r($object); die();
        if($object->status==1){
           $row_id = $object->row_id;
            $data = array('stm_receved_status' => "1");
            $result = $this->transfer_model->update_transfer_master($row_id, $data);
            if ($result == 1) {
    
                echo json_encode(array(
                    "status" => 1,
                    "msg" => "SUCCSESS.",
    
                ));
            } else {
    
                echo json_encode(array(
                    "status" => 0,
                    "msg" => "Failed. (Error code: error-403-i)",
    
                ));
            }
        
        }else{
            echo json_encode(array(
                    "status" => 0,
                    "msg" => "Failed. (Error code: error-403-i)",
    
                ));
        }
        
    }

    /**
     * Get All Data from this method.
     *
     * @return Response
     */
    public function index_post()
    {
        //$input = $this->input->post();
        $warehouse_id = $this->post('warehouse_id');
        $ref_no = $this->post('stm_ref_no');
        $note = $this->post('note');
        $ref_no = $this->post('ref_no');
        $odr_type = $this->post('stm_to_id');
        $stm_no = $this->post('stm_no');
        $stm_by = $this->post('stm_by');
        $t_type = $this->post('t_type');
        if($t_type){
            
            $data = array(
                'stm_warehouse_id' => $warehouse_id,
                'stm_ref_no' => $ref_no,
                'stm_note' => $note,
                'stm_to_id' => $odr_type,
                'stm_no' => $stm_no,
                'stm_by' => $stm_by,
                'stm_date_time' => date("Y-m-d H:i:s"),
            );
            $this->db->select("*");
            $this->db->from('stock_m_transfer_master');
            $this->db->where("stm_no", $stm_no);
            $q2 = $this->db->get();
            if($q2->num_rows()==1){
                $response = array(
                'result' => array(),
                'status' => 0,
            );
            }else{
                $result = $this->db->insert('stock_m_transfer_master', $data);
                $data['row_id'] = $this->db->insert_id();
                if ($result === FALSE) {
                    $response = array(
                        'result' => array(),
                        'status' => 0,
                        'msg' => 'Transfer No Already exist',
                    );
                } else {
                    $response = array(
                        'result' => $data,
                        'status' => 1,
                        'msg' => 'Transfer created successfully.',
                    );
                }
            }
            $this->response($response, REST_Controller::HTTP_OK);
            
            
        }else{
            
            $data = array(
                'stm_warehouse_id' => $warehouse_id,
                'stm_ref_no' => $ref_no,
                'stm_note' => $note,
                'stm_to_id' => $odr_type,
                'stm_no' => $stm_no,
                'stm_by' => $stm_by,
                'stm_date_time' => date("Y-m-d H:i:s"),
            );
            $this->db->select("*");
            $this->db->from('stock_transfer_master');
            $this->db->where("stm_no", $stm_no);
            $q2 = $this->db->get();
            if($q2->num_rows()==1){
                $response = array(
                'result' => array(),
                'status' => 0,
            );
            }else{
                $result = $this->db->insert('stock_transfer_master', $data);
                $data['row_id'] = $this->db->insert_id();
                if ($result === FALSE) {
                    $response = array(
                        'result' => array(),
                        'status' => 0,
                        'msg' => 'Transfer No Already exist',
                    );
                } else {
                    $response = array(
                        'result' => $data,
                        'status' => 1,
                        'msg' => 'Transfer created successfully.',
                    );
                }
            }
            $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)
    {
        
        $this->db->delete('products', array('id' => $id));
        $this->response(['Product deleted successfully.'], REST_Controller::HTTP_OK);
    }
}
