<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Production_Process extends CI_Controller {

    var $main_menu_name = "production_process";
	var $sub_menu_name = "production_process";
	
	public function __construct()
	{
		parent::__construct();
		$this->load->model('Warehouse_Model');
		$this->load->model('Common_Model');
		$this->load->model('Production_Process_Model');
		$this->load->model('Stock_Counter_Model');
		date_default_timezone_set('asia/colombo');
	}

	public function index()	{
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		echo "production process step";
	}
	function list_product_block(){
	    $data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
	    $this->load->view('product_block/product_block_list',$data);
	}
	public function get_list_product_block($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Production_Process_Model->getProductsBlockList($start, $length, $search_key_val);
        $value_count    = $this->Production_Process_Model->getProductsBlockList('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Production_Process_Model->getProductsBlockList('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $open = "";$close = "";
        $enable="";
        $disable="";
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $k = '';
                if ($products->product_status == 0) {
                    $k = "btn-danger";
                    $m = "fa-minus-circle";
                } else {
                    $k = "btn-green";
                    $m = "fa-check";
                }
                if ($products->product_status == 0) {
                        $open = '<a class="list-group-item list-group-item-danger">';
                        $close = '</a>';
                    } else if ($products->product_status == 1) {
                        $open = '<a class="list-group-item" style="border: none; background: inherit">';
                        $close = '</a>';
                    }
                $retVal              = (empty($products->sub_cat_name)) ? "--:--" : $products->sub_cat_name;
                $row                 = array();
                $no_of_mold =$this->Production_Process_Model->getProductsBlockCount($products->product_id);
                $row[]      = $open.$products->product_code.$close;
                $row[]      = $open.$products->product_name.$close;
                $row[]      = $open.$products->cat_name.$close;
                $row[]      = $retVal;
                $row[]      = $open.$products->mpt_name.$close;
                $row[]      = $products->product_price;
                $row[]      = $products->product_cost;
                $row[]      = $open.$no_of_mold.$close;
                $actdes     = '';
               
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs ' . $k . ' dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="' . base_url('production_process/list_product_mold?id='. $products->product_id)  . '"><i class="fa fa-file-text-o"></i> View Mold List</a></li>
                            ';
                    if($this->Common_Model->check_permission(113,$this->session->userdata( 'ss_group_id' ), 1 )){
                        if ($products->product_status == 0) {
                            $actdes .= $enable;
                        } else if ($products->product_status == 1) {
                            $actdes .= $disable;
                        }
                    }
                $actdes.='<li class="divider"></li><li><a onclick="create_new_block(' . $products->product_id . '); return false;" href="#"><i class="fa fa-trash-o"></i> Create New Block</a></li>';  
                $actdes = $actdes . ' 
                         
                            </ul></div>';
                            
                if($this->Common_Model->check_permission(112,$this->session->userdata( 'ss_group_id' ), 1 )){
                       $row[]  = $actdes;
                    }else{
                      $row[]  = "";  
                    }
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
	function create_new_product_block(){
	    $data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		$data['main_product_id'] =$this->input->get('product_id');
		$data['details']=$this->Production_Process_Model->get_block_details($this->input->get('product_id'));
	    $this->load->view('product_block/create_new_product_block',$data);
	}
	public function get_product_dynamic(){
        $str = $this->input->post('search_string');
		$result=$this->Production_Process_Model->get_row_matirial_and_intermediate_product($str);
        echo json_encode($result);
    }
    public function get_product_dynamic_final_and_intermediate(){
        $str = $this->input->post('search_string');
		$result=$this->Production_Process_Model->get_row_final_and_intermediate_product($str);
        echo json_encode($result);
    }
     public function add_row_matirial_and_intermediate_product()    {
		$this->load->library('form_validation');
		
		
		$this->form_validation->set_rules('product_id', 'Product', 'required|xss_clean');
		$this->form_validation->set_rules('main_product_id', 'Main Product', 'required|xss_clean');
		$this->form_validation->set_rules('allocated_quantity', 'Quntity', 'required|xss_clean');
		$this->form_validation->set_rules('base_item', 'BASE ITEM', 'xss_clean');
		
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
        $product_id=$this->input->post('product_id');
		$main_product_id=$this->input->post('main_product_id');
		$allocated_quantity=$this->input->post('allocated_quantity');
		$base_item=$this->input->post('base_item');
        $alrady=$this->Production_Process_Model->check_aldary_in_the_block($product_id,$main_product_id);    
        if($alrady==0){
            $data=array(
			'pdm_id'=>$main_product_id,
			'product_id'=>$product_id,
			'product_qty'=>$allocated_quantity,	
			'base_item'=>$base_item,
		);	
         $result=$this->Production_Process_Model->save_broduct_block_item($data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
        }else{
            $st = array('status' =>0,'validation' =>'This item already added');
          echo json_encode($st);
        }  
		}
	}
	public function get_product_block_sub_item_list(){
        $product_id=$this->input->get('product_id');
        
        
        
        
        $moldmasterdata=$this->Production_Process_Model->get_block_details($product_id);
        $values = $this->Production_Process_Model->get_product_block_sub_item_list_with_delete($product_id);
        $totalData=count($values);
        $totalFiltered=$totalData;
         $data          = array();
         $base_item_qty=0;
	    foreach ($values as $row) {
	        $item_quata_pre=0;
	        $math_operation=$row['math_operation'];
	       if($row['base_item']==1){
	           $base_item_qty=$row['product_qty']*$row['conversion_value'];
	           $item_quata_pre=number_format(100,3,".","")."%";
	       }else{
	           if($base_item_qty!=0){
	               $procut_in_convertion_value=$row['product_qty']*$row['conversion_value'];
	               $item_quata_pre=($procut_in_convertion_value/$base_item_qty)*100;
	               $item_quata_pre=number_format($item_quata_pre,3,".","")."%";
	           }else{
	              $item_quata_pre='Base item not set yet' ;
	           }
	       }
	      
	       if($row['is_deleted']==0){
	          $disable_button='<button type="button" class="btn btn-danger btn-xs" data-toggle="tooltip" data-placement="bottom" title="Disable this item"  onClick="delete_item_block('.$row['pdi_id'].')"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';  
	       $total_cost= $row['product_mat_cost']*$row['product_qty'];
	           
	           
	       }else{
	           $disable_button='<button type="button" class="btn btn-success btn-xs" data-toggle="tooltip" data-placement="bottom" title="Enable this item"  onClick="enable_item_block('.$row['pdi_id'].')"><i class="fa fa-trash-o" aria-hidden="true"></i></button>'; 
	       
	          $total_cost= 0;
	           
	       }
	       
	       
	       
	       
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_mat_code'];
	        $nestad_data[]  = $row['product_mat_name'];
	        $nestad_data[]  = $row['mpt_name'];
	        $nestad_data[]  = $row['unit_name'];
	        $nestad_data[]  = $row['product_mat_cost'];
	        $nestad_data[]  = number_format($row['product_qty'],3,".","");
	        $nestad_data[]  = $item_quata_pre;
	        $nestad_data[]  = number_format($total_cost,2,".","");
	        $nestad_data[]  = number_format(($total_cost/$moldmasterdata['batch_qty']),2,".","");
	        
	        
	       
	       
	        
	     $action='
	     <button type="button" class="btn btn-primary btn-xs" data-toggle="tooltip" data-placement="bottom" title="Edit allocated quantity" onClick="update_aloacted_qty('.$row['pdi_id'].')" ><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button>
	     '.$disable_button.'
	     ';
	     if($row['base_item']==0){
	       $base_item=' <button type="button" class="btn btn-default btn-xs" data-toggle="tooltip" data-placement="bottom" title="Select as base item " onClick="select_as_base('.$row['pdi_id'].')" ><i class="fa fa-square-o" aria-hidden="true"></i></button>';
	   }else{
	     $base_item='<span type="button" class="btn btn-success btn-xs" data-toggle="tooltip" data-placement="bottom" title="BASED ITEM "><i class="fa fa-check" aria-hidden="true"></i></span>';
	     }
	       $nestad_data[]  =$action.$base_item;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
    }
     public function update_block_product_qty(){
		$this->load->library('form_validation');
		$product_id=$this->input->post('product_id');
		$block_id=$this->input->post('block_id');
		$batch_qty=$this->input->post('batch_qty');
		$this->form_validation->set_rules('block_id', 'Main Product', 'required|xss_clean');
		$this->form_validation->set_rules('batch_qty', 'Quntity', 'required| greater_than[0]|max_length[20]|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $data=array(
			'batch_qty'=>$batch_qty,	
		);	
         $result=$this->Production_Process_Model->update_block_batch_qty($block_id,$data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	function update_item_block_alloacted_qty(){
	    $this->load->library('form_validation');
		$qty=$this->input->post('result');
		$pbi_id=$this->input->post('id');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		$this->form_validation->set_rules('result', 'Quntity', 'required| greater_than[0]|max_length[20]|xss_clean');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $data=array(
			'product_qty'=>$qty,	
		);	
         $result=$this->Production_Process_Model->update_production_block_item_table($pbi_id,$data);	   
          $st = array('status' =>1,'validation' =>'Updated');
          echo json_encode($st);
		}
	}
	function remove_item_block(){
	    $this->load->library('form_validation');
		$pbi_id=$this->input->post('id');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $data=array(
			'is_deleted'=>1,	
		);	
         $result=$this->Production_Process_Model->update_production_block_item_table($pbi_id,$data);	   
          $st = array('status' =>1,'validation' =>'Removed');
          echo json_encode($st);
		}
	}
	function add_bulk_request(){
	    $data['main_menu_name'] = 'bulk_request';
		$data['sub_menu_name'] = 'add_bulk_request';
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
	    $this->load->view('bulk_request/add_new_bulk_master',$data);
	}
	public function save_bulk_request_master()
    {
		$this->load->library('form_validation'); //form validation lib	
		
		$warehouse_id=$this->input->post('warehouse_id');
		$ref_no=$this->input->post('ref_no');
		$note=$this->input->post('note');
		$this->form_validation->set_rules('warehouse_id', 'Warehouuse', 'required|xss_clean');
		$this->form_validation->set_rules('ref_no', 'Ref No', 'xss_clean');
		$this->form_validation->set_rules('note', 'Quntity', 'max_length[500]|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $data=array(
			'brn_from_warehouse_id'=>$warehouse_id,
			'brn_to_warehouse_id'=>$warehouse_id,
			'brm_manual_ref_no'=>$ref_no,
			'brm_note'=>$note,	
			'brm_ref_no'=>$this->Common_Model->gen_ref_number('brm_id','bulk_requste_master','BRAL'),
			'added_user_id'=>$this->session->userdata('ss_user_id'),
			'added_date_time'=>date("Y-m-d H:i:s"),
		);	
          $result = $this->Production_Process_Model->insert_bulk_request_master_table($data);
        $status=0;
        if($result>0){
           $status=1; 
        }
        $retun_data=array(
            'result'=>$result,
            'status'=>$status,
            );
        echo json_encode($retun_data);
       
		}
	}
	function add_bulk_request_items(){
	    $data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		$data['brm_id'] =$this->input->get('id');
		$data['details']=$this->Production_Process_Model->getBulkRequestDetails($this->input->get('id'));
	    $this->load->view('bulk_request/add_new_bulk_items',$data);
	}
	public function save_bulk_request_items(){
		$this->load->library('form_validation');
	
		$this->form_validation->set_rules('product_id', 'Product', 'required|xss_clean');
		$this->form_validation->set_rules('brm_id', 'Main ', 'required|xss_clean');
		$this->form_validation->set_rules('req_qty', 'Quntity', 'required| greater_than[0]|max_length[20]|xss_clean');
		$this->form_validation->set_rules('req_note', 'NOTE ', 'xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $product_id=$this->input->post('product_id');
		    $brm_id=$this->input->post('brm_id');
		    $req_qty=$this->input->post('req_qty');
		    $req_note=$this->input->post('req_note'); 
		
            $data=array(
			'brm_id'=>$brm_id,
			'product_id'=>$product_id,
			'request_qty'=>$req_qty,	
			'approved_qty'=>$req_qty,	
			'bri_note'=>$req_note,
		);	
         $result=$this->Production_Process_Model->save_bulk_requste_master_table($data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	public function get_product_list_with_brm_id() {
        $brm_id=$this->input->get('brm_id');
        $values = $this->Production_Process_Model->get_product_list_with_brm_id($brm_id);
        $totalData=count($values);
        $totalFiltered=$totalData;
         $data          = array();
	    foreach ($values as $row) {
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	         $nestad_data[]  = $row['mpt_name'];
	        $nestad_data[]  = $row['unit_name'];
	        $nestad_data[]  = $row['product_cost'];
	        $nestad_data[]  = $row['request_qty'];
	        $nestad_data[]  = $row['bri_note'];
	       $nestad_data[]  =number_format(($row['product_cost']*$row['request_qty']),2,".","");
	     $action='
	     <button type="button" class="btn btn-primary btn-xs" data-toggle="tooltip" data-placement="bottom" title="Edit allocated quantity" onClick="update_aloacted_qty('.$row['bri_id'].')" ><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button>
	     <button type="button" class="btn btn-danger btn-xs" data-toggle="tooltip" data-placement="bottom" title="Remove this item"  onClick="delete_item_block('.$row['bri_id'].')"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
	     ';
	       $nestad_data[]  =$action;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
    }
    function update_bulk_item_qty(){
	    $this->load->library('form_validation');
		$qty=$this->input->post('result');
		$id=$this->input->post('id');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		$this->form_validation->set_rules('result', 'Quntity', 'required| greater_than[0]|max_length[20]|xss_clean');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $data=array(
			'request_qty'=>$qty,
			'approved_qty'=>$qty,
		);	
         $result=$this->Production_Process_Model->update_bulk_request_item_table($id,$data);	   
          $st = array('status' =>1,'validation' =>'Updated');
          echo json_encode($st);
		}
	}
	function remove_item_bulk_requste(){
	    $this->load->library('form_validation');
		$pbi_id=$this->input->post('id');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $data=array(
			'is_deleted'=>1,	
		);	
         $result=$this->Production_Process_Model->update_bulk_request_item_table($pbi_id,$data);	   
          $st = array('status' =>1,'validation' =>'Removed');
          echo json_encode($st);
		}
	}
	function list_pending_bulk_request(){
	    $data['main_menu_name'] = 'bulk_request';
		$data['sub_menu_name'] = 'list_pending_bulk_request';
	    $this->load->view('bulk_request/pending_bulk_request',$data);
	}
	public function get_pending_bulk_request($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Production_Process_Model->getPendingBulkRequest($start, $length, $search_key_val);
        $value_count    = $this->Production_Process_Model->getPendingBulkRequest('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Production_Process_Model->getPendingBulkRequest('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
     
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->brm_ref_no;
                $row[]               = $products->added_date_time;
                $row[]               = $products->brm_manual_ref_no;
                $row[]               = $products->name;
                $row[]               = $products->brm_note;
                 $row[]               ="";
                $actdes = '';
                $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">
                            <li><a href="' . base_url('production_process/add_bulk_request_items') . '?id=' . $products->brm_id . '"><i class="fa fa-pencil-square-o"></i> UPDATE</a></li>
                            <li><a style="cursor: pointer;" onclick="delete_request('. $products->brm_id .')"><i class="glyphicon fa fa-ban"></i> Delete </a></li>
                            ';
                $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);
        }
    }
     function approval_bulk_requste(){
	    $this->load->library('form_validation');
		$id=$this->input->post('id');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $data=array(
			'brm_approval_status'=>1,
			'approval_by'=>$this->session->userdata('ss_user_id'),
			'approval_date_time'=>date("Y-m-d H:i:s"),
		);	
         $result=$this->Production_Process_Model->update_bulk_request_master_table($id,$data);	   
          $st = array('status' =>1,'validation' =>'Updated');
          echo json_encode($st);
		}
	}
	
	function delete_bulk_requste(){
	    $this->load->library('form_validation');
		$id=$this->input->post('id');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
         $result=$this->Production_Process_Model->delete_bulk_order_master_table_by_primary_id($id);
         $result=$this->Production_Process_Model->delete_bulk_order_item_table_by_secondory_id($id);
          $st = array('status' =>1,'validation' =>'Updated');
          echo json_encode($st);
		}
	}
	function list_completed_bulk_request(){
	    $data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
	    $this->load->view('bulk_request/approved_bulk_request',$data);
	}
	
	public function get_approved_bulk_request($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Production_Process_Model->getApprovedBulkRequest($start, $length, $search_key_val);
        $value_count    = $this->Production_Process_Model->getApprovedBulkRequest('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Production_Process_Model->getApprovedBulkRequest('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->brm_ref_no;
                $row[]               = $products->added_date_time;
                $row[]               = $products->brm_manual_ref_no;
                $row[]               = $products->name;
                $row[]               = $products->brm_note;
                $actdes = '';
                $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">
                            <li><a href="' . base_url('production_process/genarate_bulk_production_estimate') . '?id=' . $products->brm_id . '"><i class="fa fa-pencil-square-o"></i> Generate Bulk Estimate</a></li>
                            <!--<li><a style="cursor: pointer;" onclick="approval_requste('. $products->brm_id .')"><i class="glyphicon fa fa-check"></i> Generate Bulk Production Estimate</a></li>-->
                            ';
                $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);
        }
    }
	function genarate_bulk_production_estimate(){
	    $data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		$data['brm_id'] =$this->input->get('id');
		$data['details']=$this->Production_Process_Model->getBulkRequestDetails($this->input->get('id'));
		//$data['items']=$this->Production_Process_Model->getBulkRequestDetails($this->input->get('id'));
	    $this->load->view('bulk_request/bulk_request_estimate',$data);
	}
	public function get_product_list_for_bulk_request_estimation_with_brm_id()
    {
        $brm_id=$this->input->get('brm_id');
        $values = $this->Production_Process_Model->get_product_list_with_brm_id($brm_id);
        $totalData=count($values);
        $totalFiltered=$totalData;
         $data          = array();
	    foreach ($values as $row) {
	       $display_form="";
	        $total_allocated_qty=$this->Production_Process_Model->get_total_estimated_qty($row['bri_id']);
	        if($total_allocated_qty==$row['approved_qty']){
	            $list_alocated_batch_block=$this->Production_Process_Model->get_allocated_batch_block_Estimaed_item($row['bri_id']);
	             $table_start='<table class="table">';
	              $table_head_start='<thead >';
	              $table_head_end='</thead>';
	              $table_end='</table>';
	              $table_body=' <tr><th>Code</th><th>Alocated Qty</th><th>No Of Batches </th><th>Production Qty</th><th>Extra Qty</th></tr>';
	              $total_qty_allocation=0;
	              $total_no_of_batch=0;
	              $total_production_qty=0;
	              $total_extra_qty=0;
	             foreach($list_alocated_batch_block as $lab){
	              $reminder=$lab['estimated_qty']%$lab['batch_qty'];
	              $extra_batch=0;
	              if($reminder>0){$extra_batch=1;}
	              $no_of_batches=(($lab['estimated_qty']-$reminder)/$lab['batch_qty'])+$extra_batch;
	              $production_qty=$no_of_batches*$lab['batch_qty'];
	              $exra_qty=$production_qty-$lab['estimated_qty'];
	              $total_extra_qty+=$exra_qty;
	              $total_qty_allocation+=$lab['estimated_qty'];
	              $total_no_of_batch+=$no_of_batches;
	              $total_production_qty+=$production_qty;
	              $table_body.='<tr><th>'.$lab['product_block_code'].'</th> <th>'.$lab['estimated_qty'].'</th><th>'.$no_of_batches.'</th><th>'.$production_qty.'</th><th>'.$exra_qty.'</th></tr>';
	             }
	             $table_body.='<tr><th>Total </th> <th> <div  style="border-top:1px solid gray; border-bottom:4px double gray;">'.$total_qty_allocation.'</div></th><th><div  style="border-top:1px solid gray; border-bottom:4px double gray;">'.$total_no_of_batch.'</div></th><th><div " style="border-top:1px solid gray; border-bottom:4px double gray;">'.$total_production_qty.'</div></th><th><div  style="border-top:1px solid gray; border-bottom:4px double gray;">'.$total_extra_qty.'</div></th></tr>';
	            $complete_table=$table_start.$table_body.$table_end;
	              $display_form.=$complete_table;
	        }else{
	        $blocks = $this->Production_Process_Model->get_product_blocks($row['product_id']);
	        $blocks_list="";
	        foreach($blocks as $b){
	           $blocks_list.='<option value="'.$b['pbm_id'].'">'.' '.$b['product_block_code'].' Per Batch Qty : '.$b['batch_qty'].'</option>' ;
	        }
	        $input='Quntity : <input style="max-width: 100px;min-width: 100px;" type="number" id="estimate_qty" name="estimate_qty" value="'.($row['approved_qty']-$total_allocated_qty).'" class="form-control" min="1" max="'.$row['approved_qty'].'">';
	        $select_box=' for batch block: <select name="product_batch_block" id="product_batch_block" class="form-control">'.$blocks_list.'</select>';
	        $hidden_input=' <input type="hidden" id="bri_id" name="bri_id" value="'.$row['bri_id'].'">';
            $submit_button=' <button type="submit" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Remove this item"  >ADD</button> ';
	        $display_form='<div class="form-group"><form id="create_new_batch_block_'.$row['bri_id'].'">'.$input.$select_box.$submit_button.$hidden_input.'</form> </div>';
	    }
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['approved_qty'];
	        $nestad_data[]  = $display_form;
	     $action='
	     <button type="button" class="btn btn-danger btn-xs" data-toggle="tooltip" data-placement="bottom" title="Remove this item"  onClick="delete_item_block('.$row['bri_id'].')"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
	     ';
	      $nestad_data[]  =$action;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
    }
    public function save_bulk_item_batch_block()
    {
		$this->load->library('form_validation');
		$bri_id=$this->input->post('bri_id');
		$product_batch_block=$this->input->post('product_batch_block');
		$estimate_qty=$this->input->post('estimate_qty');
		$this->form_validation->set_rules('bri_id', 'Main', 'required|xss_clean');
		$this->form_validation->set_rules('product_batch_block', 'Batch Block ', 'required|xss_clean');
		$this->form_validation->set_rules('estimate_qty', 'Quntity', 'required| greater_than[0]|max_length[20]|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $data=array(
			'bri_id'=>$bri_id,
			'batch_block_id'=>$product_batch_block,
			'estimated_qty'=>$estimate_qty,	
		);	
         $result=$this->Production_Process_Model->bulk_request_item_estimation_table($data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
       
		}
	}
	function remove_bulk_estimate_block_allocation(){
	    $this->load->library('form_validation');
		$id=$this->input->post('id');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
         $result=$this->Production_Process_Model->delete_estimate_block_alocation($id);	   
          $st = array('status' =>1,'validation' =>'Updated');
          echo json_encode($st);
		}
	}
	function generate_cost_estimation(){
	    $this->load->library('form_validation');
		$id=$this->input->post('id');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		$main_status=1;
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $details=$this->Production_Process_Model->getBulkRequestDetails($id);
            $values = $this->Production_Process_Model->get_product_list_with_brm_id($id);
             foreach ($values as $row) {
	            $total_allocated_qty=$this->Production_Process_Model->get_total_estimated_qty($row['bri_id']);
	            if($total_allocated_qty!=$row['approved_qty']){
	            $main_status=0;
                }
             }
             if($main_status==1){
                 $master_data=array(
	                  	'warehouse_id'=>$details['brn_to_warehouse_id'],
	                  	'brm_id'=>$details['brm_id'],
			            'brcem_refarance_no'=>$this->Common_Model->gen_ref_number('brcem_id','bulk_requste_cost_estimation_master','BCEAL'),
			            'added_user_id'=>$this->session->userdata('ss_user_id'),
			            'cost_estimated_date_time'=>date("Y-m-d H:i:s"),
	                  );
	            $master_id=$this->Production_Process_Model->save_bulk_requste_cost_estimation_master_table($master_data);
                 //**********************************************************************
                 foreach ($values as $row) {
                 $list_alocated_batch_block=$this->Production_Process_Model->get_allocated_batch_block_Estimaed_item($row['bri_id']);
                  foreach($list_alocated_batch_block as $lab){
	              $reminder=$lab['estimated_qty']%$lab['batch_qty'];
	              $extra_batch=0;
	              if($reminder>0){$extra_batch=1;}
	              $no_of_batches=(($lab['estimated_qty']-$reminder)/$lab['batch_qty'])+$extra_batch;
	              $production_qty=$no_of_batches*$lab['batch_qty'];
	              $exra_qty=$production_qty-$lab['estimated_qty'];
	              for($i=0;$i<$no_of_batches;$i++){
	                 //----------------------------------------------------
	                  $item_data=array(
	                  	'brcem_id'=>$master_id,
			            'batch_refarance_no'=>$this->Common_Model->gen_ref_number('brcei_id','bulk_requste_cost_estimation_items','LKB'),
			            'batch_qty'=>$lab['batch_qty'],
			            'bulk_req_master_id'=>$id,
			            'bulk_req_item_id'=>$row['bri_id'],
			            'brie_id'=>$lab['brie_id'],
			            'product_id'=>$row['product_id'],
			            'batch_product_block_id'=>$lab['batch_block_id']
	                  );
	                  $item_id=$this->Production_Process_Model->save_bulk_requste_cost_estimation_items_table($item_data);
	                  //#################################################################################################
	                  $list_sub_prodcut=$this->Production_Process_Model->get_sub_item_list($lab['batch_block_id']);
	                  foreach($list_sub_prodcut as $lsp){
	                    $sub_item_data=array(
	                  	'brcei_id'=>$item_id,
			            'item_id'=>$lsp['product_id'],
			            'item_qty'=>$lsp['product_qty'],
			            'item_cost'=>$lsp['product_cost'],
			            'item_sub_total'=>$lsp['product_qty']*$lsp['product_cost']
	                  ); 
	                  $sub_item_id=$this->Production_Process_Model->save_bulk_requste_cost_estimation_sub_items_table($sub_item_data);
	                  }
	                 //################################################################################################
	                 //---------------------------------------------------- 
	              }
	             }
                 }
                 //**********************************************************************
                $this->Production_Process_Model->update_estimated_item_cost($master_id);
                $data2=array('pickup_status'=>1,'pickup_by'=>$this->session->userdata('ss_user_id'),'pickup_date_time'=>date("Y-m-d H:i:s"),);
                $this->Production_Process_Model->update_bulk_request_master_table($id,$data2);
                $st = array('status' =>1,'validation' =>'Generated','last_id'=>$master_id);
                    echo json_encode($st); 
             }else{
                  $st = array('status' =>0,'validation' =>'Estimated not Completed. please check again!','last_id'=>0);
                    echo json_encode($st);
             }
		}
	}
    function list_completed_bulk_estimate(){
	    $data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
	    $this->load->view('bulk_request/pending_bulk_completed_estimate',$data);
	}

	 public function get_list_completed_bulk_estimate($value = '')
    {
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Production_Process_Model->getCompletedEstimation($start, $length, $search_key_val);
        $value_count    = $this->Production_Process_Model->getCompletedEstimation('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Production_Process_Model->getCompletedEstimation('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->brcem_refarance_no;
                $row[]               = $products->cost_estimated_date_time;
                $row[]               = "";
                $row[]               = $products->name;
                $row[]               = $products->total_cost_estimation_value;
                $actdes = '';
                $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">
                            <li><a href="' . base_url('production_process/estimate_detais') . '?id=' . $products->brcem_id . '"><i class="fa fa-pencil-square-o"></i> Estimate Details</a></li>
                            ';
                $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);
        }
    }
    	function estimate_detais(){
	    $data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		$data['estimation_id'] =$this->input->get('id');
		$data['details']=$this->Production_Process_Model->getEstimateDetails($this->input->get('id'));
	    $this->load->view('bulk_request/estimated_details',$data);
	}
	
	public function get_estimate_list()
    {
        $id=$this->input->get('id');
        $values = $this->Production_Process_Model->get_product_list_only($id);
        $totalData=count($values);
        $totalFiltered=$totalData;
         $data          = array();
	    foreach ($values as $row) {
	      
	             $table_start='<table class="table">';
	              $table_head_start='<thead >';
	              $table_head_end='</thead>';
	              $table_end='</table>';
	              $table_body=' <tr><th>Batch Code</th><th>Unit Cost</th><th>Qty</th><th>Estimate Cost </th></tr>';
	        $batch_list=$this->Production_Process_Model->get_related_batch_using_product_id($id,$row['product_id']);
	        $qty_sub_total=0;
	        $estimated_sub_total=0;
	        $unt_sub_total=0;
	        foreach($batch_list as $bl){
	           $table_body.='<tr><th>'.$bl['batch_refarance_no'].'</th><th>'.$bl['unit_estimated_cost'].'</th><th>'.$bl['batch_qty'].'</th><th>'.$bl['estimate_cost_value'].'</th> </tr>'; 
	           $qty_sub_total+=$bl['batch_qty'];
	           $estimated_sub_total+=$bl['estimate_cost_value'];
	        }
	        $table_body.='<tr><th>Total </th> <th></th><th><div  style="border-top:1px solid gray; border-bottom:4px double gray;">'.$qty_sub_total.'</div></th><th><div " style="border-top:1px solid gray; border-bottom:4px double gray;">'.$estimated_sub_total.'</div></th></tr>';
	        $complete_table=$table_start.$table_body.$table_end;
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $complete_table;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
    }
    	public function get_estimate_raw_matirial_list(){
        $id=$this->input->get('id');
        $values = $this->Production_Process_Model->get_related_batch_using_product_id($id);
        $totalData=count($values);
        $totalFiltered=$totalData;
         $data          = array();
	    foreach ($values as $row) {
	             $table_start='<table class="table">';
	              $table_head_start='<thead >';
	              $table_head_end='</thead>';
	              $table_end='</table>';
	              $table_body=' <tr><th>Product code</th><th>Product code</th><th> Cost </th><th>Qty</th><th>Sub Total </th></tr>';
	        $raw_matirial=$this->Production_Process_Model->get_estimate_raw_matirial_list($row['brcei_id']);
	        $qty_sub_total=0;
	        $estimated_sub_total=0;
	        $unt_sub_total=0;
	        foreach($raw_matirial as $bl){
	           $table_body.='<tr><th>'.$bl['product_code'].'</th><th>'.$bl['product_name'].'</th><th>'.$bl['item_cost'].'</th><th>'.$bl['item_qty'].'</th><th>'.$bl['item_sub_total'].'</th> </tr>'; 
	           $qty_sub_total+=$bl['item_qty'];
	           $estimated_sub_total+=$bl['item_sub_total'];
	        }
	        $table_body.='<tr><th>Total </th> <th></th><th></th><th><div  style="border-top:1px solid gray; border-bottom:4px double gray;">'.$qty_sub_total.'</div></th><th><div " style="border-top:1px solid gray; border-bottom:4px double gray;">'.$estimated_sub_total.'</div></th></tr>';
	        $complete_table=$table_start.$table_body.$table_end;
	        $nestad_data=array();
	        $nestad_data[]  = $row['batch_refarance_no']."<br>( ".$row['product_code']." : ".$row['product_name']." )";
	        $nestad_data[]  = $row['batch_qty'];
	        $nestad_data[]  = $complete_table;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
    }
    public function get_raw_and_intermediate_as_bulk()
    {
        $id=$this->input->get('id');
        $values = $this->Production_Process_Model->get_raw_matiarial_andintermediate_product_list_only($id);
        $totalData=count($values);
        $totalFiltered=$totalData;
         $data          = array();
	    foreach ($values as $row) {
	       $req_qty=$this->Production_Process_Model->get_raw_matiarial_and_intermediate_product_total_qty($id,$row['item_id']);
	       $cost=$this->Production_Process_Model->get_raw_matiarial_and_intermediate_product_total_cost($id,$row['item_id']);
	       $nestad_data=array();
	       $nestad_data[]  = $row['product_code'];
	       $nestad_data[]  = $row['product_name'];
	       $nestad_data[]  = $req_qty;
	       $nestad_data[]  = $cost;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
    }
    
    function upcoming_productions_batch(){
         $data['main_menu_name'] = 'production';
		$data['sub_menu_name'] = 'upcoming_productions_batch';
	    $this->load->view('production/upcoming_production_batch',$data);
    }
    
    	public function get_upcoming_productions_batch($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Production_Process_Model->getUpcomingProductionsBatch($start, $length, $search_key_val);
        $value_count    = $this->Production_Process_Model->getUpcomingProductionsBatch('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Production_Process_Model->getUpcomingProductionsBatch('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
     
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->batch_refarance_no;
                $row[]               = $products->batch_qty;
                $row[]               = $products->unit_estimated_cost;
                $row[]               = $products->estimate_cost_value;
                $row[]               = $products->product_code." : ".$products->product_name;
                $actdes = '';
                $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">
                            <li><a href="' . base_url('production_process/stock_issue_for_batch') . '?id=' . $products->brcei_id . '"><i class="fa fa-pencil-square-o"></i> Item Isuue for production</a></li>
                            <!--<li><a style="cursor: pointer;" onclick="approval_requste('. $products->brcei_id .')"><i class="glyphicon fa fa-check"></i> Requste Approval</a></li>-->
                            ';
                $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);
        }
    }
    
    function stock_issue_for_batch(){
	    $data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		$data['batch_id'] =$this->input->get('id');
		$data['details']=$this->Production_Process_Model->getProductionBatchDetails($this->input->get('id'));
		//$data['items']=$this->Production_Process_Model->getBulkRequestDetails($this->input->get('id'));
	    $this->load->view('production/stock_issue_for_batch',$data);
	}
	
	
	public function get_sub_item_and_relevent_stock_batch()
    {
        $batch_id=$this->input->get('id');
        $values = $this->Production_Process_Model->get_product_list_with_batch_id($batch_id);
        $details=$this->Production_Process_Model->getProductionBatchDetails($batch_id);
        
        
        $totalData=count($values);
        $totalFiltered=$totalData;
         $data          = array();
	    foreach ($values as $row) {
	       $display_form="";
	        $total_allocated_qty=$this->Production_Process_Model->get_total_issued_qty($row['brcesi_id']);
	        if($total_allocated_qty==$row['item_qty']){
	            $list_alocated_batch_block=$this->Production_Process_Model->get_production_batch_issue_items($row['brcesi_id']);
	             $table_start='<table class="table">';
	              $table_head_start='<thead >';
	              $table_head_end='</thead>';
	              $table_end='</table>';
	              $table_body=' <tr><th>Batch Code</th><th>Cost</th><th>Quntity</th><th>Sub Total</th></tr>';
	              $total_qty_allocation=0;
	              $total_actual_cost=0;
	             foreach($list_alocated_batch_block as $lab){
	              $total_qty_allocation+=$lab['psi_item_qty'];
	              $total_actual_cost+=$lab['psi_total_cost'];
	              $table_body.='<tr><th>'.$lab['batch_ref_number'].'</th> <th>'.$lab['psi_cost'].'</th><th>'.$lab['psi_item_qty'].'</th><th>'.$lab['psi_total_cost'].'</th></tr>';
	             }
	             $table_body.='<tr><th>Total </th>  <th></th> <th> <div  style="border-top:1px solid gray; border-bottom:4px double gray;">'.$total_qty_allocation.'</div></th><th><div  style="border-top:1px solid gray; border-bottom:4px double gray;">'.$total_actual_cost.'</div></th></tr>';
	            $complete_table=$table_start.$table_body.$table_end;
	              $display_form.=$complete_table;
	        }else{
	        $blocks = $this->Production_Process_Model->get_allocated_batch_item($row['item_id']);
	        $blocks_list="";
	        foreach($blocks as $b){
	            $in_stock=   $this->Stock_Counter_Model->get_stock_balance_batch($details['warehouse_id'],$row['item_id'],$b['batch_id']);  
	            if($in_stock<=0){continue;}
	           $blocks_list.='<option value="'.$b['batch_id'].'">'.' '.$b['batch_ref_number'].' In Stock : '.$in_stock.'</option>' ;
	        }
	        $input='Quntity : <input style="max-width: 100px;min-width: 100px;" type="text" id="estimate_qty" name="estimate_qty" value="'.($row['item_qty']-$total_allocated_qty).'" class="form-control" min="1" max="'.($row['item_qty']-$total_allocated_qty).'">';
	        $select_box=' for batch block: <select name="product_batch_block" id="product_batch_block" class="form-control">'.$blocks_list.'</select>';
	        $hidden_input=' <input type="hidden" id="brcesi_id" name="brcesi_id" value="'.$row['brcesi_id'].'">
	        <input type="hidden" id="brcei_id" name="brcei_id" value="'.$row['brcei_id'].'">
	        <input type="hidden" id="brcem_id" name="brcem_id" value="'.$details['brcem_id'].'">
	        <input type="hidden" id="warehouse_id" name="warehouse_id" value="'.$details['warehouse_id'].'">
	        <input type="hidden" id="balance_qty" name="balance_qty" value="'.($row['item_qty']-$total_allocated_qty).'">
	        <input type="hidden" id="product_id" name="product_id" value="'.$row['item_id'].'">
	        ';
            $submit_button=' <button type="submit" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Remove this item"  >ADD</button> ';
	        $display_form='<div class="form-group"><form id="create_new_batch_block_'.$row['brcesi_id'].'">'.$input.$select_box.$submit_button.$hidden_input.'</form> </div>';
	    }
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['item_qty'];
	        $nestad_data[]  = $display_form;
	     $action='
	     <button type="button" class="btn btn-danger btn-xs" data-toggle="tooltip" data-placement="bottom" title="Remove this item"  onClick="delete_item_block('.$row['brcesi_id'].')"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
	     ';
	      //$nestad_data[]  =$action;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
    }
    
    public function save_issue_item_with_batch()
    {
		$this->load->library('form_validation');
		$brcesi_id=$this->input->post('brcesi_id');
		$brcei_id=$this->input->post('brcei_id');
		$brcem_id=$this->input->post('brcem_id');
		$warehouse_id=$this->input->post('warehouse_id');
		$balance_qty=$this->input->post('balance_qty');
		$product_id=$this->input->post('product_id');
		$product_batch_block=$this->input->post('product_batch_block');
		$estimate_qty=$this->input->post('estimate_qty');
		$this->form_validation->set_rules('brcesi_id', 'Main', 'required|xss_clean');
		$this->form_validation->set_rules('brcei_id', 'Main1', 'required|xss_clean');
		$this->form_validation->set_rules('brcem_id', 'Main2', 'required|xss_clean');
		$this->form_validation->set_rules('warehouse_id', 'Main3', 'required|xss_clean');
		$this->form_validation->set_rules('product_id', 'Main5', 'required|xss_clean');
		$this->form_validation->set_rules('balance_qty', 'Main4', 'required|xss_clean');
		$this->form_validation->set_rules('product_batch_block', 'Batch Block ', 'required|xss_clean');
		$this->form_validation->set_rules('estimate_qty', 'Quntity', 'required| greater_than[0]|max_length[20]|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {   
            $cost=0;
            $allocated_qty=0;
            $in_stock=   $this->Stock_Counter_Model->get_stock_balance_batch($warehouse_id,$product_id,$product_batch_block);
            if($in_stock>$balance_qty){
                if($balance_qty>=$estimate_qty){
                    $allocated_qty=$estimate_qty;
                }else{
                    $allocated_qty=$balance_qty;
                }
            }else{
                $allocated_qty=$in_stock;
            }
            $cost=$this->Production_Process_Model->get_batch_actual_cost($product_batch_block);
            $data=array(
			'brcesi_id'=>$brcesi_id,
			'batch_id'=>$product_batch_block,
			'psi_item_qty'=>$allocated_qty,
			'psi_wrehouse_id'=>$warehouse_id,
			'brcei_id'=>$brcei_id,
			'brcem_id'=>$brcem_id,
			'psi_item_id'=>$product_id,
			'psi_cost'=>$cost,
			'psi_total_cost'=>$cost*$allocated_qty,
		);	
          $result=$this->Production_Process_Model->bulk_production_stock_issue_table($data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	
		function send_to_production(){
	    $this->load->library('form_validation');
		$id=$this->input->post('id');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		$main_status=1;
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $values = $this->Production_Process_Model->get_list_estimation_subb_item_list_by_item_id($id);
             foreach ($values as $row) {
            $total_allocated_qty=$this->Production_Process_Model->get_total_production_issue_qty($row['brcesi_id']);
            if($total_allocated_qty!=$row['item_qty']){
	            $main_status=0;
                }
             }
             if($main_status==1){
                 $master_data=array(
	                  	'pickup_status'=>1,
			            'pickup_by'=>$this->session->userdata('ss_user_id'),
			            'pickup_date_time'=>date("Y-m-d H:i:s"),
	                  );
	            $master_id=$this->Production_Process_Model->update_bulk_requste_cost_estimation_items_table($id,$master_data);
                $st = array('status' =>1,'validation' =>'Generated','last_id'=>0);
                    echo json_encode($st); 
             }else{
                  $st = array('status' =>0,'validation' =>'Estimated not Completed. please check again!','last_id'=>0);
                    echo json_encode($st);
             }
		}
	}
	
	 function in_production(){
         $data['main_menu_name'] = 'production';
		$data['sub_menu_name'] = 'in_production';
	    $this->load->view('production/in_production_batch',$data);
    }
    
    public function get_in_productions_batch($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Production_Process_Model->getInProductionsBatch($start, $length, $search_key_val);
        $value_count    = $this->Production_Process_Model->getInProductionsBatch('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Production_Process_Model->getInProductionsBatch('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
     
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->batch_refarance_no;
                $row[]               = $products->batch_qty;
                $row[]               = $products->unit_estimated_cost;
                $row[]               = $products->estimate_cost_value;
                $row[]               = $products->product_code." : ".$products->product_name;
                $actdes = '';
                $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">
                           <li><a style="cursor: pointer;" onclick="finish_production('. $products->brcei_id .')"><i class="glyphicon fa fa-check"></i> Finish</a></li>
                            ';
                $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);
        }
    }
    
    function production_completed_batch (){
         $data['main_menu_name'] = 'production_completed_batch ';
		$data['sub_menu_name'] = 'production_completed_batch ';
	    $this->load->view('production/completed_product_batch',$data);
    }
    
    public function get_production_completed_batch($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Production_Process_Model->getCompletedBatch($start, $length, $search_key_val);
        $value_count    = $this->Production_Process_Model->getCompletedBatch('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Production_Process_Model->getCompletedBatch('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
     
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->added_date_time;
                $row[]               = $products->brm_ref_no;
                $row[]               = $products->batch_refarance_no;
                $row[]               = $products->product_code." : ".$products->product_name;
                $row[]               = $products->batch_qty;
                $row[]               = $products->estimated_unit_cost;
                $row[]               = $products->estimated_batch_cost;
                $row[]               = $products->actual_unit_cost;
                $row[]               = $products->actual_batch_cost;
                $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 save_manufactured_product()
    {
		$this->load->library('form_validation');
		$id=$this->input->post('id');
	
		$this->form_validation->set_rules('id', 'Main', 'required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {  
            $details=$this->Production_Process_Model->getProductionBatchDetails($id);
            $actual_batch_cost=$this->Production_Process_Model->get_manufacured_batch_actual_material_cost($details['brcei_id']);
            $data=array(
			'added_date_time'=>date("Y-m-d H:i:s"),
			'added_by'=>$this->session->userdata('ss_user_id'),
			'product_id'=>$details['product_id'],
			'batch_id'=>$details['brcei_id'],
			'batch_qty'=>$details['batch_qty'],
			'estimated_unit_cost'=>$details['unit_estimated_cost'],
			'estimated_batch_cost'=>$details['estimate_cost_value'],
			'actual_unit_cost'=>$actual_batch_cost/$details['batch_qty'],
			'actual_batch_cost'=>$actual_batch_cost,
			'no_of_usable_days'=>4,
			'expiery_date'=>date("Y-m-d H:i:s"),
			'warehouse_id'=>$details['warehouse_id'],
			'bulk_requste_id'=>$details['brm_id'],
		);
		$this->Production_Process_Model->save_manufactured_finish_product($data);
		 $data2=array(
	                  	'production_complete_status'=>1,
			            'p_u_updated_user'=>$this->session->userdata('ss_user_id'),
			            'p_u_date_time'=>date("Y-m-d H:i:s"),
	                  );
	      $result=$this->Production_Process_Model->update_bulk_requste_cost_estimation_items_table($id,$data2);
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	
	
	 function quality_check (){
         $data['main_menu_name'] = 'quality_check ';
		$data['sub_menu_name'] = 'quality_check ';
	    $this->load->view('production/quality_check',$data);
    }
    
     public function get_pending_qc_production_completed_batch($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Production_Process_Model->getPendingqualityCheck($start, $length, $search_key_val);
        $value_count    = $this->Production_Process_Model->getPendingqualityCheck('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Production_Process_Model->getPendingqualityCheck('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->added_date_time." <br> ".$products->brm_ref_no;
                $row[]               = $products->batch_refarance_no." <br> ".$products->product_code." <br> ".$products->product_name." <br> "."Batch Qty : ".$products->batch_qty;
                $total_allocated_qty=$this->Production_Process_Model->get_total_manufacture_defect_qty($products->batch_id);
                $blocks_list='<option value=""> Manufacture Defect </option>'; 
            $input='<input class="form-control"  type="number" id="estimate_qty" name="estimate_qty" value="" class="form-control" min="1" max="'.($products->batch_qty-$total_allocated_qty).'">';
	        $select_box='<select  name="product_batch_block" id="product_batch_block" class="form-control">'.$blocks_list.'</select>';
	        $hidden_input=' <input type="hidden" id="mp_id" name="mp_id" value="'.$products->mp_id.'">
	        <input type="hidden" id="product_id" name="product_id" value="'.$products->product_id.'">
	        <input type="hidden" id="unit_cost" name="unit_cost" value="'.$products->actual_unit_cost.'">
	        <textarea class="form-control" type="text" id="reason" name="reason" value=""></textarea>
	        <input type="hidden" id="warehouse_id" name="warehouse_id" value="'.$products->warehouse_id.'">
	        <input type="hidden" id="batch_id" name="batch_id" value="'.$products->batch_id.'">
	        <input type="hidden" id="balance_qty" name="balance_qty" value="'.($products->batch_qty-$total_allocated_qty).'"> ';
            $submit_button=' <button type="submit" class="btn btn-primary btn-xs form-control data-toggle="tooltip" data-placement="bottom" title="Remove this item"  >ADD</button> ';
	        $display_form='
	        <div class="panel panel-default">
              <div  class="panel-heading"> Remove Manufacture Defect Items <span class="pull-right"> Total Manufacture Defect Qty : '.$total_allocated_qty.'</span></div>
	        <div class="panel-body"> 
	        <form id="create_new_batch_block_'.$products->mp_id.'">
	         <div class="col-md-12">
                <div class="form-group">
                <label>Quntity  </label>
                '.$input.'
                </div>
                <div class="form-group">
                '.$hidden_input.'
                </div>
                <div class="form-group">
                '.$submit_button.'
                </div>
                </div>
                </form> 
                </div>
	        </div>
	        '; 
                $row[]               =$display_form;
                $row[]               =$products->batch_qty-$total_allocated_qty;
                $actdes='';
                $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">
                            <li><a style="cursor: pointer;" onclick="approval_requste('. $products->mp_id .')"><i class="glyphicon fa fa-check"></i> QC Approval</a></li>
                            <li><a style="cursor: pointer;" onclick="reject_requste('. $products->mp_id .')"><i class="glyphicon fa fa-ban"></i>  QC Reject </a></li>
                            ';
                $row[]               = $actdes;
                //$row[]               = $products->estimated_unit_cost;
               // $row[]               = $products->estimated_batch_cost;
               // $row[]               = $products->actual_unit_cost;
               // $row[]               = $products->actual_batch_cost;
                $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 save_manufacture_defet()
    {
		$this->load->library('form_validation');
		$estimate_qty=$this->input->post('estimate_qty');
		$mp_id=$this->input->post('mp_id');
		$product_id=$this->input->post('product_id');
		$unit_cost=$this->input->post('unit_cost');
		$reason=$this->input->post('reason');
		$warehouse_id=$this->input->post('warehouse_id');
		$batch_id=$this->input->post('batch_id');
		$balance_qty=$this->input->post('balance_qty');
		
		$this->form_validation->set_rules('mp_id', 'Main', 'required|xss_clean');
		$this->form_validation->set_rules('product_id', 'Main1', 'required|xss_clean');
		$this->form_validation->set_rules('unit_cost', 'Main2', 'required|xss_clean');
		$this->form_validation->set_rules('warehouse_id', 'Main3', 'required|xss_clean');
		$this->form_validation->set_rules('warehouse_id', 'Main5', 'required|xss_clean');
		$this->form_validation->set_rules('balance_qty', 'Main4', 'required|xss_clean');
		$this->form_validation->set_rules('estimate_qty', 'Quntity', 'required| greater_than[0]|max_length[20]|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {   
            $data=array(
			'mdp_batch_id'=>$batch_id,
			'mdp_product_id'=>$product_id,
			'mdp_qty'=>$estimate_qty,
			'mdp_actual_unit_cost'=>$unit_cost,
			'mdp_cost_sub_total'=>$unit_cost*$estimate_qty,
			'mdp_user_id'=>$this->session->userdata('ss_user_id'),
			'mpd_date_time'=>date("Y-m-d H:i:s"),
			'mdp_note'=>$reason,
			'mdp_warehouse_id'=>$warehouse_id,
			'mp_id'=>$mp_id
		);	
          $result=$this->Production_Process_Model->save_manufactured_defect_product_table($data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	public function give_qc_appoval()
    {
		$this->load->library('form_validation');
		$id=$this->input->post('id');
		$status=$this->input->post('status');
	
		$this->form_validation->set_rules('id', 'Main', 'required|xss_clean');
		$this->form_validation->set_rules('status', 'Main2', 'required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {  
            $data=array(
			'quality_control_date_time'=>date("Y-m-d H:i:s"),
			'quality_control_by'=>$this->session->userdata('ss_user_id'),
			'quality_control_status'=>$status,
		);
	      $result=$this->Production_Process_Model->update_manufactured_products_table($id,$data);
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	
	 function ready_for_grn (){
         $data['main_menu_name'] = 'ready_for_grn ';
		$data['sub_menu_name'] = 'ready_for_grn ';
	    $this->load->view('production/ready_for_grn',$data);
    }
    
     public function get_ready_for_grn($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Production_Process_Model->getReadyForGRN($start, $length, $search_key_val);
        $value_count    = $this->Production_Process_Model->getReadyForGRN('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Production_Process_Model->getReadyForGRN('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
     
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $total_allocated_qty=$this->Production_Process_Model->get_total_manufacture_defect_qty($products->batch_id);
                $row[]               = $products->added_date_time;
                $row[]               = $products->brm_ref_no;
                $row[]               = $products->batch_refarance_no;
                $row[]               = $products->product_code." : ".$products->product_name;
                $row[]               = $products->batch_qty;
                $row[]               = $total_allocated_qty;
                $row[]               = $products->batch_qty-$total_allocated_qty;
                $row[]               = $products->actual_unit_cost;
                $row[]               = $products->actual_batch_cost;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
    
    function auto_grn_process(){
        $value=$this->Production_Process_Model->getReadyForAutoGRN();
        $master_data = array(
       'reference_no' => $this->Common_Model->gen_ref_number('id','purchases','GRN'),
       'warehouse_id' => 4,
       'supplier_id'  => 1,
       'date'         =>date("Y-m-d H:i:s"),
       'note'         => "",
       'total'        => 0,
       'grand_total'  => 0,
       'discount'     => 0,
       'discount_cal' => 0,
	   'supp_invocie_no'=>""
    );
    $pur_id=$this->Production_Process_Model->save_purchases_table($master_data);
        $grand_total=0;
         foreach ($value as $row) {
           $total_allocated_qty=$this->Production_Process_Model->get_total_manufacture_defect_qty($row->batch_id);
           $grand_total+=($row->actual_unit_cost*($row->batch_qty-$total_allocated_qty));
          
             $item_data=array(
                 'purchase_id'=>$pur_id,
                 'product_id'=>$row->product_id,
                 'product_code'=>$row->product_code,
                 'product_name'=>$row->product_name,
                 'quantity'=>$row->batch_qty-$total_allocated_qty,
                 'unit_price'=>$row->actual_unit_cost,
                 'sub_total'=>($row->actual_unit_cost*($row->batch_qty-$total_allocated_qty)),
                 'manufacture_batch_re_no'=>$row->batch_refarance_no,
                 'manufacture_batch_id'=>$row->batch_id,
                 'is_new_batch'=>1,
                 'mp_id'=>$row->mp_id
                 );
                 $result=$this->Production_Process_Model->save_purchases_item_table($item_data);
                 $data=array(
			    'grn_date_time'=>date("Y-m-d H:i:s"),
			    'grn_by'=>$this->session->userdata('ss_user_id'),
			    'grn_status'=>1,
		        );
	            $result=$this->Production_Process_Model->update_manufactured_products_table($row->mp_id,$data);
         }
         
          $master_data2 = array(
            'total'        => $grand_total,
            'grand_total'  => $grand_total,
            );
          $result=$this->Production_Process_Model->update_purchases_table($pur_id,$master_data2);
           $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
    }
    
    
    	function list_product_mold(){
	    $data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		$data['id']         = $this->input->get('id');
	    $this->load->view('product_block/product_mold_list',$data);
	}
	public function get_list_product_mold($value = ''){
	    $product_id     = $this->input->get('id');
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Production_Process_Model->getProductsMold($start, $length, $search_key_val,$product_id);
        $value_count    = $this->Production_Process_Model->getProductsMold('', '', '',$product_id);
        if ($search_key_val) {
            $values_c  = $this->Production_Process_Model->getProductsMold('', '', $search_key_val,$product_id);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $open = "";$close = "";
        $enable="";
        $disable="";
        $included_items="";
       
        
        
        
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
            $sub_items = $this->Production_Process_Model->get_product_block_sub_item_list($products->pbm_id); 
            $table="";
            $thead="<table class='table'><thead><tr> <td>Code</td> <td>Name</td> <td>Unit</td> <td>Qty</td> <td>Unit Cost</td> <td>Total </td> <td>Production <br> Base </td> <td> % </td><tr></thead>";
            $tbodycontainer="";
            $sub_total=0;
	        foreach ($sub_items as $tbl) {
	        $tr="<tr> <td>".$tbl['product_mat_code']."</td><td>".$tbl['product_mat_name']." </td><td>".$tbl['unit_code']." </td><td>".$tbl['product_qty']." </td><td>".$tbl['product_mat_cost']." </td><td>".$tbl['product_mat_cost']*$tbl['product_qty']." </td> <td> </td>  <td></td> </tr>";
	        $tbodycontainer.=$tr;
	        $sub_total+=($tbl['product_mat_cost']*$tbl['product_qty']);
	        }
            $table=  $thead."<tbody>".$tbodycontainer."</tbody></table>";
                
                $row                 = array();
                $row[]      = $open.$products->product_block_code.$close;
                $row[]      = $open.$products->product_code.$close;
                $row[]      = $open.$products->product_name.$close;
                $row[]      =$table;
               
                $row[]      = $sub_total ;
                $row[]      = $products->batch_qty;
                $actdes     = '';
               
                $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">';
                    if($this->Common_Model->check_permission(113,$this->session->userdata( 'ss_group_id' ), 1 )){
                        if ($products->product_status == 0) {
                            $actdes .= $enable;
                        } else if ($products->product_status == 1) {
                            $actdes .= $disable;
                        }
                    }
                    if($this->Common_Model->check_permission(112,$this->session->userdata( 'ss_group_id' ), 1 )){
                        $actdes = $actdes . '
                            <li><a href="' . base_url('production_process/create_new_product_block?product_id=') . $products->pbm_id . '&s="><i class="fa fa-edit"></i>Allocate Material And Services</a></li>
                            ';
                    }
                $actdes = $actdes . ' 
                         
                            </ul></div>';
                            
                if($this->Common_Model->check_permission(112,$this->session->userdata( 'ss_group_id' ), 1 )){
                       $row[]  = $actdes;
                    }else{
                      $row[]  = "";  
                    }
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
    
    	function mark_base_item(){
	    $this->load->library('form_validation');
		$pbi_id=$this->input->post('id');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
		$result=$this->Production_Process_Model->get_pdm_id_using_pdi_id($pbi_id);
		if($result!=false){
		    $data=array(
			'base_item'=>0,	
		);	
		    $result=$this->Production_Process_Model->update_block_item_table_using_secondary_id($result,$data);
		     $data=array(
			'base_item'=>1,	
		);	
            $result=$this->Production_Process_Model->update_production_block_item_table($pbi_id,$data);
		}
          $st = array('status' =>1,'validation' =>'Updated');
          echo json_encode($st);
		}
	}
	
	 public function loadManagementTool()
    {
        $this->load->model('common_model');
        $data['service_centre'] = $this->Production_Process_Model->get_service_center_list();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'management_tool';
        $data['data_list']  = $this->loadGetProductMaterialListAvailability();
        $this->load->view('product_material/list_product_material_availability', $data);
    }
    
    function loadGetProductMaterialListAvailabilityold(){
       
        $values=$this->Production_Process_Model->get_service_center_order_list();
        $value_count=count($values);
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $service_centre = $this->Production_Process_Model->get_service_center_list();
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $k = '';
                if ($products->product_status == 0) {
                    $k = "btn-danger";
                    $m = "fa-minus-circle";
                } else {
                    $k = "btn-green";
                    $m = "fa-check";
                }
                if ($products->product_status == 0) {
                        $open = '<a class="list-group-item list-group-item-danger">';
                        $close = '</a>';
                    } else if ($products->product_status == 1) {
                        $open = '<a class="list-group-item" style="border: none; background: inherit">';
                        $close = '</a>';
                    }
                //$retVal              = (empty($products->sub_cat_name)) ? "--:--" : $products->sub_cat_name;
                $row                 = array();
                $ss_warehouse_id =  "";
                $qty=$this->Stock_Counter_Model->get_stock_balance('',$products->product_id);
               
                // $row[]               = '<div style="margin-bottom: 0px; width: 50px; height: 50px;" class="fileupload-new thumbnail"><img alt="" src="' . asset_url() . "uploads/thumbs/" . $products->product_mat_thumb . '"></div>';
                //$row[]               = $open.$products->product_mat_id.$close;
                $row[]          = $open.'<input name="product_mat_code[]" value="'.$products->product_code.'" readonly>'.$close;
                $row[]          = $open.$products->product_name.$close;
                $row[]          = number_format($products->requested_qty, 2, '.', ',');'<!--<span class="total_order" data-id="'.$products->product_id.'" data-current_qty="current_qty_'.$products->product_id.'" data-new_qty="new_qty_'.$products->product_id.'">'.$products->requested_qty.'</span>-->';
                $row[]          = '<input name="final_qty[]" id="final_qty_'.$products->product_id.'" readonly>';
                
               foreach ($service_centre as $sc) {
                    $row[]               = '<input data-toggle="tooltip" data-placement="top" title="ORIGINAL QUANTITY IS '.$products->requested_qty.'" name="wh_qty_'.$sc['msc_code'].'[]" class="input-sm new_qty_'.$products->product_id.'" data-final_qty="final_qty_'.$products->product_id.'" data-class_name="new_qty_'.$products->product_id.'" value="'.$products->allocated_qty.'"> <!--| <span class="current_qty_'.$products->product_id.'">'.$products->requested_qty.'</span>-->';
                }
                $actdes = '<button class="btn btn-default btn-sm" type="button" onClick="check_qty(this,\'final_qty_'.$products->product_id.'\',\''.$products->product_code.'\')"><i class="fa fa-file-text-o"></i> Check</button>';
                $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);
        }
   }
   function check_qty(){
        $output = array(
            'success' => true
        );
        echo json_encode($output);
   }
   
   function loadGetProductMaterialListAvailability(){
       
        $values=$this->Production_Process_Model->get_service_center_order_list();
        $value_count=count($values);
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $service_centre = $this->Production_Process_Model->get_service_center_list();
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $k = '';
                if ($products->product_status == 0) {
                    $k = "btn-danger";
                    $m = "fa-minus-circle";
                } else {
                    $k = "btn-green";
                    $m = "fa-check";
                }
                if ($products->product_status == 0) {
                        $open = '<a class="list-group-item list-group-item-danger">';
                        $close = '</a>';
                    } else if ($products->product_status == 1) {
                        $open = '<a class="list-group-item" style="border: none; background: inherit">';
                        $close = '</a>';
                    }
                //$retVal              = (empty($products->sub_cat_name)) ? "--:--" : $products->sub_cat_name;
                $row                 = array();
                $ss_warehouse_id =  "";
                $qty=$this->Stock_Counter_Model->get_stock_balance('',$products->product_id);
               
                // $row[]               = '<div style="margin-bottom: 0px; width: 50px; height: 50px;" class="fileupload-new thumbnail"><img alt="" src="' . asset_url() . "uploads/thumbs/" . $products->product_mat_thumb . '"></div>';
                //$row[]               = $open.$products->product_mat_id.$close;
                $row[]          = $open.'<input name="product_mat_code[]" value="'.$products->product_code.'" readonly>'.$close;
                $row[]          = $open.$products->product_name.$close;
                $row[]          = number_format($products->requested_qty, 2, '.', ',');'<!--<span class="total_order" data-id="'.$products->product_id.'" data-current_qty="current_qty_'.$products->product_id.'" data-new_qty="new_qty_'.$products->product_id.'">'.$products->requested_qty.'</span>-->';
                $row[]          = '<input name="final_qty[]" id="final_qty_'.$products->product_id.'" readonly> <input type="hidden" name="product_id" value="'.$products->product_id.'" readonly>';
                
               foreach ($service_centre as $sc) {
                   $serrvice_req_qty = $this->Production_Process_Model->get_service_center_allocated_qty($products->go_id,$sc['msc_code'],$products->product_id);
                        
                      $extra_input ='<input type="hidden" name="wh_qty[]" value="'.$sc['msc_code'].'">';
                    $row[]               = '<input data-toggle="tooltip" data-placement="top" title="ORIGINAL QUANTITY IS '.$products->requested_qty.'" name="wh_qty[]" class="input-sm new_qty_'.$products->product_id.'" data-final_qty="final_qty_'.$products->product_id.'" data-class_name="new_qty_'.$products->product_id.'" value="'.$serrvice_req_qty.'"> <!--| <span class="current_qty_'.$products->product_id.'">'.$products->requested_qty.'</span>-->'.$extra_input;
                 
                   
                   
               }
                $actdes = '<button class="btn btn-default btn-sm" type="submit" onClick="check_qty(this,\'final_qty_'.$products->product_id.'\',\''.$products->product_code.'\')"><i class="fa fa-file-text-o"></i> Check</button>';
                $row[]  = $actdes;
                $data[] = $row;
            }
            return $data;
            
        } else {
            return $data=array();
        }
   }
   
   
   	function update_group_order(){
	    $this->load->library('form_validation');
		$w_qty=$this->input->post('wh_qty');
		$id=$this->input->post('id');
		$product_id=$this->input->post('product_id');
		
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else{
            $count=0;
            $data=array();
           foreach($w_qty as $d){
             $remainder=$count%2;
           if($remainder==0){
               $data=array('allocated_qty'=>$d);
           }else{
               $this->Production_Process_Model->update_group_item($id,$d,$product_id,$data);
           }
           $count++;
           }
        }
        $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
        
        }
	    
	    function save_group_order_with_items(){
	        $id=$this->input->get('id');
	        
	       $data_list= $this->Production_Process_Model->get_service_center_order_list_final($id);
	        
	        
	        $data=array(
			'brn_from_warehouse_id'=>4,
			'brn_to_warehouse_id'=>4,
			'brm_manual_ref_no'=>'',
			'brm_note'=>'',	
			'brm_ref_no'=>$this->Common_Model->gen_ref_number('brm_id','bulk_requste_master','BR'),
			'added_user_id'=>$this->session->userdata('ss_user_id'),
			'added_date_time'=>date("Y-m-d H:i:s"),
		);	
          $last_id = $this->Production_Process_Model->insert_bulk_request_master_table($data);
          foreach($data_list as $row){
               $data=array(
			'brm_id'=>$last_id,
			'product_id'=>$row['product_id'],
			'request_qty'=>$row['allocated_qty'],	
			'approved_qty'=>$row['allocated_qty'],	
		);	
         $result=$this->Production_Process_Model->save_bulk_requste_master_table($data); 
          }
           $st = array('status' =>1,'validation' =>'Added','result'=>$last_id);
          echo json_encode($st);
	    }
	    
	    	function enable_item_block(){
	    $this->load->library('form_validation');
		$pbi_id=$this->input->post('id');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $data=array(
			'is_deleted'=>0,	
		);	
         $result=$this->Production_Process_Model->update_production_block_item_table($pbi_id,$data);	   
          $st = array('status' =>1,'validation' =>'Removed');
          echo json_encode($st);
		}
	}
	
		function list_bulk_request(){
	    $data['main_menu_name'] = 'reports';
		$data['sub_menu_name'] = 'list_bulk_request';
	    $this->load->view('bulk_request/list_bulk_request',$data);
	}
		public function get_completed_bulk_request($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Production_Process_Model->getCompletedBulkRequest($start, $length, $search_key_val);
        $value_count    = $this->Production_Process_Model->getCompletedBulkRequest('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Production_Process_Model->getCompletedBulkRequest('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
     
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->brm_ref_no;
                $row[]               = $products->added_date_time;
                $row[]               = $products->brm_manual_ref_no;
                $row[]               = $products->name;
                $row[]               = $products->brm_note;
                 $row[]               ="";
                $actdes = '';
                $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">
                            <!--<li><a href="' . base_url('production_process/add_bulk_request_items') . '?id=' . $products->brm_id . '"><i class="fa fa-pencil-square-o"></i> UPDATE</a></li>
                            <li><a style="cursor: pointer;" onclick="delete_request('. $products->brm_id .')"><i class="glyphicon fa fa-ban"></i> Delete </a></li>-->
                            ';
                $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);
        }
    }

	
}