<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
    include('core_stock_in_out.php');  
class Stock_In_Out extends Core_Stock_In_Out
{
    public function __construct()
    {
        parent::__construct();
        date_default_timezone_set("Asia/Colombo");
    }
    /*lakmal*/
    function save_issue_items($data){
        //
        if ($this->db->insert('stock_issue_items', $data)) {
            $lst = $this->db->insert_id();
            return $lst;
        } else {
            return false;
        }
    }
    function save_issue($data){
        if ($this->db->insert('stock_issue', $data)) {
            $lst = $this->db->insert_id();
            return $lst;
        } else {
            return false;
        }
    }
    /*end lakmal*/
    function IssueMaterialBatchForSTN()
    {
        $status = 1;
        ini_set('display_errors', 1);
        $id = $this->getId();
        
        // start transaction
        $this->db->trans_begin();

        
        $sungle_item_list = $this->Stock_In_Out_Model->get_stn_ingrediant_bulk_list($id, null);
        $overall_process_status = 1;
    
        $message = '';
        foreach ($sungle_item_list as $sil) {
            $overall_req_qty = $sil['pbis_qty'];
            $avilble_qty = $this->Stock_Counter_Model->get_stock_balance($sil['psnm_warehouse_id'], $sil['pbsi_product_mat_id']);
            //echo "PRODUCT ".$sil['pbsi_product_mat_id']." | TOTAL REQ Qty ".$sil['pbis_qty']." | AVAIBLE QTY ".$avilble_qty." <hr>";
            $message = "<hr>PRODUCT " . $sil['product_mat_name'] . " | TOTAL REQ Qty " . $sil['pbis_qty'] . " | AVAIBLE QTY " . $avilble_qty . " <hr>";
            if ($avilble_qty < $overall_req_qty) {
                $overall_process_status = 0;
                break;
            }
        }
        if ($overall_process_status == 0) {
            $this->db->trans_rollback();
            $st = array('status' => 0, 'validation' => 'Out of Stock : ' . $message, 'result' => 'null');
            echo json_encode($st);
            return false;
        }
        $data = array(
            'psnm_id' => $id,
            'user_id' => $this->session->userdata('ss_user_id'),
            'system_date_time' => date('Y-m-d H:i:s')
        );
        $master_id = $this->executeSaveMasterTable($data);
    
        $data['psiom_id'] = $master_id;
        $data['line'] = 'stock_in_out.php / 62';
        $this->save_issue($data);
    
        $snt_result = $this->Stock_In_Out_Model->get_stn_ingrediant_individual_item_list($id, null);
        foreach ($snt_result as $stnr) {
            $allocated_pbsi_qty = $this->Stock_In_Out_Model->get_pbsi_allocated_stn_qty_total($stnr['pbsi_id'], $id);
            if ($allocated_pbsi_qty >= $stnr['pbis_qty']) {
                continue;
            }
            //foreach 2 start point
            $batch_list = $this->Stock_In_Out_Model->runGetMaterialBatch($stnr['pbsi_product_mat_id']);
            $required_product_qty = $stnr['pbis_qty'];
            $total_batch_allocated_stock = 0;
            $remain_allocated_qty = $stnr['pbis_qty'];
            foreach ($batch_list as $bl) {
                //foreach 3 start point
                $batch_stock = $this->Stock_Counter_Model->get_stock_balance_batch('', $stnr['pbsi_product_mat_id'], $bl['batch_id']);
    
    
                if ($batch_stock <= 0) {
                    continue;
                }
                if ($remain_allocated_qty <= 0) {
                    $status = 0;
                    continue;
                }
                if ($total_batch_allocated_stock >= $required_product_qty) {
                    $status = 0;
                    continue;
                }
                if ($batch_stock >= $remain_allocated_qty) {
                    //---------------------------------------------------------
                    $total_batch_allocated_stock += $remain_allocated_qty;
                    $data = array(
                        'psiom_id' => $master_id,
                        'pbi_id' => $stnr['pbi_id'],
                        'pbsi_id' => $stnr['pbsi_id'],
                        'psni_id' => $stnr['psni_id'],
                        'psnm_id' => $stnr['psnm_id'],
                        'product_mat_id' => $stnr['pbsi_product_mat_id'],
                        'product_mat_batch_id' => $bl['batch_id'],
                        'unit_price' => $bl['product_cost'],
                        'cost' => ($bl['product_cost'] * $remain_allocated_qty),
                        'quantity' => $remain_allocated_qty,
                        'stock_out' => $remain_allocated_qty,
                        'psio_issue_by' => $this->session->userdata('ss_user_id'),
                        'psio_issue_on' => date('Y-m-d H:i:s')
                    );
                    $last_id = $this->executeSaveItemTable($data);
                    $data['line'] = 'stock_in_out.php / 98';
                    $this->save_issue_items($data);
                    $remain_allocated_qty -= $remain_allocated_qty;
                    //---------------------------------------------------------
                } else {
                    //---------------------------------------------------------
                    $total_batch_allocated_stock += $batch_stock;
                    $data = array(
                        'psiom_id' => $master_id,
                        'pbi_id' => $stnr['pbi_id'],
                        'pbsi_id' => $stnr['pbsi_id'],
                        'psni_id' => $stnr['psni_id'],
                        'psnm_id' => $stnr['psnm_id'],
                        'product_mat_id' => $stnr['pbsi_product_mat_id'],
                        'product_mat_batch_id' => $bl['batch_id'],
                        'unit_price' => $bl['product_cost'],
                        'cost' => ($bl['product_cost'] * $batch_stock),
                        'quantity' => $batch_stock,
                        'stock_out' => $batch_stock,
                        'psio_issue_by' => $this->session->userdata('ss_user_id'),
                        'psio_issue_on' => date('Y-m-d H:i:s')
                    );
                    $last_id = $this->executeSaveItemTable($data);
                    $data['line'] = 'stock_in_out.php / 120';
                    $this->save_issue_items($data);
                    $remain_allocated_qty -= $batch_stock;
                    //---------------------------------------------------------
                }
                //foreach 3 end point
            }
            $data = array(
                'stock_issue_status' => 1,
                'stock_issue_by' => $this->session->userdata('ss_user_id'),
                'stock_issue_date_time' => date('Y-m-d H:i:s')
            );
            $this->Stock_In_Out_Model->updateProductionBatch($stnr['pbi_id'], $data);
            //foreach 2 end point
        }
        /*$status = 1;
        if ($status == 1) {
            $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->Stock_In_Out_Model->updateStoreNoteMasterTable($id, $data);
    
            $st = array('status' => $status, 'validation' => 'Stock Issued', 'result' => 'null');
            echo json_encode($st);
        } else {
            $st = array('status' => $status, 'validation' => 'Problem Found on Stock ', 'result' => 'null');
            echo json_encode($st);
        }*/
        $status = 1;
        if ($this->db->trans_status() === FALSE || $status == 0) {
            $this->db->trans_rollback();
            $st = array(
                'status'     => 0,
                'validation' => 'Problem Found on Stock',
                'result'     => 'null'
            );
            echo json_encode($st);
        } else {
            $this->db->trans_commit();
    
            $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->Stock_In_Out_Model->updateStoreNoteMasterTable($id, $data);
    
            $st = array(
                'status'     => 1,
                'validation' => 'Stock Issued',
                'result'     => 'null'
            );
            echo json_encode($st);
        }
    }
    

    
    
