<?php

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

    class Stock extends MY_Controller {

        function __construct() {
            parent::__construct();
             $this->load->model('inventory/stock_model');
             $this->load->model('inventory/products_model');
            $this->load->model('inventory/goodsreceipts_model');
            $this->load->library('Formatslist');
        }

        //GET STOCK DIARY
        public function stockdiary() {
            $this->load->model('settings/warehouse_model');
             $data['locations'] = $this->common->getAll('LOCATIONS');
              $data['suppliers'] = $this->common->getAll('SUPPLIERS');
    //          $data['product'] = $this->common->getAll('PRODUCTS');
              $this->db->from('PRODUCTS');
            $this->db->order_by("NAME", "asc");
            $data['product']  = $this->db->get()->result();

            $data['template'] = 'inventory/stockdiary_ovw';
              $this->load->view('template',$data);
        }

        //GET STOCK DIARY
        public function getstockdiary() {
                $aColumns = array(
                'sl',
                'DATE',
                'REASON',
                'LOCATION',
                'CODE',
                'PRODUCT',
                'UNITS',
                'PRICE',
                'SUPPLIER');
            // set limit
            $sLimit = "";
            if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
                $sLimit = "LIMIT " . $_GET['iDisplayStart'] . ", " . $_GET['iDisplayLength'];
            }
            //Ordering
            if (isset($_GET['iSortCol_0'])) {
                $sOrder = "ORDER BY  ";
                for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
                    if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                        if ($aColumns[intval($_GET['iSortCol_' . $i])] != 'sl') {
                            $sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . "
                                " . $_GET['sSortDir_' . $i] . ", ";
                        }
                    }
                }
                $sOrder = substr_replace($sOrder, "", -2);
                if ($sOrder == "ORDER BY") {
                    $sOrder = "";
                }
            }
            /*
             * Filtering
             */
            $sWhere = "";
            if ($_GET['sSearch'] != "") {
                $sWhere = "WHERE (";
                for ($i=1;$i<9;$i++) {
                    if ($aColumns[$i] == 'DATE') {
                        $aColumns[$i] = 'DATE';
                    } else if ($aColumns[$i] == 'REASON') {
                        $aColumns[$i] = 'REASON';
                    } else if ($aColumns[$i] == 'LOCATION') {
                        $aColumns[$i] = 'LOCATION';
                    } else if ($aColumns[$i] == 'CODE') {
                        $aColumns[$i] = 'CODE';
                    } else if ($aColumns[$i] == 'PRODUCT') {
                        $aColumns[$i] = 'PRODUCT';
                    } else if ($aColumns[$i] == 'UNITS') {
                        $aColumns[$i] = 'UNITS';
                    } else if ($aColumns[$i] == 'PRICE') {
                        $aColumns[$i] = 'PRICE';
                    } else if ($aColumns[$i] == 'SUPPLIER') {
                        $aColumns[$i] = 'SUPPLIER';
                    }
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $_GET['sSearch'] . "%' OR ";
                }
                $sWhere = substr_replace($sWhere, "", -3);
                $sWhere .= ')';
            }
            // get data
            $order = str_replace("ORDER BY",'',	$sOrder);
            $limit = ' ' . $sLimit;
            if ($sWhere != '') {
                $where = ' AND ';
                $where .= str_replace("WHERE",'',$sWhere);
            } else {
                $where = '';
            }
            
            if($_GET["filter_begin"]) {
                $where  =   $where." AND DATE>='".date("Y-m-d H:i:s",strtotime($_GET["filter_begin"]." 00:00"))."'";
            }
            if($_GET["filter_end"]) {
                $where  =   $where." AND DATE<='".date("Y-m-d H:i:s",strtotime($_GET["filter_end"]." 23:59:59"))."'";
            }
            
            if($sOrder=='')
                $sOrder= ' ORDER BY DATE DESC';
            $sql = "SELECT * FROM (SELECT STOCKDIARY.ID, STOCKDIARY.DATENEW AS DATE, ".
                "CASE STOCKDIARY.REASON 
                    WHEN '1' THEN '(IN) Purchase' 
                    WHEN '2' THEN '(IN) Refund'  
                    WHEN '4' THEN '(IN) Movement'
                    WHEN '5' THEN '(IN) Production'
                    WHEN '-1' THEN '(OUT) Sale'
                    WHEN '-2' THEN '(OUT) Refund'
                    WHEN '-3' THEN '(OUT) Break'
                    WHEN '-4' THEN '(OUT) Movement'
                    WHEN '-5' THEN '(OUT) Production'
                    WHEN '1000' THEN 'Crossing'  
                    WHEN '999' THEN 'Request'
                    ELSE '' 
                END as REASON"
                . ", PRODUCTS.CODE, PRODUCTS.NAME AS PRODUCT, STOCKDIARY.UNITS, STOCKDIARY.PRICE,"
                . " SUPPLIERS.NAME AS SUPPLIER, LOCATIONS.NAME AS LOCATION FROM STOCKDIARY"
                . " LEFT JOIN PRODUCTS ON STOCKDIARY.PRODUCT = PRODUCTS.ID"
                . " LEFT JOIN SUPPLIERS ON SUPPLIERS.ID = STOCKDIARY.SUPPLIER"
                . " JOIN LOCATIONS ON LOCATIONS.ID = STOCKDIARY.LOCATION) A WHERE 1 " . $where . $sOrder . $limit;
            
