<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
include('core_production_material_in_out.php');
class Production_Material_In_Out extends Core_Production_Material_In_Out
{
    public function __construct()
    {
        parent::__construct();
        ini_set('display_errors', 1);
    }
    function productionMaterilOut()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        
        
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'production_material_in_out';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('store/production_material_out_master', $data);
    }
    function storeProductionMaterilOut()
    {
        $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(
                'psom_document_no' => $ref_no,
                'psom_warehouse_id' => $warehouse_id,
                'psom_note' => $note,
                'psom_user_id' => $this->session->userdata('ss_user_id'),
                'psom_date_time' => date('Y-m-d H:i:s'),
                'psom_ref_no' => $this->Common_Model->gen_ref_number('psom_id', 'production_stock_out_master', 'SI')
            );
            $last_id = $this->executeSaveMasterTable($data);
            $st      = array(
                'status' => 1,
                'validation' => 'Added',
                'result' => $last_id
            );
            echo json_encode($st);
        }
    }
    function loadSTNListForIssue()
    {
        $id                     = $this->getId();
        $data                   = array();
        $data['details']        = $this->executeSelectMasterTable($id);
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'production_material_in_out';
        $data['stn_id']         = $id;
        $this->load->view('store/production_material_out_items', $data);
    }
    function getListPendingSTN()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getPendingSTNListForBasicDataTable($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['psnm_ref_no'];
                $nestad_data[] = $row['psnm_manual_ref_no'];
                $nestad_data[] = $row['warehouse_name'];
                $nestad_data[] = $row['psnm_date_time'];
                $nestad_data[] = $row['user_first_name'];
                $action        = '<input type="checkbox" id="select_' . $row['psnm_id'] . '" name="select[]" value="' . $row['psnm_id'] . '">';
                $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 saveStoreSTNItems()
    {
        $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('select', 'Select Item', 'required');
        $master_id    = $this->cleanAndValidateNumber($this->input->post('master_id'));
        $warehouse_id = $this->cleanAndValidateNumber($this->input->post('warehouse_id'));
        $select       = $this->cleanAndValidateArray($this->input->post('select'));
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            foreach ($select as $row) {
                $data    = array(
                    'psom_id' => $master_id,
                    'psnm_id' => $row
                );
                $last_id = $this->executeSaveItemTable($data);
                $data    = array(
                    'psnm_pickup_status' => 1,
                    'psnm_pickup_by' => $this->session->userdata('ss_user_id'),
                    'psnm_pickup_on' => date('Y-m-d H:i:s')
                );
                $this->executeUpdateSubItemTable($row, $data);
            }
            $st = array(
                'status' => 1,
                'validation' => 'Added',
                'result' => $last_id
            );
            echo json_encode($st);
        }
    }
    function getListSelectedSTN()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getSelectedSTNListForBasicDataTable($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['psnm_ref_no'];
                $nestad_data[] = $row['psnm_manual_ref_no'];
                $nestad_data[] = $row['warehouse_name'];
                $nestad_data[] = $row['psnm_date_time'];
                $nestad_data[] = $row['user_first_name'];
                $action        = '<button class="btn btn-xs btn-danger" id="delete' . $row['psoi_id'] . '" name="delete' . $row['psoi_id'] . '" onclick="rollback(' . $row['psoi_id'] . ')" >Rolll Back</button>';
                if ($row['psoi_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 rollbackSTNToPendingStatus()
    {
        $id     = $this->getId();
        $result = $this->executeSelectItemTable($id);
        if (isset($result['psnm_id'])) {
            $main_recode_id = $result['psnm_id'];
            $data           = array(
                'psnm_rollback_status' => 1,
                'psnm_pickup_status' => 0,
                'psnm_rollback_by' => $this->session->userdata('ss_user_id'),
                'psnm_rollback_on' => date('Y-m-d H:i:s')
            );
            $status         = $this->executeUpdateSubItemTable($main_recode_id, $data);
            if ($status == 1) {
                $status = $this->executeDeleteItemTable($id);
            }
            $st = array(
                'status' => $status,
                'validation' => 'Rollbacked',
                'result' => 'null'
            );
            echo json_encode($st);
        } else {
            $st = array(
                'status' => 0,
                'validation' => 'Not Found',
                'result' => 'null'
            );
            echo json_encode($st);
        }
    }
    function notCompleteStoreNote()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'not_complete_store_note';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('estimate/not_completed_store_note', $data);
    }
    function getListNotCompleteStoreNote()
    {
        $request_data  = $this->getClientSideDataTableParameters();
        $result_array  = $this->getNotCompleteStoreNoteForBasicDataTableOnServerSide($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->psnm_ref_no;
                $row[]  = $products->psnm_manual_ref_no;
                $row[]  = $products->psnm_date_time;
                $row[]  = $products->user_first_name;
                $row[]  = $products->warehouse_name;
                $row[]  = $products->psnm_note;
                $actdes = '';
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs  dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                              <li><a href="' . base_url('production_preparation/loadStoreNoteItems?id=' . $products->psnm_id) . '"  style="cursor: pointer;"><i class="glyphicon fa fa-edit"></i> Update Store Note</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 getListSelectedSTNTotalMaterial()
    {
        $this->load->model('Stock_Counter_Model');
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getSelectedSTNMaterialListForBasicDataTable($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) {
                $required_qty  = $this->Production_Material_In_Out_Model->runGetSumAllSTNMaterial($row['product_mat_id'], $request_data['id']);
                $avilble_qty   = $this->Stock_Counter_Model->get_stock_balance('', $row['product_mat_id']);
                $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[] = $required_qty;
                $nestad_data[] = $avilble_qty;
                $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 updteStoreNote()
    {
        return 0;
        $this->load->library('form_validation');
        $this->form_validation->set_rules('stn_master_id', 'Recode', 'required|xss_clean');
        $stn_master_id = $this->cleanAndValidateNumber($this->input->post('stn_master_id'));
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            $data    = array(
                'psnm_status' => 1,
                'finish_by' => $this->session->userdata('ss_user_id'),
                'finish_on' => date('Y-m-d H:i:s')
            );
            $last_id = $this->executeUpdateMasterTable($stn_master_id, $data);
            $st      = array(
                'status' => 1,
                'validation' => 'Added',
                'result' => $last_id
            );
            echo json_encode($st);
        }
    }
    function loadSTNIssueFromStore()
    {
        $id                     = $this->getId();
        $data                   = array();
        $data['details']        = $this->executeSelectMasterTable($id);
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'production_material_in_out';
        $data['stn_id']         = $id;
        $this->load->view('store/production_material_issue', $data);
    }
    function getListSelectedSTNforIssueMaterialBatch()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getSelectedSTNListForBasicDataTable($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['psnm_ref_no'];
                $nestad_data[] = $row['psnm_manual_ref_no'];
                $nestad_data[] = $row['warehouse_name'];
                $nestad_data[] = $row['psnm_date_time'];
                $nestad_data[] = $row['user_first_name'];
                $action        = '
            <button class="btn btn-xs btn-primary" id="issue' . $row['psoi_id'] . '" name="issue' . $row['psoi_id'] . '" onclick="issueMaterial(' . $row['psoi_id'] . ')" >Issue Materials</button>
            
            <button class="btn btn-xs btn-danger" id="delete' . $row['psoi_id'] . '" name="delete' . $row['psoi_id'] . '" onclick="rollback(' . $row['psoi_id'] . ')" >Rolll Back</button>';
                if ($row['psoi_status'] == 1) {
                    $action = '<span class="btn btn-xs btn-success" >Finished</span>
                 <button class="btn btn-xs btn-primary" id="print_stn' . $row['psoi_id'] . '" name="print_stn' . $row['psoi_id'] . '" onClick="print_stn(' . $row['psnm_id'] . ')" >Print STN</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 pendingProductionMaterilOut()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'pending_material_out';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('store/not_completed_issue_note', $data);
    }
    function getListNotCompleteIssueNote()
    {
        $request_data  = $this->getClientSideDataTableParameters();
        $result_array  = $this->getNotCompleteIssueNoteForBasicDataTableOnServerSide($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->psom_ref_no;
                $row[]  = $products->psom_document_no;
                $row[]  = $products->psom_date_time;
                $row[]  = $products->user_first_name;
                $row[]  = $products->warehouse_name;
                $row[]  = $products->psom_note;
                $actdes = '';
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs  dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                              <li><a href="' . base_url('production_material_in_out/loadSTNListForIssue?id=' . $products->psom_id) . '"  style="cursor: pointer;"><i class="glyphicon fa fa-edit"></i> Update Issue Note</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 finishIssueNote()
    {
        $id     = $this->getId();
        $result = $this->executeSelectItemTable($id);
        if ($id) {
            $data   = array(
                'psom_status' => 1,
                'finish_by' => $this->session->userdata('ss_user_id'),
                'finish_on' => date('Y-m-d H:i:s')
            );
            $status = $this->executeUpdateMasterTable($id, $data);
            $st     = array(
                'status' => $status,
                'validation' => 'Upddated',
                'result' => 'null'
            );
            echo json_encode($st);
        } else {
            $st = array(
                'status' => 0,
                'validation' => 'Not Found',
                'result' => 'null'
            );
            echo json_encode($st);
        }
    }
    function loadPendingJobs()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'pending_job_store';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('store/pending_store_jobs', $data);
    }
    function getListPendingStoreNote()
    {
        $request_data  = $this->getClientSideDataTableParameters();
        $result_array  = $this->getPendingStoreNoteForBasicDataTableOnServerSide($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->psnm_ref_no;
                $row[] = $products->psnm_manual_ref_no;
                $row[] = $products->psnm_date_time;
                $row[] = $products->user_first_name;
                $row[] = $products->warehouse_name;
                $row[] = $products->shedule_date_time;
                if ($products->time_profile_id == 1) {
                    $row[] = "DAY";
                } else {
                    $row[] = "NIGHT";
                }
                $row[]  = $products->psnm_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 onclick="print_storenote(' . $products->psnm_id . ')" href="#"  style="cursor: pointer;"><i class="glyphicon fa fa-print"></i> Print Store Note</a></li>
                                <li><a onclick="issue_stocks(' . $products->psnm_id . ')" href="#"  style="cursor: pointer;"><i class="glyphicon fa fa-paper-plane"></i> Issue STN</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 printSTN()
    {
        $id                               = $this->getId();
        $this->check_dublicate_stn_delete($id);
        sleep(3);
        $data['master_details']           = $this->Production_Material_In_Out_Model->runGetSTNDetails($id);
        $data['items_details']            = $this->Production_Material_In_Out_Model->runGetSTNItemDetails($id);
        $data['production_items_details'] = $this->Production_Material_In_Out_Model->runGetSTNProductionItemDetails($id);
        $data['main_menu_name']           = $this->main_menu_name;
        $data['sub_menu_name']            = 'pending_material_out';
        $data['master_id']                = $id;
        $this->load->view('store/stn_print', $data);
    }
    function internalGRN()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'internal_grn';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('store/pending_internal_grn', $data);
    }
    function getListPendingInternalGRN()
    {
        $request_data  = $this->getClientSideBasicDataTableParameters();
        $result_array  = $this->getPendingInternalGRNBasicDataTable($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->finish_on;
                $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('production_material_in_out/loadGTNDetails?id=' . $products->pgrnm_id) . '"  style="cursor: pointer;"><i class="glyphicon fa fa-edit"></i> GRN Details</a></li>
                             <li><a   id="finish' . $products->pgrnm_id . '" name="finish' . $products->pgrnm_id . '" onclick="finish(' . $products->pgrnm_id . ')" > <i class="fa fa-gear fa-spin"></i> Process GRN </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 FinishGRN()
    {
        $id     = $this->getId();
        $result = $this->Production_Material_In_Out_Model->runGetGTNPendingProductMaterialData($id);
        foreach ($result as $row) {
            $data    = array(
                'batch_ref_number' => $row['pbi_ref_no'],
                'product_id' => $row['product_mat_id'],
                'product_cost' => $row['pbi_unit_cost'],
                'grn_type' => 2,
                'grn_item_id' => $row['pgrni_id']
            );
            $last_id = $this->Production_Material_In_Out_Model->runSaveBatchProductTable($data);
            $data    = array(
                'pgtni_status' => 1,
                'batch_id' => $last_id
            );
            $this->Production_Material_In_Out_Model->runUpdateGRNMaterialItemUsingPrimaryId($row['pgrni_id'], $data);
        }
        $data    = array(
            'pgrnp_status' => 1
        );
        $status  = $this->Production_Material_In_Out_Model->runUpdateProductionGRNItemTableUsingSecondryId($id, $data);
        $data    = array(
            'pgrnm_pick_up_status' => 1,
            'pgrnm_pick_up_by' => $this->session->userdata('ss_user_id'),
            'pgrnm_pick_up_on' => date('Y-m-d H:i:s')
        );
        $status  = $this->Production_Material_In_Out_Model->runUpdateGRNMasterTableUsingPrimaryId($id, $data);
        $message = 'Completed';
        $st      = array(
            'status' => $status,
            'validation' => $message,
            'result' => 'null'
        );
        echo json_encode($st);
    }
    function directProductionConvert()
    {
        $data = array();
        $this->load->model('Warehouse_Model');
        $data['product_batch_id'] = '';
        $data['details']          = '';
        $data['warehouse_list']   = $this->Warehouse_Model->get_all_warehouse();
        $data['main_menu_name']   = $this->main_menu_name;
        $data['sub_menu_name']    = 'direct_production_convert';
        $this->load->view('store/direct_production_convert', $data);
    }
    public function getProductbatchListJson()
    {
        $this->load->model('Stock_Counter_Model');
        $str    = $this->input->post('search_string');
        $result = $this->Production_Material_In_Out_Model->runGetMaterialWithBatch($str);
        
        
        $return_result=array();
        foreach($result as $row){
            $nesteddata=array();
            
            
             $stock = $this->Stock_Counter_Model->get_stock_balance_batch('',$row['product_mat_id'],$row['batch_id']);
            $nesteddata['product_mat_id']=$row['product_mat_id'];
            $nesteddata['product_mat_code']=$row['product_mat_code'];
            $nesteddata['product_mat_name']=$row['product_mat_name'];
            $nesteddata['batch_id']=$row['batch_id'];
            $nesteddata['batch_ref_number']=$row['batch_ref_number']." STOCK : ".$stock;
           
           $return_result[]=$nesteddata;
            
        }
        
        
        
        echo json_encode($return_result);
    }
    public function saveConvertBatchMaterial()
    {
        $this->load->model('Final_Batch_Model');
        $this->load->library('form_validation');
        $product_id         = $this->input->post('product_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('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 {
            $batch = $this->Production_Material_In_Out_Model->runGetBatchAllDetails($product_id);
            if (isset($batch['product_id'])) {
            } else {
                echo "System Error!";
                return false;
            }
            if ($allocated_quantity <= $batch['quantity']) {
                $ref_id   = 0;
                $batch_id = $this->Final_Batch_Model->createNewBatch($batch['product_id'], $ref_id, $batch['batch_ref_number'], "CONVERT");
                $data     = array(
                    'pc_warehouse' => $warehouse_id,
                    'pc_prodcut_id' => $batch['product_id'],
                    'pc_parduct_mat_id' => $batch['product_mat_id'],
                    'pc_product_mat_batch_id' => $product_id,
                    'pc_qty' => $allocated_quantity,
                    'pc_user_id' => $this->session->userdata('ss_user_id'),
                    'pc_date_time' => date('Y-m-d H:i:s'),
                    'pc_qty' => $allocated_quantity,
                    'converted_batch_id' => $batch_id
                );
                $last_id  = $this->Production_Material_In_Out_Model->runSaveProductionConvertTable($data);
                $st       = array(
                    'status' => 1,
                    'validation' => 'Added'
                );
                echo json_encode($st);
                return false;
            } else {
                $st = array(
                    'status' => 1,
                    'validation' => 'Not Enough Qty'
                );
                echo json_encode($st);
                return false;
            }
            if (isset($product['product_mat_id'])) {
            } else {
                exit;
            }
            //$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);
            return false;
        }
    }
    public function loadGTNDetails()
    {
        $id   = $this->getId();
        $data = array();
        $this->load->model('Production_Estimate_Model');
        $data['details']   = $this->Production_Material_In_Out_Model->runGetGTNDetails($id);
        $data['item_list'] = $this->Production_Material_In_Out_Model->runGetGTNItems($id);
        ;
        $data['defect_list']    = $this->Production_Estimate_Model->defect_list(2);
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'internal_grn';
        $this->load->view('store/gtn_details', $data);
    }
    function markPackingDamage()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('result', 'QTY', 'required|xss_clean');
        $this->form_validation->set_rules('gtn_item_id', 'GTN', 'required|xss_clean');
        $master_id = $this->cleanAndValidateNumber($this->input->post('gtn_item_id'));
        $result    = $this->cleanAndValidateNumber($this->input->post('result'));
        $defect_reason    = $this->input->post('defect_reason');
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            $avaible_qty       = $this->Production_Material_In_Out_Model->get_availble_grn_qty($master_id);
            $packageing_damage = $this->Production_Material_In_Out_Model->marked_pakagening_damage($master_id);
            if ($avaible_qty < $result) {
                $st = array(
                    'status' => 0,
                    'validation' => 'INVALID QTY',
                    'result' => $master_id
                );
                echo json_encode($st);
                return 0;
            }
            $data = array(
                'quantity' => $avaible_qty - $result,
                'packing_damage' => $packageing_damage + $result,
                'defect_reason' => $defect_reason,
            );
            $this->Production_Material_In_Out_Model->update_production_grn_items_table($master_id, $data);
            $this->Production_Material_In_Out_Model->update_production_grn_intermediat_product($master_id, $data);
            $st = array(
                'status' => 1,
                'validation' => 'Added',
                'result' => ''
            );
            echo json_encode($st);
        }
    }
    
    
    function check_dublicate_stn_delete($id){
        $this->load->model('Manual_Function_Model');
	    $result=$this->Manual_Function_Model->duplicate_stn_item($id);
	    $dataset=array();
	    foreach($result as $r){
	      $dataset[]=$r->psni_id; 
	    }
	    if(count($dataset)>0){
	            $this->Manual_Function_Model->delete_dublicate_stn_item($dataset); 
	    }
	    $result2=$this->Manual_Function_Model->duplicate_stn_sub_item($id);
	    $dataset2=array();
	     foreach($result2 as $r){
	      $dataset2[]=$r->psnsi_id; 
	    }
	     if(count($dataset2)>0){
	       $this->Manual_Function_Model->delete_dublicate_stn_sub_item($dataset2); 
	    }
    }
}