<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
    include('core_estimate.php');  
class Estimate extends Core_Estimate
{
    public function __construct()
    {
        parent::__construct();
    }
    function  loadListApprovedRequest(){
        $data=array();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'listApprovedRequest';
        $this->load->view('estimate/approved_bulk_request',$data);
    }
    public function createEstimate(){
        $id = $this->getId();
        $data=array();
        /* get request master data and save estimate master data */
        $data =$this->setApprovedRequestBasicDataUsingMasterID($id,$data);
        $es_mstr=array(
            'pcem_request_id'=>$data['details']['brm_id'],
            'pcem_warehouse_id'=>$data['details']['brn_to_warehouse_id'],
            'pcem_id_ref_no'=>$this->Common_Model->gen_ref_number('pcem_id','production_cost_estimation_master','EST'),
            'pcem_user'=>$this->session->userdata('ss_user_id'),
            'pcem_date_time'=>date('Y-m-d H:i:s'),
            );
        $master_last_id=$this->executeSaveMasterTable($es_mstr);
        /* update main recode */
        $rq_mstr=array(
            'pickup_status'=>1,
            'pickup_by'=>$this->session->userdata('ss_user_id'),
            'pickup_date_time'=>date('Y-m-d H:i:s'),
            );
        $last_id=$this->updateRequestMasterTable($data['details']['brm_id'],$rq_mstr);
        if($last_id>0){$result=1;}else{$result=0;}
        $output = array(
                'status' => $result,
                "message" => "Error",
                'last_id'=>$master_last_id
            );
            echo json_encode($output);
    }
     function getListApprovedRequest(){
        $request_data=$this->getClientSideDataTableParameters();
        $result_array=$this->getApprovedRequestListForBasicDataTableOnServerSide($request_data);
        $values=$result_array['values'];
        $value_count=$result_array['value_count'];
        $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->warehouse_name;
                $row[]               = $products->approval_by;
                $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 style="cursor: pointer;" onclick="create_estimate('. $products->brm_id .')"><i class="glyphicon fa fa-check"></i> CREATE ESTIMATE </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  loadListPendingEstimate(){
        $data=array();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'listPendingEstimate';
        $this->load->view('estimate/pending_estimate',$data);
    }
    function getListPendingEstimate(){
        $request_data=$this->getClientSideDataTableParameters();
        $result_array=$this->getPendingEstimateListForBasicDataTableOnServerSide($request_data);
        $values=$result_array['values'];
        $value_count=$result_array['value_count'];
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->pcem_id_ref_no;
                $row[]               = $products->pcem_date_time;
                $row[]               = $products->brm_ref_no;
                $row[]               = $products->pcem_estimated_total_cost;
                $row[]               = $products->user_first_name;
                $row[]               = $products->last_modify_on;
                $row[]               = $products->modify_by;
                $row[]               = $products->warehouse_name;
                $row[]               = $products->pcem_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 style="cursor: pointer;" onclick="remove_estimation('. $products->pcem_id .')"><i class="glyphicon fa fa-ban"></i> Delete Estimation</a></li>
                            <li><a href="'.base_url('estimate/loadUpdateEstimate?id='. $products->pcem_id ).'"  style="cursor: pointer;"><i class="glyphicon fa fa-edit"></i> UPDATE</a></li>
                            <li><a href="'.base_url('estimate/loadProductionEstimateDetails?id='. $products->pcem_id ).'"  style="cursor: pointer;"><i class="glyphicon fa fa-info-circle"></i> 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  loadUpdateEstimate(){
        $data=array();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'listPendingEstimate';
        $id=$this->getId();
        $data =$this->setEstimateBasicDataUsingMasterID($id,$data);
        $this->load->view('estimate/update_estimate',$data);
    }
    function getListPendingUpdate(){
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getUpdatePendingEstimateListForBasicDataTable($request_data);
        $values=$result_array['values'];
        $value_count=$result_array['value_count'];
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        $time_list = $this->Production_Estimate_Model->loadTimeProfile(125567);
        $time_profile_list="";
	           foreach($time_list as $b){
	           $time_profile_list.='<option value="'.$b['mtp_id'].'"> '.$b['mtp_name'].'</option>' ;
	           }
        if (!empty($values)) {
            foreach ($values as $row) {
               $total_allocated_qty=$this->Production_Estimate_Model->loadTotalAllocatedEstiateQty($row['bri_id'],125564);
               $blocks = $this->Production_Estimate_Model->loadProductBlock($row['product_id'],125566);
               $blocks_list="";
	           foreach($blocks as $b){
	           $blocks_list.='<option value="'.$b['pbm_id'].'">'.' '.$b['product_block_code'].' Per Batch Qty : '.$b['batch_qty'].'</option>' ;
	           }
                 $batch_profile_list='<option value="1"> DEFAULT </option>';
                $batch_profile_list.='<option value="10"> 10 QTY  </option> ';
                
	    
	       $display_table="";
	      
	        if($total_allocated_qty>0){
	              $list_alocated_batch_block=$this->Production_Estimate_Model->loadAllocatedEstimationItem($row['bri_id'],125565);
	              $table_start='<table class="table">';
	              $table_head_start='<thead >';
	              $table_head_end='</thead>';
	              $table_end='</table>';
	              $table_body=' <tr><th>TIME<br>PROFILE</th><th>BATCH<br>PROFILE</th><th>QTY</th><th>BATCH</th><th data-toggle="tooltip" data-placement="top" title="PRODUCTION QUANTITY">PD<br>QTY</th><th>EXTRA<br>QTY</th><th>COST</th><th>ACTION</th></tr>';
	              $total_qty_allocation=0;
	              $total_no_of_batch=0;
	              $total_production_qty=0;
	              $total_extra_qty=0;
	              $total_cost_es=0;
	             foreach($list_alocated_batch_block as $lab){
	              $no_of_batches=$lab['no_of_batches'];
	              $production_qty=$lab['final_output_qty'];
	              $exra_qty=$lab['extra_output_qty'];
	              $total_extra_qty+=$exra_qty;
	              $total_qty_allocation+=$lab['allocated_qty'];
	              $total_no_of_batch+=$no_of_batches;
	              $total_production_qty+=$production_qty;
	              $total_cost_es+=$lab['pcei_cost'];
	              
	              if($lab['batch_profile']==1){
	                  $batch_proile="DEFAULT";
	              }else{
	                  $batch_proile=$lab['batch_profile'];
	              }
	              
	              
	              
	               $sub_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['pcei_id'].')"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
	     ';
	              $table_body.='<tr><td>'.$lab['mtp_name'].'</td><td>'.$batch_proile.'</td> <td>'.$lab['allocated_qty'].'</td><td>'.$no_of_batches.'</td><td>'.$production_qty.'</td><td>'.$exra_qty.'</td><td>'.$lab['pcei_cost'].'</td><td>'.$sub_action.'</td></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_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><th><div  style="border-top:1px solid gray; border-bottom:4px double gray;">'.$total_cost_es.'</div></th></tr>';
	            $complete_table=$table_start.$table_body.$table_end;
	              $display_table.=$complete_table;
	        }
	        if($total_allocated_qty<$row['approved_qty']){
	        $blocks = $this->Production_Estimate_Model->loadProductBlock($row['product_id'],125566);
	        $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="text" 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'].'"> <input type="hidden" id="est_id" name="est_id" value="'.$row['pcem_id'].'"> <input type="hidden" id="product_id" name="product_id" value="'.$row['product_id'].'">';
            //$submit_button=' <button type="submit" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Remove this item"  > ALLOCATE </button> ';
	      
	    }
	    else{
	       $display_form= $display_table;
	    }
	    
	        $select_box_basic_formula='<span style="display: none"><select name="product_batch_block" id="product_batch_block" class="form-control">'.$blocks_list.'</select></span>';
	        $select_box_time_profile=' TIME PROFILE : <select name="time_profile" id="time_profile" class="form-control">'.$time_profile_list.'</select>';
	        $select_box_batch_profile=' |  BATCH PROFILE : <select name="batch_profile" id="batch_profile" class="form-control">'.$batch_profile_list.'</select>';
	        $submit_button=' | <button type="submit" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Remove this item"  > ALLOCATE</button> ';
	        $hidden_input=' <input  type="hidden" id="bri_id" name="bri_id" value="'.$row['bri_id'].'"> <input type="hidden" id="est_id" name="est_id" value="'.$row['pcem_id'].'"> <input type="hidden" id="product_id" name="product_id" value="'.$row['product_id'].'">';
	        $input_box=' | QUANTITY : <input style="max-width: 50px;min-width: 50px;"  type="text" id="estimate_qty" name="estimate_qty" value="'.($row['approved_qty']-$total_allocated_qty).'" class="form-control" min="1" max="'.$row['approved_qty'].'">';
	        $date_input= 'DATE <input type="date" id="date" name="date" value="'.date('Y-m-d').'" class="form-control datepicker" required >';
	        
	        
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['approved_qty'];
	        $nestad_data[]  = $row['approved_qty']-$total_allocated_qty;
	       
	       if(($row['approved_qty']-$total_allocated_qty)>0){
	        $nestad_data[]  = ' <form role="form" id="create_new_batch_block_'.$row['bri_id'].'"> '.$select_box_time_profile.$select_box_batch_profile.$select_box_basic_formula.$hidden_input.$input_box.$date_input." ".$submit_button.'</form>';
	       }else{
	          $nestad_data[]  = $display_table; 
	       }
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        }else{
            $output = array(
                'data' => array(),
                "recordsTotal" => intval(0),
                "recordsFiltered" => intval(0)
            );
            echo json_encode($output);
        }
   }
   function getListEstimatedItems(){
       $this->load->model('Stock_Counter_Model');
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getUpdateEstimatedItemForBasicDataTable($request_data);
        $estimated_ingredients_items=$this->Production_Estimate_Model->getEstimatedEngrediantsItem($request_data);
        $estimated_ingredients_single_items=$this->Production_Estimate_Model->getEstimatedEngrediantsSingleItems($request_data);
        
        $ingredient_stock=array();
        foreach($estimated_ingredients_items as $ei){
	        $stock=$this->Stock_Counter_Model->get_stock_balance('',$ei['product_mat_id']); 
	        $nested_data=array(
	            'product_mat_id'=>$ei['product_mat_id'],
	            'stock'=>$stock,
	            );
	            $ingredient_stock[]=$nested_data;
	    }
        $values=$result_array['values'];
        $value_count=$result_array['value_count'];
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        $currant_stock=0;
        
        $warning_btn='';
        $warning_text='';
        if (!empty($values)) {
            foreach ($values as $row) {
	      
	       $total_allocated_qty=0;
	       $is_product_ing_short_detected=0;
	             
	              $table_start='<table  class="table collapse" id="tbl_'.$row['pcei_id'].'">';
	              $table_head_start='<thead >';
	              $table_head_end='</thead>';
	              $table_end='</table>';
	              $table_body=' <tr><th>INGREDIENTS</th><th data-toggle="tooltip" data-placement="top" title="UNIT OF MEASUREMENTS">UOM</th><th data-toggle="tooltip" data-placement="top" title="REQUIRED QUANTITY">R.QTY</th><th data-toggle="tooltip" data-placement="top" title="CURRANT STOCK">C.STOCK</th><th data-toggle="tooltip" data-placement="top" title="CARRY FORWORD STOCK">C/F STOCK</th></tr>';
	           
	            $currant_stock=0;
	             foreach($estimated_ingredients_items as $lab){
	                 $is_this_ing_short_detected=0; 
	                 if($lab['pcei_id']==$row['pcei_id']){
	                     
	                     //------------------------
	                     foreach($ingredient_stock as $key => $value)
                        {
                            if($value['product_mat_id']==$lab['product_mat_id']){
                             $currant_stock=$value['stock'];
                             $ingredient_stock[$key]['stock'] = $value['stock']-$lab['pcesi_final_qty'];
                            }else{
                            continue;
                            }
                        }
	                   //------------------------  
	                  $variance=$currant_stock-$lab['pcesi_final_qty'];
                      if($variance<0){
                      $is_product_ing_short_detected=1;
                      $is_this_ing_short_detected=1;
                  }
	                }else{
	                    continue;
	                }
                  $warning_tr='';
                  $warning_text='Stock requirement is fulfilled, click here to see details';
                  $warning_btn='btn-success';
                  if($is_this_ing_short_detected==1){
                      $warning_tr='style="background-color:#FFCCCB;"';
                      
                  }
                  if($is_product_ing_short_detected==1){
                       $warning_btn='btn-warning';
                       $warning_text='Required stock not enough, click here to see details';
                  }
                  
	              $table_body.='<tr '.$warning_tr.'><td>'.$lab['product_mat_code'].' - '.$lab['product_mat_name'].' </td><td>'.$lab['unit_code'].'</td><td>'.number_format($lab['pcesi_final_qty'],2,".","").'</td> <td>'.number_format($currant_stock,2,".","").'</td><td>'.number_format($variance,2,".","").'</td></tr>';
	               //$currant_stock-=$lab['pcesi_final_qty'];
	                 
                 
	               
	               
	             }
	             //$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_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><th><div  style="border-top:1px solid gray; border-bottom:4px double gray;">'.$total_cost_es.'</div></th></tr>';
	            $complete_table=$table_start.$table_body.$table_end;
	             $display_table='<button type="button" class="btn btn-md '.$warning_btn.' " data-toggle="collapse" data-target="#tbl_'.$row['pcei_id'].'"><i class="fa fa-eye" aria-hidden="true"> </i> '. $warning_text.'</button>';
	              $display_table.=$complete_table;
	       
	       
	       $batch_profile="DEFAULT";
	        if($row['batch_profile']==1){
	            $batch_proile="DEFAULT";
	        }else{
	           $batch_proile=$row['batch_profile']." QTY"; 
	        }
	         $remove_btn='<button type="button" class="btn btn-danger btn-xs" data-toggle="tooltip" data-placement="bottom" title="Remove this item"  onClick="delete_item_block('.$row['pcei_id'].')"><i class="fa fa-trash-o" aria-hidden="true"></i> REMOVE</button>
	     ';
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['mtp_name'];
	        
	        
	        $nestad_data[]  = $batch_proile;
	        $nestad_data[]  = $row['unit_name'];
	        $nestad_data[]  = $row['allocated_qty'];
	        $nestad_data[]  = $row['extra_output_qty'];
	         $nestad_data[]  = $row['final_output_qty'];
	        $nestad_data[]  = $display_table; 
	        $nestad_data[]=$remove_btn;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        }else{
            $output = array(
                'data' => array(),
                "recordsTotal" => intval(0),
                "recordsFiltered" => intval(0)
            );
            echo json_encode($output);
        }
   }
    function createEstimateItemsAndSubItems(){
        $this->load->library('form_validation');
		$this->form_validation->set_rules('bri_id', 'Main', 'required|xss_clean');
		$this->form_validation->set_rules('time_profile', 'Time Profile', 'required|xss_clean');
		$this->form_validation->set_rules('batch_profile', 'Batch Profile', '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');
		$estimate_qty=$this->cleanAndValidateText($this->input->post('estimate_qty'));
		$bri_id=$this->cleanAndValidateNumber($this->input->post('bri_id'));
		$product_batch_block=$this->cleanAndValidateNumber($this->input->post('product_batch_block'));
		$est_id=$this->cleanAndValidateNumber($this->input->post('est_id'));
        $time_profile=$this->cleanAndValidateNumber($this->input->post('time_profile'));
        $batch_profile=$this->cleanAndValidateNumber($this->input->post('batch_profile'));
        $product_id=$this->cleanAndValidateNumber($this->input->post('product_id'));
        $datetime=$this->cleanAndValidateNumber($this->input->post('date'));
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
               if($estimate_qty<0.001){
                   $st = array('status' =>0,'validation' =>'Invalid Quantity' );
                     echo json_encode($st); 
                   return false;
               }
           $mod_data= $this->Production_Estimate_Model->loadProductBlockDetail($product_batch_block,125567);
           
          $reminder=$estimate_qty%$batch_profile;
          $extra_batch=0;
          if($reminder>0){$extra_batch=1;}
          if($batch_profile==1){
              $no_of_batches=1;
              $production_qty=$estimate_qty;
              $exra_qty=0;
          }else{
               $no_of_batches=(($estimate_qty-$reminder)/$batch_profile)+$extra_batch;
               $production_qty=$no_of_batches*$batch_profile;
               $exra_qty=$production_qty-$estimate_qty;
          }
            $data=array(
			'order_request_item_id'=>$bri_id,
			'pcem_id'=>$est_id,
			'product_block_id'=>$product_batch_block,
			'allocated_qty'=>$estimate_qty,	
			'product_id'=>$product_id,	
			'extra_output_qty'=>$exra_qty,	
			'final_output_qty'=>$production_qty,
			'orq_selected_by'=>$this->session->userdata('ss_user_id'),
			'orq_by_date_time'=>date('Y-m-d H:i:s'),
			'orq'=>$estimate_qty,
			'no_of_batches'=>$no_of_batches,
			'pcei_user'=>$this->session->userdata('ss_user_id'),
            'pcei_date_time'=>date('Y-m-d H:i:s'),
            'time_profile_id'=>$time_profile,
            'batch_profile'=>$batch_profile,
            'required_date'=>date('Y-m-d H:i:s', strtotime($datetime)),
		);
		$last_id= $this->executeSaveItemTable($data);
		$mod_items= $this->Production_Estimate_Model->loadProductBlockItemList($product_batch_block,125568);
		$total_material_cost=0;
		foreach($mod_items as $row){
		    $material_cost=($row['product_mat_cost']*($row['product_qty']/$mod_data['batch_qty'])*$production_qty);
		    $total_material_cost+=$material_cost;
		    $item_data=array();
		    $item_data=array(
			'pcei_id'=>$last_id,
			'product_mat_id'=>$row['product_id'],
			'pcesi_final_qty'=>(($row['product_qty']/$mod_data['batch_qty'])*$production_qty),
			'original_qty'=>$row['product_qty']/$mod_data['batch_qty'],	
			'no_of_batch'=>$no_of_batches,
			'pcesi_user'=>$this->session->userdata('ss_user_id'),
			'pcesi_date_time'=>date('Y-m-d H:i:s'),
			'pcesi_tot_cost'=>$material_cost,
		    'pcesi_cost'=>$row['product_mat_cost'],
		    );
		    $this->executeSaveSubItemTable($item_data);
		}
		$data=array(
			'pcei_cost'=>$total_material_cost
		);
		$this->executeUpdateItemTable($last_id,$data);
		$data=array(
			'last_modify_by'=>$this->session->userdata('ss_user_id'),
            'last_modify_on'=>date('Y-m-d H:i:s'),
		);
		$this->executeUpdateMasterTable($est_id,$data);
		$st = array('status' =>1,'validation' =>'Added');
        echo json_encode($st);
		}
    }
    function deleteEstimateSubItemsAndItems(){
         $id=$this->getId();
         $request_data=$this->Production_Estimate_Model->deleteSubItemsWithItem($id);
         $st = array('status' =>1,'validation' =>'Deleted');
         echo json_encode($st);
    }
    function finishProductionEstimate(){
        $id=$this->getId();
        $result=$this->executeSelectMasterTable($id);
        $result=$this->Production_Estimate_Model->runSelectOrderRequestByMasterId($result['pcem_request_id']);
        $status=1;
        foreach($result as $row){
              $total_allocated_qty=$this->Production_Estimate_Model->loadTotalAllocatedEstiateQty($row['bri_id'],125564);
              if($row['approved_qty']!=$total_allocated_qty){
                $status=0;
                continue;
              }
        }
        if($status==1){
            $cost_total=$this->Production_Estimate_Model->runSelectSumEstimatedItemByMasterId($id);
            $data=array(
            'pcem_estimated_total_cost'=>$cost_total,
			'last_modify_by'=>$this->session->userdata('ss_user_id'),
            'last_modify_on'=>date('Y-m-d H:i:s'),
            'pcem_staus'=>1,
            'pcem_approval_status'=>1,
			'pcem_approval_by'=>$this->session->userdata('ss_user_id'),
			'pcem_approval_on'=>date("Y-m-d H:i:s"),
		    );
            $this->executeUpdateMasterTable($id,$data);
            $st = array('status' =>1,'validation' =>'Updated');
            echo json_encode($st);
        }else{
           $st = array('status' =>0,'validation' =>'Estimate Not Completed. Please Check Again !');
            echo json_encode($st); 
        }
        return false;
        
        
    }
    function loadProductionEstimateDetails(){
        $id=$this->getId();
        $data=array();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'listPendingEstimate';
        $data=$this->setEstimateBasicDataUsingMasterID($id,$data);
        $data=$this->setEstimateBasicDataUsingItemID($id,$data);
        $data=$this->setEstimateBasicDataUsingSubItemID($id,$data);
        $this->load->view('estimate/estimated_details',$data);
       
    }
    
    function loadgenerateNewBatch(){
        $data=array();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'generate_new_batch';
        $this->load->view('estimate/completed_estimate',$data);
    }
    function getListCompletedEstimate(){
        $request_data=$this->getClientSideDataTableParameters();
        $result_array=$this->getCompletedEstimateListForBasicDataTableOnServerSide($request_data);
        $values=$result_array['values'];
        $value_count=$result_array['value_count'];
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->pcem_id_ref_no;
                $row[]               = $products->pcem_date_time;
                $row[]               = $products->brm_ref_no;
                $row[]               = $products->pcem_estimated_total_cost;
                $row[]               = $products->user_first_name;
                $row[]               = $products->last_modify_on;
                $row[]               = $products->modify_by;
                $row[]               = $products->warehouse_name;
                $row[]               = $products->pcem_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 style="cursor: pointer;" onclick="generate_estimate_batch('. $products->pcem_id .')"><i class="glyphicon fa fa-check"></i> SEND TO PRODUCTION</a></li>
                            <li><a href="'.base_url('estimate/loadProductionEstimateDetails?id='. $products->pcem_id ).'"  style="cursor: pointer;"><i class="glyphicon fa fa-info-circle"> </i> 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 delete_estimation(){
	    $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_Estimate_Model->delete_estimate_master_table_by_primary_id($id);
         $result=$this->Production_Estimate_Model->delete_estimate_item_table_by_secondory_id($id);
          $st = array('status' =>1,'validation' =>'Updated');
          echo json_encode($st);
		}
	}
    
    
    
    
    
    
    
  
  
  
  
  
   
}