//            echo $sql;exit;
            
            $arr = $this->common->customquery($sql);
            $totalCount_sql = " Select count(*) AS total FROM STOCKDIARY LEFT JOIN PRODUCTS ON STOCKDIARY.PRODUCT = PRODUCTS.ID"
                . " LEFT JOIN SUPPLIERS ON SUPPLIERS.ID = STOCKDIARY.SUPPLIER"
                . " JOIN LOCATIONS ON LOCATIONS.ID = STOCKDIARY.LOCATION";
            $totalCount_sql .= " WHERE 1 ";
            $totalCount = $this->common->customquery($totalCount_sql);
            $iTotal = $totalCount[0]->total;
            /*
             * Output
             */
            $output = array(
                "sEcho" => intval($_GET['sEcho']),
                "iTotalRecords" => $iTotal,
                "iTotalDisplayRecords" => $iTotal,
                "aaData" => array()
            );
            $j = $_GET['iDisplayStart']+1;
            if ($arr != '') {
                foreach ($arr as $key => $aRow) {
                    $row = array();
                    $row[0] = $j;
                    $row[1] = $this->formatslist->dateFormat($aRow->DATE);
                    $row[2] = $aRow->REASON;
                    $row[3] = $aRow->LOCATION;
                    $row[4] = $aRow->CODE;
                    $row[5] = $aRow->PRODUCT;
                    $row[6] = $aRow->UNITS;
                    $row[7] = $this->formatslist->formatCurrencyWithHash($aRow->PRICE);
                    $row[8] = $aRow->SUPPLIER;
                    $output['aaData'][] = $row;
                    $j++;
                }
            } else {
                    //
            }
            echo json_encode($output);
        }
        