    function  issueAddtionalItemForProduction(){
        
         $id=$this->getId();
        
        $result=$this->Stock_In_Out_Model->getAddtionalItemData($id); 
      
        if(!$result){
        $st = array('status' =>0,'validation' =>'DATA NOT FOUND','result'=>1);
        echo json_encode($st);
        return;
        }
         $data=array(
             'psnm_id'=>$result['ad_item_id'],
             'user_id'=>$this->session->userdata('ss_user_id'),
             'system_date_time'=>date('Y-m-d H:i:s')
              );
             $master_id= $this->executeSaveMasterTable($data);
             
             $data['psiom_id'] = $master_id;
             $data['line'] = 'stock_in_out.php / 186';
             $this->save_issue($data);
        
              $data=array(
                          'psiom_id'=>$master_id,
                          'pbi_id'=>$result['pbi_id'],
                          'product_mat_id'=>$result['product_id'],
                          'product_mat_batch_id'=>$result['batch_id'],
                          'unit_price'=>$result['product_cost'],
                          'cost'=>($result['product_cost']*$result['req_qty']),
                          'quantity'=>$result['req_qty'],
                          'stock_out'=>$result['req_qty'],
                          'psio_issue_by'=>$this->session->userdata('ss_user_id'),
                          'psio_issue_on'=>date('Y-m-d H:i:s')
                          );
                      $last_id= $this->executeSaveItemTable($data);
                      $data['line'] = 'stock_in_out.php / 183';
                      $this->save_issue_items($data);
                      
                      
                      
                      
                       $data=array(
             'ad_req_issue_status'=>1,
             'issue_user_id'=>$this->session->userdata('ss_user_id'),
             'issue_system_date_time'=>date('Y-m-d H:i:s')
              );
            $this->Stock_In_Out_Model->updateAdditionalRequiestTable($id,$data);    
        $st = array('status' =>1,'validation' =>'Saved','result'=>1);
        echo json_encode($st);
       
   }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  
  
   
}