<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
include('core_manufacture_preparation.php');
class Manufacture_Preparation extends Core_Manufacture_Preparation
{
    public function __construct()
    {
        ini_set('display_errors', 1);
        parent::__construct();
        date_default_timezone_set("Asia/Colombo");
    }
    function loadPendingManufacture()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'pending_manufacture';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/pending_manufacture', $data);
    }
    function getListPendingProduction()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getPendingProductionListForBasicDataTable($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 $row) {
                $nestad_data   = array();
                $nestad_data[] = $row['pbi_ref_no'];
                $nestad_data[] = $row['product_code'];
                $nestad_data[] = $row['product_name'];
                $nestad_data[] = $row['pbi_qty'];
                $nestad_data[] = $row['psnm_ref_no'];
                $nestad_data[] = $row['warehouse_name'];
                $nestad_data[] = $row['user_first_name'];
                $action        = '<button class="btn btn-xs btn-primary" id="send' . $row['pbi_id'] . '" name="send' . $row['pbi_id'] . '" onclick="sendToProduction(' . $row['pbi_id'] . ')" >Send To Production</button>';
                $nestad_data[] = $action;
                $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 sendToProduction()
    {
        $id = $this->getId();
        if ($id > 0) {
            $data   = array(
                'prodcution_start_status' => 1,
                'production_start_by' => $this->session->userdata('ss_user_id'),
                'prodcution_start_on' => date('Y-m-d H:i:s')
            );
            $status = $this->executeUpdateMasterTable($id, $data);
            $st     = array(
                'status' => $status,
                'validation' => 'Successfully Updated ',
                'result' => 'null'
            );
            echo json_encode($st);
        } else {
            $st = array(
                'status' => 0,
                'validation' => 'Not Found',
                'result' => 'null'
            );
            echo json_encode($st);
        }
    }
    function loadOngoingManufacture()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $this->load->model('Production_Estimate_Model');
        $data['main_menu_name']    = $this->main_menu_name;
        $data['sub_menu_name']     = 'ongoing_manufacture';
        $data['warehouse_list']    = $this->Warehouse_Model->get_all_warehouse();
        $data['department_list']    = $this->Warehouse_Model->getDepartment(); 
        $data['time_profile_list'] = $this->Production_Estimate_Model->loadTimeProfile(125567);
        $data['defect_list']       = $this->Production_Estimate_Model->defect_list();
        $this->load->view('manufacture/ongoing_manufacture', $data);
    }
    function getListOngoingProduction()
    {
        // $request_data=$this->getClientSideBasicDataTableParameters();
        $warehouse_id    = $this->input->get('warehouse_id');
        $req_date        = $this->input->get('req_date');
        $req_date        = '';//date('Y-m-d H:i:s', strtotime($req_date));
        $time_profile_id = $this->input->get('time_profile_id');
        $department_id = $this->input->get('department_id');
        
        
        $result_array    = $this->Manufacture_Preparation_Model->getOngoingProductionNew($warehouse_id, $time_profile_id, $req_date,$department_id);
        $values          = $result_array; //$result_array['values'];
        $value_count     = count($result_array); //$result_array['value_count'];
        $totalData       = $value_count;
        $totalFiltered   = $totalData;
        $data            = array();
        if (!empty($values)) {
            foreach ($values as $row) {
                $nestad_data     = array();
                $nestad_data[]   = $row['product_name'];
                $nestad_data[]   = $row['product_code'];
                $nestad_data[]   = $row['pbi_ref_no'];
                $nestad_data[]   = $row['pbi_qty'];
                $nestad_data[]   = $row['pbi_required_date'];
                $nestad_data[]   = $row['mtp_name'];
                $addtional_items = '<button class="btn btn-success btn-sm " onClick="req_aaddit(' . $row['pbi_id'] . ')">REQUEST  ITEMS <i class="fa fa-plus  fa-2x fa-fw"></i></button> ';
                $status          = ' <button class="btn btn-warning btn-sm " onClick="start_production(' . $row['pbi_id'] . ')">START MANUFACTURE <i class="fa fa-clock-o  fa-2x fa-fw"></i></button> ' . $addtional_items;
                if ($row['prodcution_start_status'] == 1) {
                    $status = 'QC QTY  <input id="qc_qty_' . $row['pbi_id'] . '" name="qc_qty" class="" value="" required> <button class="btn btn-primary btn-sm" onclick="approval_qc(' . $row['pbi_id'] . ','.$row['pbi_qty'].')">FINISH MANUFACTURE <i class="fa fa-circle-o-notch fa-spin fa-2x fa-fw"></i></button> ' . $addtional_items;
                }
                $nestad_data[] = '<span class="col-sm-12"> <button class="btn btn-default btn-sm" onclick="show_ingredients(' . $row['pbi_id'] . ')">CHECK INGREDIENTS</button> ' . $status . "</span>";
                //$action='<button class="btn btn-xs btn-primary" id="send'.$row['pbi_id'].'" name="send'.$row['pbi_id'].'" onclick="finish_production('.$row['pbi_id'].')" >Finish Production</button>';
                //--------------------------------
                //-------------------------------------
                /*   $action='<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=""  style="cursor: pointer;" id="send'.$row['pbi_id'].'" name="send'.$row['pbi_id'].'" onclick="finish_production('.$row['pbi_id'].')"><i class="glyphicon fa fa-check"></i> Finish Production</a></li>
                <!--<li><a href="'.base_url('manufacture_preparation/loadRequestAddtionalItems?id='. $row['pbi_id'] ).'"  style="cursor: pointer;"><i class="glyphicon fa fa-plus-circle"></i> Request Additional Items</a></li>-->
                <!--<li><a href="'.base_url('manufacture_preparation/loadRemoveRemainingItems?id='. $row['pbi_id'] ).'"  style="cursor: pointer;"><i class="glyphicon fa fa-minus-circle"></i> Send Remaining Items</a></li>-->
                <li><a href="#"  onclick="show_ingredients('.$row['pbi_id'].')"><i class="glyphicon fa fa-eve"></i> Ingredients</a></li>
                
                
                ';*/
                // $nestad_data[]  =$action;
                $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 startProduction()
    {
        $id = $this->getId();
        if ($id > 0) {
            $data   = array(
                'prodcution_start_status' => 1,
                'production_start_by' => $this->session->userdata('ss_user_id'),
                'prodcution_start_on' => date('Y-m-d H:i:s')
            );
            $status = $this->executeUpdateMasterTable($id, $data);
            $st     = array(
                'status' => $status,
                'validation' => 'Successfully Updated ',
                'result' => 'null'
            );
            echo json_encode($st);
        } else {
            $st = array(
                'status' => 0,
                'validation' => 'Not Found',
                'result' => 'null'
            );
            echo json_encode($st);
        }
    }
    function finishProduction()
    {
        $id = $this->getId();
        if ($id > 0) {
            $data   = array(
                'production_end_status' => 1,
                'production_end_by' => $this->session->userdata('ss_user_id'),
                'production_end_on' => date('Y-m-d H:i:s')
            );
            $status = $this->executeUpdateMasterTable($id, $data);
            $st     = array(
                'status' => $status,
                'validation' => 'Successfully Updated ',
                'result' => 'null'
            );
            echo json_encode($st);
        } else {
            $st = array(
                'status' => 0,
                'validation' => 'Not Found',
                'result' => 'null'
            );
            echo json_encode($st);
        }
    }
    function loadManufacturedProduct()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'manufactured_manufacture';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/manufactured_manufacture', $data);
    }
    function getListManufacturedProduction()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getManufacturedProductionListForBasicDataTable($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 $row) {
                $nestad_data   = array();
                $nestad_data[] = $row['pbi_ref_no'];
                $nestad_data[] = $row['product_code'];
                $nestad_data[] = $row['product_name'];
                $nestad_data[] = $row['pbi_qty'];
                $nestad_data[] = $row['psnm_ref_no'];
                $nestad_data[] = $row['warehouse_name'];
                $nestad_data[] = $row['user_first_name'];
                $action        = '<button class="btn btn-xs btn-primary" id="send' . $row['pbi_id'] . '" name="send' . $row['pbi_id'] . '" onclick="finish_production(' . $row['pbi_id'] . ')" >Finish Production</button>';
                $nestad_data[] = ""; //$action;
                $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 loadQCProcess()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'qc_process';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/quality_check', $data);
    }
    function getListPendingQCProduction()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getManufacturedProductionListForBasicDataTable($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 $row) {
                $nestad_data   = array();
                $nestad_data[] = $row['pbi_ref_no'];
                $nestad_data[] = $row['product_code'];
                $nestad_data[] = $row['product_name'];
                $nestad_data[] = $row['pbi_qty'];
                $nestad_data[] = $row['output_qty'];
                $nestad_data[] = $row['defect_qty'];
                $nestad_data[] = $row['warehouse_name'];
                $nestad_data[] = $row['user_first_name'];
                $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_qc(' . $row['pbi_id'] . ')"><i class="glyphicon fa fa-check"></i> QC Approval</a></li>
                               <li><a style="cursor: pointer;" onclick="reject_qc(' . $row['pbi_id'] . ')"><i class="glyphicon fa fa-ban"></i> QC Reject</a></li>
                            ';
                $nestad_data[] = $actdes;
                $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 setQcApproval()
    {
        $status  = 0;
        $massage = 'Enter Valid Quantity';
        $this->load->library('form_validation');
        $this->form_validation->set_rules('id', 'Main Recode', 'required|xss_clean');
        $this->form_validation->set_rules('result', 'QC Quntity', 'required|xss_clean| greater_than[0]');
        $master_id = $this->cleanAndValidateNumber($this->input->post('id'));
        $qty       = $this->cleanAndValidateNumber($this->input->post('result'));
        $defect_reason       = $this->cleanAndValidateNumber($this->input->post('defect_reason'));
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            if($qty<=0){
                $st = array(
                'status' => 0,
                'validation' => "INVALID QTY"
            );
            echo json_encode($st);
            return false;
            }
            $total_actual_cost    = $this->Manufacture_Preparation_Model->runGetSumBatchMaterialCost($master_id);
            $total_addtional_cost = $this->Manufacture_Preparation_Model->runGetSumAdditionalBatchMaterialCost($master_id);
            $row_data             = $this->executeSelectMasterTable($master_id);
            if (isset($row_data['pbi_qty'])) {
                if ($qty) {
                    $remain_qty = 0;
                    if ($row_data['pbi_qty'] < $qty) {
                        $remain_qty = 0;
                    }
                    if ($row_data['pbi_qty'] > $qty) {
                        $remain_qty = $row_data['pbi_qty'] - $qty;
                    }
                    $extra_qty=0;
                    $extra_value=0;
                    if($row_data['pbi_qty'] < $qty){
                        $extra_qty=$qty-$row_data['pbi_qty'];
                        $extra_value=($total_actual_cost / $row_data['pbi_qty'])*$extra_qty;
                    }
                    $data = array(
                        'pbi_lost_value' => (($total_actual_cost / $row_data['pbi_qty']) * $remain_qty),
                        'pbi_additional_cost' => $total_addtional_cost,
                        'pbi_total_actual_cost' => $total_actual_cost,
                        'pbi_unit_cost' => ($total_actual_cost / $row_data['pbi_qty']),
                        'defect_qty' => $remain_qty,
                        'output_qty' => $qty,
                        'qc_status' => 1,
                        'qc_by' => $this->session->userdata('ss_user_id'),
                        'qc_on' => date('Y-m-d H:i:s'),
                        'production_end_status' => 1,
                        'production_end_on' => date('Y-m-d H:i:s'),
                        'production_end_by' => $this->session->userdata('ss_user_id'),
                        'manufacture_defect_reason_id' => $defect_reason,
                        'extra_output_qty' => $extra_qty,
                        'extra_output_value' => $extra_value,
                    );
                    $this->executeUpdateMasterTable($master_id, $data);
                    $data = array(
                        'product_cost' => ($total_actual_cost / $row_data['pbi_qty'])
                    );
                    $this->Manufacture_Preparation_Model->update_product_table($row_data['pbi_product_id'], $data);
                    $status  = 1;
                    $massage = "Sucssesfully Updated!";
                } else {
                    $status  = 0;
                    $massage = "Not Valid Quntity";
                }
            } else {
                $status  = 0;
                $massage = "Not Found";
            }
            $st = array(
                'status' => $status,
                'validation' => $massage,
                'result' => 'null'
            );
            echo json_encode($st);
        }
    }
    function setQcApprovalReject()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('id', 'Main Recode', 'required|xss_clean');
        $master_id = $this->cleanAndValidateNumber($this->input->post('id'));
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            $total_actual_cost    = $this->Manufacture_Preparation_Model->runGetSumBatchMaterialCost($master_id);
            $total_addtional_cost = $this->Manufacture_Preparation_Model->runGetSumAdditionalBatchMaterialCost($master_id);
            $row_data             = $this->executeSelectMasterTable($master_id);
            if (isset($row_data['pbi_qty'])) {
                if ($row_data['pbi_qty']) {
                    $data = array(
                        'pbi_lost_value' => $total_actual_cost,
                        'pbi_additional_cost' => $total_addtional_cost,
                        'pbi_total_actual_cost' => $total_actual_cost,
                        'pbi_unit_cost' => ($total_actual_cost / $row_data['pbi_qty']),
                        'defect_qty' => $row_data['pbi_qty'],
                        'output_qty' => 0,
                        'qc_status' => 2,
                        'qc_by' => $this->session->userdata('ss_user_id'),
                        'qc_on' => date('Y-m-d H:i:s')
                    );
                    $this->executeUpdateMasterTable($master_id, $data);
                    $status  = 1;
                    $massage = "Sucssesfully Updated!";
                } else {
                    $status  = 0;
                    $massage = "Not Valid Quntity";
                }
            } else {
                $status  = 0;
                $massage = "Not Found";
            }
        }
        $st = array(
            'status' => $status,
            'validation' => $massage,
            'result' => 'null'
        );
        echo json_encode($st);
    }
    function loadReadyForGRN()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'ready_for_grn';
        $data['department_list']    = $this->Warehouse_Model->getDepartment(); 
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/ready_for_grn', $data);
    }
    function getListReadyForGRN()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getQCProductionListForBasicDataTable($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 $row) {
                $nestad_data   = array();
                $nestad_data[] = $row['pbi_ref_no'];
                $nestad_data[] = $row['product_code'];
                $nestad_data[] = $row['product_name'];
                $nestad_data[] = $row['pbi_qty'];
                $nestad_data[] = $row['output_qty'];
                $nestad_data[] = $row['defect_qty'];
                $nestad_data[] = $row['pbi_unit_cost'];
                $nestad_data[] = $row['pbi_lost_value'];
                $nestad_data[] = $row['warehouse_name'];
                $nestad_data[] = $row['user_first_name'];
                $nestad_data[] = $row['qc_on'];
                $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="req_return_additional_items(' . $row['pbi_id'] . ')"><i class="glyphicon fa fa-undo"></i> RETURN EXTRA QTY </a></li>
                               <!--<li><a style="cursor: pointer;" onclick="reject_qc(' . $row['pbi_id'] . ')"><i class="glyphicon fa fa-ban"></i> QC Reject</a></li>-->
                               </ui></div>
                            ';
                $nestad_data[] = $actdes;
                $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 loadCreateNewGTN()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'not_completed_gtn';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/create_new_gtn', $data);
    }
    function createNewGTN()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required|xss_clean');
        $this->form_validation->set_rules('ref_no', 'Ref No ', 'xss_clean');
        $this->form_validation->set_rules('note', 'Note', 'xss_clean');
        $ref_no       = $this->cleanAndValidateText($this->input->post('ref_no'));
        $warehouse_id = $this->cleanAndValidateNumber($this->input->post('warehouse_id'));
        $note         = $this->cleanAndValidateText($this->input->post('note'));
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            $data    = array(
                'pgrnm_doc_no' => $ref_no,
                'pgrnm_warehouse_id' => $warehouse_id,
                'pgrnm_note' => $note,
                'pgrnm_user_id' => $this->session->userdata('ss_user_id'),
                'pgrnm_date_time' => date('Y-m-d H:i:s'),
                'pgrnm_ref_no' => $this->Common_Model->gen_ref_number('pgrnm_id', 'production_grn', 'MGRN')
            );
            $last_id = $this->executeSaveItemTable($data);
            $st      = array(
                'status' => 1,
                'validation' => 'Added',
                'result' => $last_id
            );
            echo json_encode($st);
        }
    }
    function loadQCPassedProduct()
    {
        $this->load->model('Warehouse_Model');
        $id                     = $this->getId();
        $data                   = array();
        $data['details']        = $this->executeSelectItemTable($id);
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'production_material_in_out';
         $data['department_list']    = $this->Warehouse_Model->getDepartment(); 
        $data['stn_id']         = $id;
        $this->load->view('manufacture/update_gtn', $data);
    }
    function getListPendingGTNProductionBatch()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getQCProductionListForBasicDataTable($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 $row) {
                $nestad_data     = array();
                $trransfered_qty = $this->Manufacture_Preparation_Model->get_transferred_gt_qty($row['pbi_id']);
                $nestad_data[]   = $row['pbi_ref_no'];
                $nestad_data[]   = $row['product_code'];
                $nestad_data[]   = $row['product_name'];
                $nestad_data[]   = $row['output_qty'];
                $nestad_data[]   = $trransfered_qty;
                $nestad_data[]   = $row['output_qty'] - $trransfered_qty;
                // $action='<input type="checkbox" id="pbi_id'.$row['pbi_id'].'" name="pbi_id[]" value="'.$row['pbi_id'].'">';
                $action          = '<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="goods_transfer(' . $row['pbi_id'] . ')"><i class="glyphicon fa fa-exchange"></i> Transfer To Store </a></li>
                            
                               </ui></div>
                            ';
                $nestad_data[]   = $action;
                $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 saveGTNItems()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required|xss_clean');
        $this->form_validation->set_rules('master_id', 'Main Recode', 'required|xss_clean');
        $this->form_validation->set_rules('pbi_id', 'Select Item', 'required');
        $master_id    = $this->cleanAndValidateNumber($this->input->post('master_id'));
        $warehouse_id = $this->cleanAndValidateNumber($this->input->post('warehouse_id'));
        $pbi_id       = $this->cleanAndValidateArray($this->input->post('pbi_id'));
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            foreach ($pbi_id as $row) {
                $details = $this->Manufacture_Preparation_Model->runGetBtachProductDetails($row);
                $data    = array(
                    'pgrnm_id' => $master_id,
                    'pbi_id' => $row,
                    'product_id' => $details['pbi_product_id'],
                    'product_mat_id' => $details['sub_product_of'],
                    'quantity' => $details['output_qty'],
                    'pgrni_unit_cost' => $details['pbi_unit_cost'],
                    'pgrni_total_cost' => $details['pbi_unit_cost'] * $details['output_qty'],
                    'pgrni_product_type_id' => $details['product_type_id']
                );
                $last_id = $this->executeSaveSubItemTable($data);
                $data    = array(
                    'finish_status' => 1,
                    'finish_by' => $this->session->userdata('ss_user_id'),
                    'finish_on' => date('Y-m-d H:i:s')
                );
                $this->executeUpdateMasterTable($row, $data);
            }
            $st = array(
                'status' => 1,
                'validation' => 'Added',
                'result' => $last_id
            );
            echo json_encode($st);
        }
    }
    function getListSelectedGTNProductionBatch()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getQCSelectedGTNProductionListForBasicDataTable($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 $row) {
                $nestad_data   = array();
                $nestad_data[] = $row['pbi_ref_no'];
                $nestad_data[] = $row['product_code'];
                $nestad_data[] = $row['product_name'];
                $nestad_data[] = $row['quantity'];
                $nestad_data[] = $row['user_first_name'];
                $nestad_data[] = $row['qc_on'];
                $action        = '<button class="btn btn-xs btn-danger" id="func' . $row['pgrnp_id'] . '" name="func' . $row['pgrnp_id'] . '" onclick="rollback(' . $row['pgrnp_id'] . ')" >Roll-Back</button>';
                if ($row['pgrnm_status'] == 1) {
                    $action = '<span class="btn btn-xs btn-success"> Finished </span>';
                }
                $nestad_data[] = $action;
                $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 rollbackGTNItemToPendingStatus()
    {
        $id     = $this->getId();
        $result = $this->executeSelectSubItemsTable($id);
        if (isset($result['pbi_id'])) {
            $main_recode_id = $result['pbi_id'];
            $data           = array(
                'pbi_rollback_status' => 1,
                'finish_status' => 0,
                'pbi_rollback_by' => $this->session->userdata('ss_user_id'),
                'pbi_rollback_on' => date('Y-m-d H:i:s')
            );
            $status         = $this->executeUpdateMasterTable($main_recode_id, $data);
            if ($status == 1) {
                $status = $this->executeDeleteSubItemTable($id);
            }
            $st = array(
                'status' => $status,
                'validation' => 'Rollback',
                'result' => 'null'
            );
            echo json_encode($st);
        } else {
            $st = array(
                'status' => 0,
                'validation' => 'Not Found',
                'result' => 'null'
            );
            echo json_encode($st);
        }
    }
    function FinishGTN()
    {
        $id     = $this->getId();
        $result = $this->executeSelectSubItemsTableUsingSecondaryId($id);
        if ($result) {
        } else {
            $result = array();
        }
        $recode_count = 0;
        foreach ($result as $row) {
            $recode_count++;
            if ($row['pgrni_product_type_id'] == 2) {
                $data = array(
                    'pgrnm_id' => $row['pgrnm_id'],
                    'pbi_id' => $row['pbi_id'],
                    'product_id' => $row['product_id'],
                    'product_mat_id' => $row['product_mat_id'],
                    'quantity' => $row['quantity'],
                    'pgrnp_id' => $row['pgrnp_id']
                );
                $this->Manufacture_Preparation_Model->runSaveIntermediateItems($data);
            }
        }
        $data = array(
            'pgrnm_status' => 1,
            'finish_by' => $this->session->userdata('ss_user_id'),
            'finish_on' => date('Y-m-d H:i:s')
        );
        if ($recode_count > 0) {
            $status  = $this->executeUpdateItemTable($id, $data);
            $message = 'Completed';
        } else {
            $status  = 0;
            $message = 'You Must Select at least 1 Production Batch !';
        }
        $st = array(
            'status' => $status,
            'validation' => $message,
            'result' => 'null'
        );
        echo json_encode($st);
    }
    function loadNotCompletedGTN()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'not_completed_gtn';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/pending_gtn', $data);
    }
    function getListPendingInternalGTN()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getPendingInternalGTNBasicDataTable($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->pgrnm_ref_no;
                $row[]  = $products->pgrnm_doc_no;
                $row[]  = $products->pgrnm_date_time;
                $row[]  = $products->user_first_name;
                $row[]  = $products->warehouse_name;
                $row[]  = $products->pgrnm_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('manufacture_preparation/loadQCPassedProduct?id=' . $products->pgrnm_id) . '"  style="cursor: pointer;"><i class="glyphicon fa fa-edit"></i> Update GTN</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 loadRequestAddtionalItems()
    {
        $id                       = $this->getId();
        $data                     = array();
        $data['product_batch_id'] = $id;
        $data['details']          = $this->Manufacture_Preparation_Model->runGetProductBatchDetails($id);
        $data['main_menu_name']   = $this->main_menu_name;
        $data['sub_menu_name']    = 'production_material_in_out';
        $this->load->view('manufacture/request_add_material', $data);
    }
    function getlistAdditionalBatchItem()
    {
        $this->load->model('Stock_Counter_Model');
        ini_set('display_errors', 1);
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getPendingAdditionalBatchItemBasicDataTable($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 $row) {
                $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['pbsi_original_cost'];
                $nestad_data[] = $row['pbis_qty'];
                $nestad_data[] = $row['pbsi_cost_total'];
                $action        = '';
                if ($row['request_type'] == 1) {
                    $action = '<span class="btn btn-xs btn-success">Original</span>';
                } else {
                    $action = '<span class="btn btn-xs btn-warning">Additional</span> ';
                    if ($row['request_type'] == 2 && $row['pbsi_issue_status'] == 0) {
                        $action .= ' <button class="btn btn-xs btn-danger"  onclick="rollback(' . $row['pbsi_id'] . ')" > <i class="fa fa-trash-o"></i> </button>';
                    }
                }
                $nestad_data[] = $action;
                $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);
        }
    }
    public function saveAdditionalBatchMaterial()
    {
        $this->load->library('form_validation');
        $product_id         = $this->input->post('product_id');
        $product_batch_id   = $this->input->post('product_batch_id');
        $allocated_quantity = $this->input->post('allocated_quantity');
        $warehouse_id       = $this->input->post('warehouse_id');
        $this->form_validation->set_rules('product_id', 'Product', 'required|xss_clean');
        $this->form_validation->set_rules('product_batch_id', 'Batch', 'required|xss_clean');
        $this->form_validation->set_rules('allocated_quantity', 'Quntity', 'required|xss_clean');
        $this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required|xss_clean');
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            $product = $this->Manufacture_Preparation_Model->runGetProductMAterialDetails($product_id);
            if (isset($product['product_mat_id'])) {
            } else {
                exit;
            }
            $data             = array(
                'pbi_id' => $product_batch_id,
                'pbsi_product_mat_id' => $product_id,
                'pbis_qty' => $allocated_quantity,
                'pbsi_original_cost' => $product['product_mat_cost'],
                'pbsi_cost_total' => $product['product_mat_cost'] * $allocated_quantity,
                'request_type' => 2
            );
            $last_id          = $this->Manufacture_Preparation_Model->runSaveBatchSubItemTable($data);
            $data             = array(
                'psnm_warehouse_id' => $warehouse_id,
                'psnm_user_id' => $this->session->userdata('ss_user_id'),
                'psnm_date_time' => date('Y-m-d H:i:s'),
                'psnm_ref_no' => $this->Common_Model->gen_ref_number('psnm_id', 'production_store_note_master', 'STN'),
                'psnm_status' => 1
            );
            $last_stn_mstr_id = $this->Manufacture_Preparation_Model->runSaveSTNMasterTable($data);
            $data             = array(
                'psnm_id' => $last_stn_mstr_id,
                'pbi_id' => $product_batch_id
            );
            $last_stn_item_id = $this->Manufacture_Preparation_Model->runSaveSTNItemTable($data);
            $data             = array(
                'psnm_id' => $last_stn_mstr_id,
                'psni_id' => $last_stn_item_id,
                'pbi_id' => $product_batch_id,
                'pbsi_id' => $last_id
            );
            $this->Manufacture_Preparation_Model->runSaveSTNSubItemTable($data);
            $st = array(
                'status' => 1,
                'validation' => 'Added'
            );
            echo json_encode($st);
        }
    }
    function loadRemoveRemainingItems()
    {
        $id                       = $this->getId();
        $data                     = array();
        $data['product_batch_id'] = $id;
        $data['details']          = $this->Manufacture_Preparation_Model->runGetProductBatchDetails($id);
        $data['main_menu_name']   = $this->main_menu_name;
        $data['sub_menu_name']    = 'production_material_in_out';
        $this->load->view('manufacture/remove_remaining_material', $data);
    }
    function getlistIssuedBatchItem()
    {
        $this->load->model('Stock_Counter_Model');
        ini_set('display_errors', 1);
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getIssuedBatchItemBasicDataTable($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 $row) {
                $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['unit_price'];
                $nestad_data[] = $row['quantity'];
                $nestad_data[] = $row['cost'];
                $action        = '';
                if ($row['psio_request_type'] == 3) {
                    $action = '<span class="btn btn-xs btn-success">Removed Items</span>';
                } else {
                    $action = '<span class="btn btn-xs btn-warning">Original</span> ';
                    if ($row['psio_request_type'] == 1 && $row['pick_up_status'] == 1) {
                        $action .= ' <button class="btn btn-xs btn-danger"  onclick="send_back(' . $row['psio_id'] . ')" > <i class="fa fa-undo">Send Back</i> </button>';
                    }
                }
                $nestad_data[] = $action;
                $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);
        }
    }
    public function saveSendBackBatchMaterial()
    {
        $this->load->library('form_validation');
        $issue_id           = $this->input->post('id');
        $allocated_quantity = $this->input->post('result');
        $this->form_validation->set_rules('id', 'Product', 'required|xss_clean');
        $this->form_validation->set_rules('result', 'Quntity', 'required|xss_clean');
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            $sendbak_qty    = ($allocated_quantity * -1);
            $issued_details = $this->Manufacture_Preparation_Model->runGetMAterialIssueDetails($issue_id);
            $product        = $this->Manufacture_Preparation_Model->runGetProductMAterialDetails($issued_details['product_mat_id']);
            if ($issued_details['quantity'] < $allocated_quantity) {
                $st = array(
                    'status' => 0,
                    'validation' => 'Invalid Qty'
                );
                echo json_encode($st);
                return false;
            }
            if (isset($product['product_mat_id'])) {
            } else {
                exit;
            }
            $data    = array(
                'pbi_id' => $issued_details['pbi_id'],
                'pbsi_product_mat_id' => $issued_details['product_mat_id'],
                'pbis_qty' => $sendbak_qty,
                'pbsi_original_cost' => $product['product_mat_cost'],
                'pbsi_cost_total' => $product['product_mat_cost'] * $sendbak_qty,
                'request_type' => 3,
                'pbsi_issue_status' => 1
            );
            $last_id = $this->Manufacture_Preparation_Model->runSaveBatchSubItemTable($data);
            $data    = array(
                'pbi_id' => $issued_details['pbi_id'],
                'pbsi_id' => $issued_details['pbsi_id'],
                'psni_id' => $issued_details['psni_id'],
                'psnm_id' => $issued_details['psnm_id'],
                'psoi_id' => $issued_details['psoi_id'],
                'psom_id' => $issued_details['psom_id'],
                'product_mat_id' => $issued_details['product_mat_id'],
                'product_mat_batch_id' => $issued_details['product_mat_batch_id'],
                'unit_price' => $issued_details['unit_price'],
                'cost' => $issued_details['unit_price'] * $sendbak_qty,
                'quantity' => $sendbak_qty,
                'stock_in' => $allocated_quantity,
                'psio_issue_by' => $this->session->userdata('ss_user_id'),
                'psio_issue_on' => date('Y-m-d H:i:s'),
                'stock_out' => 0,
                'psio_request_type' => 3,
                'pick_up_status' => 1
            );
            $this->Manufacture_Preparation_Model->runSaveSTNIssueItemTable($data);
            $st = array(
                'status' => 1,
                'validation' => 'Added'
            );
            echo json_encode($st);
            return true;
        }
    }
    function getIngredients()
    {
        $this->load->model('Stock_Counter_Model');
        $id               = $this->getId();
        $items            = $this->Manufacture_Preparation_Model->runGetPendingAdditionalBatchItem($id);
        $table_start      = '
<input type="button" id="btn" value="Print" onclick="printDiv();">
        
         <div id="DivIdToPrint">
        <table  class="table" >';
        $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></tr>';
        $currant_stock    = 0;
        foreach ($items as $lab) {
            $currant_stock = $this->Stock_Counter_Model->get_stock_balance('', $lab['pbsi_product_mat_id']);
            $table_body .= '<tr><td>' . $lab['product_mat_code'] . ' - ' . $lab['product_mat_name'] . ' </td><td>' . $lab['unit_name'] . '</td><td>' . number_format($lab['pbis_qty'], 2, ".", "") . '</td> <td>' . number_format($currant_stock, 2, ".", "") . '</td></tr>';
        }
        $complete_table = $table_start . $table_body . $table_end.'</div>';
        $st             = array(
            'data' => $complete_table
        );
        echo json_encode($st);
    }
    function getProductionStock()
    {
        ini_set('display_errors', 1);
        $warehouse_id = $this->input->get('warehouse_id');
        $department_id = $this->input->get('department_id');
        $values       = $this->Manufacture_Preparation_Model->getPendingManufactureIngreediantList($warehouse_id,$department_id);
        $data         = array();
        if (!empty($values)) {
            foreach ($values as $row) {
                $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['quantity'];
                $action        = '';
                $nestad_data[] = $action;
                $data[]        = $nestad_data;
            }
            $output = array(
                'data' => $data
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => array()
            );
            echo json_encode($output);
        }
    }
    function request_addtional_items()
    {
        $id   = $this->getId();
        $page = ' <div class="panel panel-default">
            
              <div class="panel-body"> 
               <form action = "#" method = "post"  id="form_bulk_items" name="form_bulk_items" >
                 <div class="col-md-12">
                  <div class="form-group">
                     <label>RAW MATERIAL / VALUE ADDED STOCK  </label>
                    <input  type="hidden" id="product_id"  name="product_id" class="js-data-product-sn-ajax form-control" style="padding:0px 0px; border: none; box-shadow: none" placeholder="-Select Item-" /><!--onChange="setitemselect()"-->
                     <input id="pbi_id" name="pbi_id" type="hidden" class="form-control" value="' . $id . '"/>
                     </div>
                    </div>
                <div class="col-sm-6 ">
                  <div class="form-group">
                    <label> QUANTITY  </label>
                    <input id="req_qty" name="req_qty" type="text" class="form-control" value=""/>
                  </div>
                </div>
                 <div class="col-sm-6 pull-right" >
                  <div class="form-group">
                    <label>&nbsp;&nbsp; </label>
                    <input type="submit" name="add_category" value="ADD" class=" form-control btn btn-primary">
                  </div>
                </div>
                  </form>
                  </div>
        </div>
        
        <script>
          $(".js-data-product-sn-ajax").select2({
        ajax: {
            "type": "POST",
                "url": "' . base_url('manufacture_preparation/get_product_dynamic_row_and_intermediate') . '",
                dataType: "json",
                delay: 0,
                data: function (query) {
                            //alert(1);
                if (!query)
                        query = "";
                return {
                search_string: query,
                 cat_srh: $("#cat_srh").val(),
                  subcategory: $("#subcategory").val(),
                        format: "json"
                };
                },
                results: function (data) {
                return {
                results: $.map(data, function (item) {
                return {
                    //alert();
                text: item.label,
                        slug: item.id,
                        id: item.id
                };
                })
                };
                },
                cache: true
         }
        });
        
    
        </script>
        ';
        $st   = array(
            'data' => $page
        );
        echo json_encode($st);
    }
    public function get_product_dynamic_row_and_intermediate()
    {
        $this->load->model('Stock_Counter_Model');
        $str    = $this->input->post('search_string');
        $result = $this->Manufacture_Preparation_Model->get_row_matirial_and_intermediate_product($str);
        $data   = array();
        foreach ($result as $row) {
            $batch_stock = $this->Stock_Counter_Model->get_stock_balance_batch('', $row['product_mat_id'], $row['batch_id']);
            $nested_data = array(
                'label' => $row['product_mat_code'] . " " . $row['product_mat_name'] . " STOCK : " . $batch_stock,
                'id' => $row['batch_id']
            );
            $data[]      = $nested_data;
        }
        echo json_encode($data);
    }
    public function get_pbi_dynamic_row_and_intermediate()
    {
        $this->load->model('Stock_Counter_Model');
        $str    = $this->input->post('search_string');
        $id     = $this->input->get('id');
        $result = $this->Manufacture_Preparation_Model->get_row_matirial_and_intermediate_product($str);
        $data   = array();
        foreach ($result as $row) {
            $batch_stock = $this->Stock_Counter_Model->get_stock_balance_batch('', $row['product_mat_id'], $row['batch_id']);
            $nested_data = array(
                'label' => $row['product_mat_code'] . " " . $row['product_mat_name'],
                'id' => $row['batch_id']
            );
            $data[]      = $nested_data;
        }
        echo json_encode($data);
    }
    public function save_addtional_request_items()
    {
        $this->load->library('form_validation');
        $product_id = $this->input->post('product_id');
        $pbi_id     = $this->input->post('pbi_id');
        $req_qty    = $this->input->post('req_qty');
        $this->form_validation->set_rules('product_id', 'Product', 'required|xss_clean');
        $this->form_validation->set_rules('pbi_id', 'Main ', 'required|xss_clean');
        $this->form_validation->set_rules('req_qty', 'Quntity', 'required| greater_than[-100]|max_length[20]|xss_clean');
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            
            if($req_qty<=0){
                  $st = array(
                'status' => 0,
                'validation' => 'Invalid Qty'            );
            echo json_encode($st);
            return false;
            }
            
            $product_id_original = $this->Manufacture_Preparation_Model->get_product_id($product_id);
            $data                = array(
                'pbi_id' => $pbi_id,
                'batch_id' => $product_id,
                'req_qty' => $req_qty,
                'request_by' => $this->session->userdata('ss_user_id'),
                'request_on' => date('Y-m-d H:i:s'),
                'product_id' => $product_id_original
            );
            $result              = $this->Manufacture_Preparation_Model->save_additional_requste_master_table($data);
            $st                  = array(
                'status' => 1,
                'validation' => 'Added'
            );
            echo json_encode($st);
        }
    }
    function getAddtionalReqList()
    {
        ini_set('display_errors', 1);
        $warehouse_id = $this->input->get('warehouse_id');
        $values       = $this->Manufacture_Preparation_Model->getAddtionalReqList($warehouse_id);
        $data         = array();
        if (!empty($values)) {
            foreach ($values as $row) {
                $nestad_data = array();
                $option      = '<li><a href="#"  style="cursor: pointer;"  onclick="issue_production(' . $row['ad_item_id'] . ')"><i class="glyphicon fa fa-check"></i> Issue Item For Production</a></li>';
                $type        = '<span class="btn btn-xs btn-warning">TO BE ISSUE</span>';
                if ($row['request_type'] == 2) {
                    $type   = '<span class="btn btn-xs btn-danger">TO BE GRN</span>';
                    $option = '<li><a href="#"  style="cursor: pointer;"  onclick="issue_production(' . $row['ad_item_id'] . ')"><i class="glyphicon fa fa-check"></i> GRN  TO STORES</a></li>';
                }
                $nestad_data[] = $type;
                $nestad_data[] = $row['product_code'];
                $nestad_data[] = $row['product_name'];
                $nestad_data[] = $row['pbi_ref_no'];
                $nestad_data[] = $row['product_mat_code'];
                $nestad_data[] = $row['product_mat_name'];
                $nestad_data[] = $row['unit_code'];
                $nestad_data[] = $row['req_qty'];
                $nestad_data[] = $row['request_on'];
                $action        = '<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">
                             ' . $option . '
                          
                        
                            
                            
                            ';
                $nestad_data[] = $action;
                $data[]        = $nestad_data;
            }
            $output = array(
                'data' => $data
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => array()
            );
            echo json_encode($output);
        }
    }
    function return_extra_items()
    {
        $id   = $this->getId();
        $page = ' <div class="panel panel-default">
            
              <div class="panel-body"> 
               <form action = "#" method = "post"  id="form_bulk_items" name="form_bulk_items" >
                 <div class="col-md-12">
                  <div class="form-group">
                     <label>RAW MATERIAL / VALUE ADDED STOCK  </label>
                    <input  type="hidden" id="product_id"  name="product_id" class="js-data-product-sn-ajax form-control" style="padding:0px 0px; border: none; box-shadow: none" placeholder="-Select Item-" /><!--onChange="setitemselect()"-->
                     <input id="pbi_id" name="pbi_id" type="hidden" class="form-control" value="' . $id . '"/>
                     </div>
                    </div>
                <div class="col-sm-6 ">
                  <div class="form-group">
                    <label> QUANTITY  </label>
                    <input id="req_qty" name="req_qty" type="text" class="form-control" value=""/>
                  </div>
                </div>
                 <div class="col-sm-6 pull-right" >
                  <div class="form-group">
                    <label>&nbsp;&nbsp; </label>
                    <input type="submit" name="add_category" value="ADD" class=" form-control btn btn-primary">
                  </div>
                </div>
                  </form>
                  </div>
        </div>
        
        <script>
          $(".js-data-product-sn-ajax").select2({
        ajax: {
            "type": "POST",
                "url": "' . base_url('manufacture_preparation/get_pbi_dynamic_row_and_intermediate?id=?' . $id) . '",
                dataType: "json",
                delay: 0,
                data: function (query) {
                            //alert(1);
                if (!query)
                        query = "";
                return {
                search_string: query,
                 cat_srh: $("#cat_srh").val(),
                  subcategory: $("#subcategory").val(),
                        format: "json"
                };
                },
                results: function (data) {
                return {
                results: $.map(data, function (item) {
                return {
                    //alert();
                text: item.label,
                        slug: item.id,
                        id: item.id
                };
                })
                };
                },
                cache: true
         }
        });
        
    
        </script>
        ';
        $st   = array(
            'data' => $page
        );
        echo json_encode($st);
    }
    public function save_return_extra_items()
    {
        $this->load->library('form_validation');
        $product_id = $this->input->post('product_id');
        $pbi_id     = $this->input->post('pbi_id');
        $req_qty    = $this->input->post('req_qty');
        $this->form_validation->set_rules('product_id', 'Product', 'required|xss_clean');
        $this->form_validation->set_rules('pbi_id', 'Main ', 'required|xss_clean');
        $this->form_validation->set_rules('req_qty', 'Quntity', 'required| greater_than[-100]|max_length[20]|xss_clean');
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            $product_id_original = $this->Manufacture_Preparation_Model->get_product_id($product_id);
            $data                = array(
                'pbi_id' => $pbi_id,
                'batch_id' => $product_id,
                'req_qty' => $req_qty * (-1),
                'request_by' => $this->session->userdata('ss_user_id'),
                'request_on' => date('Y-m-d H:i:s'),
                'product_id' => $product_id_original,
                'request_type' => 2
            );
            $result              = $this->Manufacture_Preparation_Model->save_additional_requste_master_table($data);
            $st                  = array(
                'status' => 1,
                'validation' => 'Added'
            );
            echo json_encode($st);
        }
    }
    function saveGTNItemsWithCustomQty()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('result', 'QTY', 'required|xss_clean');
        $this->form_validation->set_rules('gtn_id', 'GTN', 'required|xss_clean');
        $this->form_validation->set_rules('pbi_id', 'BATCH', 'required');
        $master_id = $this->cleanAndValidateNumber($this->input->post('gtn_id'));
        $pbi_id    = $this->cleanAndValidateNumber($this->input->post('pbi_id'));
        $result    = $this->cleanAndValidateNumber($this->input->post('result'));
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            $transfered_qty = $this->Manufacture_Preparation_Model->get_transferred_gt_qty($pbi_id);
            $details        = $this->Manufacture_Preparation_Model->runGetBtachProductDetails($pbi_id);
            $balance_qty    = $details['output_qty'] - $transfered_qty;
            if ($balance_qty < $result) {
                $st = array(
                    'status' => 0,
                    'validation' => 'INVALID QTY',
                    'result' => $master_id
                );
                echo json_encode($st);
                return 0;
            }
            $data           = array(
                'pgrnm_id' => $master_id,
                'pbi_id' => $pbi_id,
                'product_id' => $details['pbi_product_id'],
                'product_mat_id' => $details['sub_product_of'],
                'quantity' => $result,
                'pgrni_unit_cost' => $details['pbi_unit_cost'],
                'pgrni_total_cost' => $details['pbi_unit_cost'] * $result,
                'pgrni_product_type_id' => $details['product_type_id']
            );
            $last_id        = $this->executeSaveSubItemTable($data);
            $transfered_qty = $this->Manufacture_Preparation_Model->get_transferred_gt_qty($pbi_id);
            if ($transfered_qty == $details['output_qty']) {
                $data = array(
                    'finish_status' => 1,
                    'finish_by' => $this->session->userdata('ss_user_id'),
                    'finish_on' => date('Y-m-d H:i:s')
                );
                $this->executeUpdateMasterTable($pbi_id, $data);
            }
            $st = array(
                'status' => 1,
                'validation' => 'Added',
                'result' => $last_id
            );
            echo json_encode($st);
        }
    }
    
      function loadReadyForGRNReport()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'loadReadyForGRNReport';
        $data['department_list']    = $this->Warehouse_Model->getDepartment(); 
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/loadReadyForGRNReport', $data);
    }
     function getListReadyForGRNReport()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getQCProductionListForBasicDataTableReport($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 $row) {
                $nestad_data   = array();
                $nestad_data[] = $row['pbi_ref_no'];
                $nestad_data[] = $row['product_code'];
                $nestad_data[] = $row['product_name'];
                $nestad_data[] = $row['pbi_qty'];
                $nestad_data[] = $row['output_qty'];
                $nestad_data[] = $row['defect_qty'];
                $nestad_data[] = $row['extra_output_qty'];
                $nestad_data[] = $row['pbi_unit_cost'];
                $nestad_data[] = $row['pbi_lost_value'];
                $nestad_data[] = $row['extra_output_value'];
                $nestad_data[] = $row['pbi_estimate_cost'];
                $nestad_data[] = $row['pbi_total_actual_cost'];
                $nestad_data[] = $row['user_first_name'];
                $nestad_data[] = $row['qc_on'];
                $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="req_return_additional_items(' . $row['pbi_id'] . ')"><i class="glyphicon fa fa-undo"></i> RETURN EXTRA QTY </a></li>-->
                               <!--<li><a style="cursor: pointer;" onclick="reject_qc(' . $row['pbi_id'] . ')"><i class="glyphicon fa fa-ban"></i> QC Reject</a></li>-->
                               </ui></div>
                            ';
                //$nestad_data[] = $actdes;
                $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);
        }
    }
}