//        public function printArray($array) {
//        $items = array();
//        foreach ($array as $key => $value) {
//
//            if (is_array($value)) {
//                //$this->printArray($value, $pad.' ');
//                var_dump($value);
//            } else {
//                echo "$key => $value";
//            }
//        }
//    }

    public function addstockdiary2() {


        $pos = 0;
        $reason = $this->input->post('REASON');
        $units = 1;
        switch ($reason) {

            case '5':
            case '-1':
            case '-2':
            case '-3':
            case '-4':
            case '-5':
            case '1000':
                $units = -1;
                break;
        }

        foreach ($_POST as $key => $value) {
            if (substr($key, 0, 4) === "item" && $pos != substr($key, strlen($key) - 1, 1)) {
                $pos = substr($key, strlen($key) - 1, 1);
                if ($_POST["itemid_" . $pos] != "") {
//                    $items[]=array("itemid"=>$_POST["itemid_".$pos]
//                            ,"itemcode"=>$_POST["itemcode_".$pos]
//                            ,"itemname"=>$_POST["itemname_".$pos]
//                            ,"itemprice"=>$_POST["itemprice_".$pos]
//                            ,"itemqty"=>abs($_POST["itemqty_".$pos])*$units);


                    $pid = $_POST["itemid_" . $pos];
                    $itemcode = $_POST["itemcode_" . $pos];
                    $itemname = $_POST["itemname_" . $pos];
                    $itemprice = $_POST["itemprice_" . $pos];
                    $itemqty = abs($_POST["itemqty_" . $pos]) * $units;

                    if ($reason == '5') {
                        $mats = $this->stock_model->getMaterialsProd($pid);
                    } else {
                        $mats = $this->stock_model->getMaterialsProduction($pid);
                    }

                    if (sizeof($mats) > 0) {
                        for ($i = 0; $i < count($mats); $i++) {
                            $mat_data = array(
                                'ID' => uniqid(),
                                'DATENEW' => date("Y-m-d H:i:s", strtotime($this->input->post('DATENEW'))),
                                'REASON' => ($this->input->post('REASON') == 5) ? -5 : $this->input->post('REASON'),
                                'LOCATION' => $this->input->post('LOCATION'),
                                'SUPPLIER' => $this->input->post('SUPPLIER_ID'),
                                'PRODUCT' => $mats[$i]->MATERIAL,
                                'UNITS' => $itemqty * $mats[$i]->UNITS,
                                'PRICE' => $mats[$i]->PRICEBUY,
                            );
                            if ($this->stock_model->add($mat_data) == TRUE) {
                                //UPDATE CURRENTSTOCK
                                $pidinstock = $this->goodsreceipts_model->productInStockCurrent($mats[$i]->MATERIAL, $this->input->post('LOCATION'));
                                if ($pidinstock) {
                                    $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION'), $mats[$i]->MATERIAL, $itemqty * $mats[$i]->UNITS);
                                } else {
                                    $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION'), $mats[$i]->MATERIAL, $itemqty * $mats[$i]->UNITS);
                                }
                                if ($reason == '1000') {
                                    $mat_data['ID'] = uniqid();
                                    $mat_data['UNITS'] = $itemqty * $mats[$i]->UNITS * -1;
                                    $mat_data['LOCATION'] = $this->input->post('LOCATION1');
                                    if ($this->stock_model->add($mat_data) == TRUE) {
                                        //UPDATE CURRENTSTOCK
                                        $pidinstock = $this->goodsreceipts_model->productInStockCurrent($mats[$i]->MATERIAL, $this->input->post('LOCATION1'));
                                        if ($pidinstock) {
                                            $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION1'), $mats[$i]->MATERIAL, $itemqty * $mats[$i]->UNITS);
                                        } else {
                                            $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION1'), $mats[$i]->MATERIAL, $itemqty * $mats[$i]->UNITS);
                                        }
                                    }
                                }

//                                if ($reason == '1') {
//                                    $this->products_model->productpricecalculation($quantity * $mats[$i]->UNITS,$mats[$i]->MATERIAL);
//                                }
                            }
                        }


                        if ($reason == '5') {
                            $form_data = array(
                                'ID' => uniqid(),
                                'DATENEW' => date("Y-m-d H:i:s", strtotime($this->input->post('DATENEW'))),
                                'REASON' => 5,
                                'LOCATION' => $this->input->post('LOCATION'),
                                'SUPPLIER' => $this->input->post('SUPPLIER_ID'),
                                'PRODUCT' => $pid,
                                'UNITS' => $_POST["itemqty_" . $pos],
                                'PRICE' => $itemprice,
                            );
                            if ($this->stock_model->add($form_data) == TRUE) {
                                $pidinstock = $this->goodsreceipts_model->productInStockCurrent($pid, $this->input->post('LOCATION'));
                                if ($pidinstock) {
                                    $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION'), $pid, $itemqty);
                                } else {
                                    $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION'), $pid, $itemqty);
                                }
                            }
                        }
                    } else {

                        $form_data = array(
                            'ID' => uniqid(),
                            'DATENEW' => date("Y-m-d H:i:s", strtotime($this->input->post('DATENEW'))),
                            'REASON' => $this->input->post('REASON'),
                            'LOCATION' => $this->input->post('LOCATION'),
                            'SUPPLIER' => $this->input->post('SUPPLIER_ID'),
                            'PRODUCT' => $pid,
                            'UNITS' => $itemqty,
                            'PRICE' => $itemprice,
                        );
                        if ($this->stock_model->add($form_data) == TRUE) {
                            //UPDATE CURRENTSTOCK
                            $pidinstock = $this->goodsreceipts_model->productInStockCurrent($pid, $this->input->post('LOCATION'));
                            if ($pidinstock) {
                                $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION'), $pid, $itemqty);
                            } else {
                                $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION'), $pid, $itemqty);
                            }
                            if ($reason == '1000') {
                                $form_data['ID'] = uniqid();
                                $form_data['UNITS'] = $itemqty * -1;
                                $form_data['LOCATION'] = $this->input->post('LOCATION1');
                                if ($this->stock_model->add($form_data) == TRUE) {
                                    //UPDATE CURRENTSTOCK
                                    $pidinstock = $this->goodsreceipts_model->productInStockCurrent($pid, $this->input->post('LOCATION1'));
                                    if ($pidinstock) {
                                        $currentstock=$pidinstock[0]->UNITS;
                                        $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION1'), $pid, $itemqty * -1);
                                    } else {
                                        $currentstock=0;
                                        $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION1'), $pid, $itemqty * -1);
                                    }
                                }
                            }

                            if ($reason == '1') {
                                
                                $this->products_model->productpricecalculation($itemprice, $pid,$currentstock,$itemqty);
                                $mprodctlist = $this->products_model->productmaterialidwise($pid);
                                if ($mprodctlist) {
                                    foreach ($mprodctlist as $mprodctrec) {
                                        $productrec = $this->products_model->productmaterialmaterialwise($mprodctrec->PRODUCT);
                                        $this->goodsreceipts_model->updateProductCost($productrec->PRODUCT, $productrec->TOTALAMOUNT);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

return "Done"; exit;
            //redirect('inventory/stock/stockdiary');
    }

    public function addstockdiary() {
                $reason = $this->input->post('REASON');
                switch ($reason) {
                    case '1':
                    case '2':
                    case '4':
                        $quantity = abs($this->input->post('UNITS'));
                        break;
                    case '5':
                        $quantity = abs($this->input->post('UNITS')) * -1;
                        break;
                    case '-1':
                    case '-2':
                    case '-3':
                    case '-4':
                    case '-5':
                    case '1000':
                        $quantity = $this->input->post('UNITS') * -1;
                    break;
                }
                $pid = $this->input->post('PRODUCT');
                if($reason=='5') {
                    $mats = $this->stock_model->getMaterialsProd($pid);
                } else {
                    $mats = $this->stock_model->getMaterialsProduction($pid);
                }
                if (sizeof($mats) > 0) {
                    for ($i = 0; $i < count($mats); $i++) {
                            $mat_data = array(
                                'ID' => uniqid(),
                                'DATENEW' => date("Y-m-d H:i:s",strtotime($this->input->post('DATENEW'))),
                                'REASON' => ($this->input->post('REASON')==5) ? -5 : $this->input->post('REASON'),
                                'LOCATION' => $this->input->post('LOCATION'),
                                'SUPPLIER' =>$this->input->post('SUPPLIER_ID'),
                                'PRODUCT' => $mats[$i]->MATERIAL,
                                'UNITS' => $quantity * $mats[$i]->UNITS,
                                'PRICE' => $mats[$i]->PRICEBUY,   
                            );
                            if ($this->stock_model->add($mat_data) == TRUE) {
                                //UPDATE CURRENTSTOCK
                                $pidinstock = $this->goodsreceipts_model->productInStockCurrent($mats[$i]->MATERIAL, $this->input->post('LOCATION'));
                                if ($pidinstock) {
                                    $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION'),$mats[$i]->MATERIAL,$quantity * $mats[$i]->UNITS );
                                } else {
                                    $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION'),$mats[$i]->MATERIAL,$quantity * $mats[$i]->UNITS);
                                }
                                if ($reason == '1000') {
                                    $mat_data['ID'] = uniqid();
                                    $mat_data['UNITS'] = $quantity * $mats[$i]->UNITS * -1;
                                    $mat_data['LOCATION'] = $this->input->post('LOCATION1');
                                    if ($this->stock_model->add($mat_data) == TRUE) {
                                        //UPDATE CURRENTSTOCK
                                        $pidinstock = $this->goodsreceipts_model->productInStockCurrent($mats[$i]->MATERIAL, $this->input->post('LOCATION1'));
                                        if ($pidinstock) {
                                            $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION1'),$mats[$i]->MATERIAL,$quantity * $mats[$i]->UNITS );
                                        } else {
                                            $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION1'),$mats[$i]->MATERIAL,$quantity * $mats[$i]->UNITS);
                                        }
                                    }
                                }
                                
//                                if ($reason == '1') {
//                                    $this->products_model->productpricecalculation($quantity * $mats[$i]->UNITS,$mats[$i]->MATERIAL);
//                                }
                                
                            } else {
                                 redirect('inventory/stock/stockdiary');
                            }
                    }
                    
                    
                    if ($reason == '5') {
                        $form_data = array(
                            'ID' => uniqid(),
                            'DATENEW' => date("Y-m-d H:i:s",strtotime($this->input->post('DATENEW'))),
                            'REASON' => 5,
                            'LOCATION' => $this->input->post('LOCATION'),
                            'SUPPLIER' => $this->input->post('SUPPLIER_ID'),
                            'PRODUCT' => $this->input->post('PRODUCT'),
                            'UNITS' => $this->input->post('UNITS'),
                            'PRICE' => $this->input->post('PRICE'),
                        );
                        if ($this->stock_model->add($form_data) == TRUE) {
                            $pidinstock = $this->goodsreceipts_model->productInStockCurrent($this->input->post('PRODUCT'), $this->input->post('LOCATION'));
                            if ($pidinstock) {
                                    $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION'),$pid,$this->input->post('UNITS'));
                            } else {
                                    $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION'),$pid,$this->input->post('UNITS'));
                            }
                        }
                    }
                } else {
                    
                    $form_data = array(
                         'ID' => uniqid(),
                        'DATENEW' => date("Y-m-d H:i:s",strtotime($this->input->post('DATENEW'))),
                        'REASON' => $this->input->post('REASON'),
                        'LOCATION' => $this->input->post('LOCATION'),
                        'SUPPLIER' => $this->input->post('SUPPLIER_ID'),
                        'PRODUCT' => $this->input->post('PRODUCT'),
                        'UNITS' => $quantity,
                        'PRICE' => $this->input->post('PRICE'),
                    );
                    if ($this->stock_model->add($form_data) == TRUE) {
                        //UPDATE CURRENTSTOCK
                        $pidinstock = $this->goodsreceipts_model->productInStockCurrent($this->input->post('PRODUCT'), $this->input->post('LOCATION'));
                        if ($pidinstock) {
                            $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION'),$pid,$quantity );
                        } else {
                            $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION'),$pid,$quantity);
                        }
                        if ($reason == '1000') {
                            $form_data['ID'] = uniqid();
                            $form_data['UNITS'] = $quantity * -1;
                            $form_data['LOCATION'] = $this->input->post('LOCATION1');
                            if ($this->stock_model->add($form_data) == TRUE) {
                                //UPDATE CURRENTSTOCK
                                    $pidinstock = $this->goodsreceipts_model->productInStockCurrent($this->input->post('PRODUCT'), $this->input->post('LOCATION1'));
                                    if ($pidinstock) {
                                        $currentstock=$pidinstock[0]->UNITS;
                                        $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION1'),$pid,$quantity * -1 );
                                    } else {
                                        $currentstock=0;
                                        $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION1'),$pid,$quantity * -1);
                                    }
                            }
                        }
                        
                        if ($reason == '1') {
                            
                            $this->products_model->productpricecalculation($this->input->post('PRICE'),$pid,$currentstock,$quantity);
                            $mprodctlist = $this->products_model->productmaterialidwise($pid);
                            if($mprodctlist) {
                                foreach($mprodctlist as $mprodctrec) {
                                    $productrec = $this->products_model->productmaterialmaterialwise($mprodctrec->PRODUCT);
                                    $this->goodsreceipts_model->updateProductCost($productrec->PRODUCT, $productrec->TOTALAMOUNT);
                                }
                            }
                        }
                        
                    }
                }
                echo "Done";exit;
            //    redirect('inventory/stock/stockdiary');
            }


     public function deletestockdiary($id) {

            $where = array('ID' => $id);  
            $this->common->delete('STOCKDIARY',$where);
            $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
            redirect('inventory/stock/stockdiary');

        }

         public function editstockdiary($id) {
            $where = array('ID' => $id,);
            $data = $this->common->getWhere('STOCKDIARY',$where);

            echo json_encode($data);

        }


        private function getproductcategoriescombo($id = NULL) {
            $this->load->model('inventory/categories_model');
            $catarr = $this->categories_model->getproductcategories();
            $data = '<option value="">Select category</option>';
            for ($i = 0; $i < count($catarr); $i++) {
                if ($id != NULL && $id == $catarr[$i]->ID)
                    $data .= "<option id=\"option_custom\" selected=\"yes\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
                else
                    $data .= "<option id=\"option_custom\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
            }
            return $data;
        }

        //MATERIALS CATEGORY DROPDOWN LIST
        private function getmaterialcategoriescombo($id = NULL) {
            $this->load->model('inventory/categories_model');
            $catarr = $this->categories_model->getmaterialcategories();
            $data = '<option value="">Select</option>';
            for ($i = 0; $i < count($catarr); $i++) {
                if ($id != NULL && $id == $catarr[$i]->ID)
                    $data .= "<option id=\"option_custom\" selected=\"yes\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
                else
                    $data .= "<option id=\"option_custom\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
            }
            return $data;
        }

        //GET LOCATION LIST
        private function _getLocations($id = NULL) {
            $this->load->model('inventory/products_model');
            $catarr = $this->products_model->getLocations();
            $data = '';
            $data = '<option value="">Select</option>';
            for ($i = 0; $i < count($catarr); $i++) {
                if ($id != NULL && $id == $catarr[$i]->ID)
                    $data .= "<option id=\"option_custom\" selected=\"yes\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
                else
                    $data .= "<option id=\"option_custom\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
            }
            return $data;
        }

        //GET SUPPLIER LIST
        private function _getSuppliers($id = NULL) {
            $this->load->model('inventory/products_model');
            $catarr = $this->products_model->getSuppliers();
            $data = '';
            for ($i = 0; $i < count($catarr); $i++) {
                if ($id != NULL && $id == $catarr[$i]->ID)
                    $data .= "<option id=\"option_custom\" selected=\"yes\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
                else
                    $data .= "<option id=\"option_custom\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
            }
            return $data;
        }

        private function _getPIDbN($name) {
            $this->load->model('inventory/products_model');
            return $this->products_model->getpidbn($name);
        }

        function getsupplierautocomplete() {
            $term = $this->input->post('term', TRUE);
            $this->load->model('partner/suppliers_model');
            $rows = $this->suppliers_model->getsupplierautocomplete($term);
            $keywords = array();
            foreach ($rows as $row)
                array_push($keywords, $row->NAME);
            echo json_encode($keywords);
        }

        function getitemsautocomplete() {
            $term = $this->input->post('term', TRUE);
            $this->load->model('inventory/products_model');
            $rows = $this->products_model->getitemsautocomplete($term);
            $keywords = array();
            foreach ($rows as $row)
                array_push($keywords, array(
                    'label' => $row->NAME,
                    'value' => $row->ID,
                    'pricebuy' => $row->PRICEBUY,
                    'pricesell' => $row->PRICESELL
                ));
            echo json_encode($keywords);
        }

        function getlocations() {
            $term = $this->input->post('term', TRUE);
            $this->load->model('settings/warehouse_model');
            $rows = $this->warehouse_model->getwarehouseautocomplete($term);
            $keywords = array();
            foreach ($rows as $row)
                array_push($keywords, $row->NAME);
            echo json_encode($keywords);
        }

        public function getpnamebyrefcode() {
            $rcode = $this->input->post('reference');
            $this->load->model('inventory/stock_model');
            $result = $this->stock_model->getpnamebyrefcode($rcode);
            $data = '{"name": "' . $result[0]->NAME . '"}';
            echo $data;
        }

        public function getproductcostandqohinlocation() {
            $pname = $this->input->post('product');
            $location = $this->input->post('location');
            var_dump($location);
            $this->load->model('inventory/stock_model');
            $result = $this->stock_model->getproductcostandqoh($pname, $location);
            $data = '{"uom": "' . $result[0]->UOM . '", "cost": "' . $result[0]->COST . '", "qoh": "' . $result[0]->QOH . '"}';
            echo $data;
        }

        private function _getSUPPLIERIDbN($name) {
            $this->load->model('partner/suppliers_model');
            return $this->suppliers_model->getsupplieridbn($name);
        }

        function printgrn() {
            $this->load->helper('dompdf');
            $this->load->helper('file');
            $data['grn'] = $this->uri->segment(4);
            $data['printdate'] = date('d-m-Y', time());
            $data['user'] = $this->session->userdata('user');
            $this->load->model('inventory/goodsreceipts_model');
            $this->load->model('inventory/stock_model');
            //$poid = $this->goodsreceipts_model->getpoidbygrn($this->uri->segment(3));
            $this->load->model('settings/companyinfo_model');
            $data['companyinfo'] = $this->companyinfo_model->getcompanyinfo('0');
            $data['grn'] = $this->uri->segment(4);
            $data['grntype'] = 'others';
            $data['grnlines'] = $this->goodsreceipts_model->getgrnlineswithoutpo($this->uri->segment(4));
            $data['reason'] = $data['grnlines'][0]->REASON;
            $data['supplier'] = 0;
            $data['po'] = 0;
            $html = $this->load->view('inventory/goodsreceipt_print', $data, true);
            //echo $html;
            pdf_create($html, 'GRN_' . $data['grn'] . '-' . date('d-m-Y'));
            pdf_create($html, 'GRN_', false);
        }
        
        function createnew($status=''){
            
             $this->load->model('settings/warehouse_model');
             $data['locations'] = $this->common->getAll('LOCATIONS');
              $data['suppliers'] = $this->common->getAll('SUPPLIERS');
    //          $data['product'] = $this->common->getAll('PRODUCTS');
              $this->db->from('PRODUCTS');
            $this->db->order_by("NAME", "asc");
            $data['product']  = $this->db->get()->result();
        $data['template'] = 'inventory/stockdiary_add';
              $this->load->view('template',$data);
    }
    

        //WAREHOUSE AUTOCOMPLETE
        function getwarehousesautocomplete() {
            $term = $this->input->post('term', TRUE);
            $this->load->model('settings/warehouse_model');
            $rows = $this->warehouse_model->getwarehousesautocomplete($term);
            $keywords = array();
            foreach ($rows as $row)
                array_push($keywords, array(
                    'label' => $row->NAME,
                    'value' => $row->ID
                ));
            echo json_encode($keywords);
        }

        //REFERENCE AUTOCOMPLETE
        function getreferenceautocomplete() {
            $term = $this->input->post('term', TRUE);
            $this->load->model('inventory/products_model');
            $rows = $this->products_model->getreferenceautocomplete($term);
            $keywords = array();
            foreach ($rows as $row)
                array_push($keywords, $row->REFERENCE);
            echo json_encode($keywords);
        }

        //SUPPLIER AUTOCOMPLETE
        function getsupplierrsautocomplete() {
            $term = $this->input->post('term', TRUE);
            $this->load->model('partner/suppliers_model');
            $rows = $this->suppliers_model->getsupplierrsautocomplete($term);
            $keywords = array();
            foreach ($rows as $row)
                array_push($keywords, array(
                    'label' => $row->NAME,
                    'value' => $row->ID
                ));
            echo json_encode($keywords);
        }

        //UOM AUTOCOMPLETE
        function getuomautocomplete() {
            $term = $this->input->post('term', TRUE);
            $this->load->model('settings/uom_model');
            $rows = $this->uom_model->getuomautocomplete($term);
            $keywords = array();
            foreach ($rows as $row)
                array_push($keywords, array(
                    'label' => $row->NAME,
                    'value' => $row->ID
                ));

            echo json_encode($keywords);
        }

        //ITEM AUTOCOMPLETE
        function getitemautocomplete() {
            $term = $this->input->post('term', TRUE);
            $this->load->model('inventory/materials_model');
            $rows = $this->materials_model->getitemautocomplete($term);
            $keywords = array();
            foreach ($rows as $row)
                array_push($keywords, array(
                    'label' => $row->NAME,
                    'value' => $row->ID
                ));

            echo json_encode($keywords);
        }

        function record() {
            $this->load->model('inventory/stock_model');
            $this->load->model('inventory/goodsreceipts_model');
            $oper = $this->input->post('oper');
            $reason = $this->input->post('REASON');
            switch ($reason) {
                case '1':
                case '2':
                case '4':
                case '5':
                    $quantity = $this->input->post('UNITS') * 1;
                    break;
                case '-1':
                case '-2':
                case '-3':
                case '-4':
                case '-5':
                case '1000':
                    $quantity = $this->input->post('UNITS') * -1;
                    break;
            }

            if ($oper == 'del') {
                $id = $this->input->post('id');
                if ($id) {
                    //$this->stock_model->deleteitem_units($id);
                    $this->stock_model->delete($id);
                    $fdata = array('msgt' => 'S', 'msg' => 'Stock deleted successfully.');
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'inventory/stock/stockdiary');
                } else {
                    $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete product.');
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'inventory/stock/stockdiary');
                }
            } else {

                $pid = $this->input->post('ITEM_ID');
                $mats = $this->stock_model->getMaterialsProd($pid);

                if (sizeof($mats) > 0) {
                        for ($i = 0; $i < count($mats); $i++) {
                            $mat_data = array(
                            'ID' => uniqid(),
                            'DATENEW' => date("Y-m-d H:i:s",strtotime($this->input->post('DATENEW'))),
                            'REASON' => $this->input->post('REASON'),        
                            'LOCATION' => $this->input->post('LOCATION'),
                            'SUPPLIER' =>$this->input->post('SUPPLIER_ID'),
                            //'REFERENCE' => $this->input->post('REFERENCE'),
                            'PRODUCT' => $mats[$i]->MATERIAL,
                            'UNITS' => $quantity * $mats[$i]->UNITS,
                            'PRICE' => $mats[$i]->PRICEBUY,   
                        );
                        if ($this->stock_model->add($mat_data) == TRUE) {
                            //UPDATE CURRENTSTOCK
                            $pidinstock = $this->goodsreceipts_model->productInStockCurrent($mats[$i]->MATERIAL, $this->input->post('LOCATION'));
                            if ($pidinstock) {
                                $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION'),$mats[$i]->MATERIAL,$quantity * $mats[$i]->UNITS );
                            } else {
                                $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION'),$mats[$i]->MATERIAL,$quantity * $mats[$i]->UNITS);
                            }
                            if ($reason == '1000') {
                                $mat_data['ID'] = uniqid();
                                $mat_data['UNITS'] = $quantity * $mats[$i]->UNITS * -1;
                                $mat_data['LOCATION'] = $this->input->post('LOCATION1');
                                if ($this->stock_model->add($mat_data) == TRUE) {
                                    //UPDATE CURRENTSTOCK
                                    $pidinstock = $this->goodsreceipts_model->productInStockCurrent($mats[$i]->MATERIAL, $this->input->post('LOCATION1'));
                                    if ($pidinstock) {
                                        $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION1'),$mats[$i]->MATERIAL,$quantity * $mats[$i]->UNITS );
                                    } else {
                                        $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION1'),$mats[$i]->MATERIAL,$quantity * $mats[$i]->UNITS);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    $form_data = array(
                        'ID' => uniqid(),
                        'DATENEW' => date("Y-m-d H:i:s",strtotime($this->input->post('DATENEW'))),
                        'REASON' => $this->input->post('REASON'),
                        'LOCATION' => $this->input->post('LOCATION'),
                        'SUPPLIER' => $this->input->post('SUPPLIER_ID'),
                        'PRODUCT' => $this->input->post('ITEM_ID'),
                        'UNITS' => $quantity,
                        'PRICE' => $this->input->post('PRICE'),
                    );
                    
                    if ($this->stock_model->add($form_data) == TRUE) {
                        //UPDATE CURRENTSTOCK
                        $pidinstock = $this->goodsreceipts_model->productInStockCurrent($this->input->post('ITEM_ID'), $this->input->post('LOCATION'));
                        if ($pidinstock) {
                            $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION'),$this->input->post('ITEM_ID'),$quantity );
                        } else {
                            $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION'),$this->input->post('ITEM_ID'),$quantity);
                        }
                        if ($reason == '1000') {
                            $form_data['ID'] = uniqid();
                            $form_data['UNITS'] = $quantity * -1;
                            $form_data['LOCATION'] = $this->input->post('LOCATION1');
                            if ($this->stock_model->add($form_data) == TRUE) {
                                //UPDATE CURRENTSTOCK
                                $pidinstock = $this->goodsreceipts_model->productInStockCurrent($this->input->post('ITEM_ID'), $this->input->post('LOCATION1'));
                                if ($pidinstock) {
                                    $this->goodsreceipts_model->updateStockcurrent($this->input->post('LOCATION1'),$this->input->post('ITEM_ID'),$quantity * -1 );
                                } else {
                                    $this->goodsreceipts_model->insertStockcurrent($this->input->post('LOCATION1'),$this->input->post('ITEM_ID'),$quantity * -1);
                                }
                            }

                        }
                    }
                }
            }
        }
    }