<?php

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

class Bulkload extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->model('settings/companyinfo_model');
        $this->load->model('settings/bulkload_model');
        $this->load->model('inventory/goodsreceipts_model');
        set_time_limit(0);
    }

    function index() {

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

    function loadcategory() {

        $this->form_validation->set_rules('categories', 'Categories', 'trim|required');
        $categories = $this->input->post('categories');
        $categories_array = explode("\n", $categories);
        //$categories_array = array_unique($categories_array);
        $records = array();
        $cattotallines = 0;
        $catcreatedlines = 0;
        $catfailedlines = 0;
        $catemptylines = 0;
        $duplicateentries=array();
        $a='';
        foreach ($categories_array as $value) {
            if ($value != '') {
//                $a.=$this->bulkload_model->getcategoryid(trim($value))."<br/>";
                if($this->bulkload_model->getcategoryid(trim($value))){
                    array_push($duplicateentries,trim($value));
                }else{
                    if ($this->bulkload_model->loadcategory(array("ID" => uniqid(), "NAME" => trim($value))) == 1) {
                        $catcreatedlines = $catcreatedlines + 1;
                    } else {
                        $catfailedlines = $catfailedlines + 1;
                    }
                }
            } else {
                $catemptylines = $catemptylines + 1;
            }
            $cattotallines = $cattotallines + 1;
        }
//        echo $duplicateentries;exit;
        $duplicateentries   =   array_unique($duplicateentries);
        $fdata = array('msgt' => 'S', 'msg' => $cattotallines." ".$this->lang->line("LINESFOUND")." ".$catcreatedlines.
            " ".$this->lang->line("CATEGROIESCREATED")." ".$catfailedlines." ".$this->lang->line("LINESFAILED")." ".$catemptylines.
            " ".$this->lang->line("EMPTYLINES")." ",'duplicatemsg' => implode("<br/>",$duplicateentries),
            'duplicatelabel' => '<a data-toggle="modal" data-target="#confirmmodal" href="#">'.$this->lang->line("CLICK").'</a> '
            .$this->lang->line("TOVIEWDUPLICATEENTRIES"));
        $this->session->set_flashdata($fdata);
        redirect('settings/bulkload');
    }

    function loadproduct() {
        $this->form_validation->set_rules('barcode', 'Barcode', 'trim|required');
        $this->form_validation->set_rules('product', 'Product', 'trim|required');
        $this->form_validation->set_rules('buyprice', 'Buy Price', 'trim|required');
        $this->form_validation->set_rules('sellprice', 'Sell Price', 'trim|required');
        $this->form_validation->set_rules('category', 'Category', 'trim|required');
        $barcodes = $this->input->post('barcode');
        $products = $this->input->post('product');
        $buyprice = $this->input->post('buyprice');
        $sellprice = $this->input->post('sellprice');
        $category = $this->input->post('category');
        $barcodes_array = explode("\n", $barcodes);
        $products_array = explode("\n", $products);
        $buyprice_array = explode("\n", $buyprice);
        $sellprice_array = explode("\n", $sellprice);
        $category_array = explode("\n", $category);
        if (sizeof($barcodes_array)>0 && sizeof($barcodes_array) == sizeof($products_array) && sizeof($products_array) == sizeof($buyprice_array) && sizeof($buyprice_array) == sizeof($sellprice_array) && sizeof($sellprice_array) == sizeof($category_array)) {
            $records = array();
            $prototallines = 0;
            $procreatedlines = 0;
            $profailedlines = 0;
            $proemptylines = 0;
            $duplicates = 0;
            $linescreated=0;
            $entries = array();
            $entries = '';
            $duplipreentries=array();
            $sql = 'SELECT * FROM PRODUCTS';
            $existingdata = $this->common->customquery($sql);
            $Arrayreference =   array();
            $Arraycode      =   array();
            $Arrayname      =   array();
            $dupentries     =   array();
            if($existingdata){
                foreach ($existingdata as $exstvalue) {
                    array_push($Arraycode, strtoupper($exstvalue->CODE));
                    array_push($Arrayname, strtoupper($exstvalue->NAME));
                }
            }

            
            
            if($barcodes_array){
                $i=0;
                $catid  =   '';
                $validentries = array();
                foreach ($barcodes_array as $value) {
                    $value = str_replace(' ', '', $value);
                    if(trim($value)=='' || trim($products_array[$i])=='' || trim($buyprice_array[$i])=='' || trim($sellprice_array[$i])=='' || trim($category_array[$i])==''){
                        $proemptylines++;
                    }else{
                        $flag   =   0;
                        if (in_array(trim(strtoupper($value)), $Arraycode)) {
                            $flag   =   1;
                        }
                        if (in_array(trim(strtoupper($products_array[$i])), $Arrayname)) {
                            $flag   =   2;
                        }
                        $catid  =   $this->bulkload_model->getcategoryid(trim($category_array[$i]));
                        if($catid==null){
                            $flag   =   3;
                        }
                        if($validentries){
                            foreach($validentries as $validrec){
                                if(strtoupper(trim($validrec["CODE"]))==strtoupper(trim($value))){
                                    $flag   =   1;
//                                    break;
                                }
                                if(strtoupper(trim($validrec["NAME"]))==strtoupper(trim($products_array[$i]))){
                                    $flag   =   2;
//                                    break;
                                }
                            }
                        }
                        if($flag==0){
                            array_push($validentries, array(
                                'ID' => uniqid(),
                                'REFERENCE' => trim(preg_replace('/\s+/', '', $value)),
                                'CODE' => trim(preg_replace('/\s+/', '', $value)),
                                'NAME' => trim($products_array[$i]),
                                'PRICEBUY' => trim(preg_replace('/\s+/', '', $buyprice_array[$i])),
                                'PRICESELL' => trim(preg_replace('/\s+/', '', $sellprice_array[$i])),
                                'CATEGORY' => $catid,
                                'TAXCAT' => '000'
                            ));
                            $linescreated++;
                        }else{
                            if($flag==1)
                                $errormsg   =   $this->lang->line("CODEALREADYEXISTS");
                            else if($flag==2)
                                $errormsg   =   $this->lang->line("NAMEALREADYEXISTS");
                            else if($flag==3)
                                $errormsg   =   $this->lang->line("CATEGROYDOESNOTEXISTS");
                            else
                                $errormsg   =   '';
                            array_push($dupentries,array(
                                'CODE' => $value,
                                'NAME' => $products_array[$i],
                                'MSG'=>$errormsg
                            ));
                            $duplicates++;
                        }
                    }
                    $i++;
                }

                if($validentries){
                    $this->db->insert_batch('PRODUCTS', $validentries);                  
                }
            }
            if($dupentries){
                foreach($dupentries as $dupentry){
                    $dp="Code : ".$dupentry["CODE"]."<br/>".$this->lang->line("NAME")." : ".$dupentry["NAME"]."<br/>"
                            .$this->lang->line("ERRORMSG")." : ".$dupentry["MSG"];
                    array_push($duplipreentries,$dp);
                }
            }
            $duplipreentries    =   implode("<hr/>",$duplipreentries);
$fdata = array('msgt' => 'S', 'msg' => $i." ".$this->lang->line("LINESFOUND")." ".$linescreated.
    " ".$this->lang->line("PRODUCTSCREATED")." ".$duplicates." ".$this->lang->line("INVALIDENTRIES")." ".$proemptylines." ".$this->lang->line("EMPTYLINES"),
    'duplicatemsg'=>$duplipreentries,
    'duplicatelabel' => '<a data-toggle="modal" data-target="#confirmmodal" href="#"> '.$this->lang->line("CLICK").'</a> '.$this->lang->line("TOVIEWINVALIDENTRIES"));
            $this->session->set_flashdata($fdata);
            redirect('settings/bulkload');
        }
        else {
            $fdata = array('msgt' => 'E', 'msg' => $this->lang->line("LINESDOESNOTMATCH"));
            $this->session->set_flashdata($fdata);
            redirect('settings/bulkload');
        }
    }

    function loadstock() {
        $this->form_validation->set_rules('stockproduct', 'Products', 'trim|required');
        $this->form_validation->set_rules('stockquantity', 'Quantity', 'trim|required');
        $products = $this->input->post('stockproduct');
        $stock = $this->input->post('stockquantity');
        $products_array = explode("\n", $products);
        $stock_array = explode("\n", $stock);
        $records = array();
        $cattotallines = 0;
        $catcreatedlines = 0;
        $catfailedlines = 0;
        $catemptylines = 0;
        $duplicateentries=array();
        $locale = $this->companyinfo_model->getlocaleinfo();
        if($locale->LOCATION)
            $warehousesel   =   $locale->LOCATION;
        else
            $warehousesel   =   0;
        if (sizeof($products_array) == sizeof($stock_array)) {
                foreach ($products_array as $value) {
                    $value = str_replace(' ', '', $value);
                    if(trim($value)){
                        $existproduct   =   $this->bulkload_model->getproductcode(trim($value));
                        if(!$existproduct){
                            array_push($duplicateentries,trim($value));
                        }else{
                            if ($value != '' && $stock_array[$cattotallines] != '') {
                                $prid   =   $this->bulkload_model->getproductid(trim(preg_replace('/\s+/', '', $value)));
                                $pidinstock = $this->goodsreceipts_model->productInStockCurrent( $prid , $warehousesel);
                                if ($pidinstock) {
                                    $this->goodsreceipts_model->updateStockcurrent($warehousesel,$prid, trim(preg_replace('/\s+/', '', $stock_array[$cattotallines])));
                                } else {
                                    $this->goodsreceipts_model->insertStockcurrent($warehousesel, $prid, trim(preg_replace('/\s+/', '', $stock_array[$cattotallines])));
                                }
                                $catcreatedlines = $catcreatedlines + 1;
//                                if ($this->bulkload_model->loadstock(array("LOCATION" => $warehousesel,
//                                    "PRODUCT" => $this->bulkload_model->getproductid(trim(preg_replace('/\s+/', '', $value))),
//                                    "UNITS" => trim(preg_replace('/\s+/', '', $stock_array[$cattotallines])))) == 1) {
//                                    $catcreatedlines = $catcreatedlines + 1;
//                                } else {
//                                    $catfailedlines = $catfailedlines + 1;
//                                }
                                
                            } else {
                                $catemptylines = $catemptylines + 1;
                            }
                        }
                    }
                        $cattotallines = $cattotallines + 1;
                }
            $duplicateentries   =   array_unique($duplicateentries);
            $fdata = array('msgt' => 'S', 'msg' => $cattotallines." ".$this->lang->line("LINESFOUND")." ".$catcreatedlines
                ." ".$this->lang->line("STOCKUPDATED")." ".$catfailedlines." ".$this->lang->line("LINESFAILED")." ".$catemptylines 
                . $this->lang->line("EMPTYLINES")." ",'duplicatemsg' => implode("<br/>",$duplicateentries),
                'duplicatelabel' => '<a data-toggle="modal" data-target="#confirmmodal" href="#"> '. $this->lang->line("CLICK").'</a>'
                . ' '.$this->lang->line("TOVIEWTHEPRODUCTBARCODESNOTINPRODUCTTABLE"));
            $this->session->set_flashdata($fdata);
            redirect('settings/bulkload');
        } else {
            $fdata = array('msgt' => 'E', 'msg' => $this->lang->line("LINESDOESNOTMATCH"));
            $this->session->set_flashdata($fdata);
            redirect('settings/bulkload');
        }
    }

}
