<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Products extends MY_Controller {
    function __construct() {
        parent::__construct();
        $this->load->model('inventory/products_model');
        $this->load->model('inventory/Categories_model');
        $this->load->library('Formatslist');
        $this->load->model('settings/companyinfo_model');
        $this->load->model('inventory/tariff_model');
    }
    
    //GET PRODUCTS
    public function index() {
        $where = array('ID!=' => -1);
        $data['categories'] = $this->Categories_model->getallcategories();
        $data['tax_categories'] = $this->common->getWhere('TAXCATEGORIES',$where);
        $where_resources = array('NAME' => 'Product.Properties');
        $data['resources'] =  $this->common->getWhere('RESOURCES',$where_resources);
        $data['attributeset'] = $this->common->getAll('ATTRIBUTESET');
        $currencyFormat = $this->formatslist->formatCurrency(0);
        $data['currencyDecimel'] = strlen(substr(strrchr($currencyFormat, "."), 1));
        $this->db->from('PRODUCTS');
        $this->db->order_by("NAME", "asc");
        $data['product']  = $this->db->get()->result();
        $data['template'] = 'inventory/products_overview';
        $this->load->view('template',$data);
    }
    
    public function productdetails() {
        if ($this->uri->segment(4)) {
            $pid = $this->uri->segment(4);
        }
        $data['product'] = $this->getproductdetails($pid);
        $data['productid']=$pid;
        $data['fields']=$this->getproductlabeldetails($pid);
        $this->load->model('inventory/stock_model');
        $data['stock'] = $this->stock_model->getproductstock($pid);
        $data['tarifflist'] = $this->tariff_model->getalltariff();
         $data['template'] = 'inventory/product_details';
        $this->load->view('template',$data);
    }

    public function getproducts() {
        $sql = "SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.PRICEBUY, P.PRICESELL, P.ATTRIBUTES, P.CATEGORY, C.NAME AS categoryname,T.`NAME` AS Taxcategory FROM PRODUCTS P JOIN CATEGORIES C ON P.CATEGORY=C.ID LEFT JOIN TAXCATEGORIES T  ON P.TAXCAT = T.ID WHERE P.CATEGORY!=-1 ORDER BY  categoryname ASC,`NAME` ASC,PRICESELL ASC";
        $data['data'] = $this->common->customquery($sql);
        $data['data'] = $this->formatslist->formatCurrency(0);
        echo json_encode($data);
    }

    public function getproductdetails($id) {
        $sql = "SELECT P.*, C.NAME AS CATEGORYNAME FROM PRODUCTS P JOIN CATEGORIES C ON P.CATEGORY=C.ID WHERE P.ID LIKE '".$id."'";
        return $this->common->customquery($sql);
    }
    
//    public function listallproducts() {
//        $this->db->select('P.ID as id, P.CODE as barcode, P.NAME as text, P.PRICEBUY as pricebuy');
//        $this->db->from('PRODUCTS AS P');
//        $rows = $this->db->get()->result();
//        $keywords = array();
//        foreach ($rows as $row)
//            array_push($keywords, $row);
//        echo json_encode($keywords);
//    }
    
    function getproductlabeldetails($id) {
        $this->load->model('inventory/prodlabel_model');
        $result = $this->prodlabel_model->getproductdetails($id);
        $result->PRICESELL = $this->formatslist->formatCurrency($result->PRICESELL);
        $result->SELLPRICE = $this->formatslist->formatCurrency($result->PRICESELL);
        $result->PRICEBUY = $this->formatslist->formatCurrency($result->PRICEBUY);
        $result->SELLPRICETAX = $this->formatslist->formatCurrency($result->SELLPRICETAX);
        $result->PRICESELLTAX = $this->formatslist->formatCurrency($result->SELLPRICETAX);
        if(trim($result->ATTRIBUTES)){
            $productxml = simplexml_load_string(htmlspecialchars_decode($result->ATTRIBUTES));
        }
        $formatid = null;
        if(trim($result->ATTRIBUTES)){
            if ($productxml && $productxml->label && $productxml->label['format']) {
                $formatid = $productxml->label['format'];
            }
        }
        $labelformat = $this->getproductlabelformat($formatid);
        $labelfields = "";
        foreach ($labelformat->children() as $child) {
            $fieldname = '';
            preg_match('~{(.*?)}~', $child, $fieldname);
            if (count($fieldname) > 1) {
                list($pre, $post) = explode($fieldname[0], $child);
                
                
                
                //if(str_starts_with($fieldname[1],'PROPERTY.'))
                if(substr($fieldname[1], 0, strlen('PROPERTY.')) === 'PROPERTY.')
                 {
                    
                    $props=explode( '.', $fieldname[1]);
                     
                     if($productxml->entry['key']==$props[1])
                    {
                        
                        //echo $productxml->entry;
                         //$info[$n]['value'] = $productxml->entry;
                        $varstring  =   str_replace('"','&quot;',$productxml->entry);
                        
                         $labelfields .= '"' . $props[1]  . '": "' . $pre . $varstring . $post . '", ';
                    }
                }
                else
                {
                    $varstring  =   str_replace('"','&quot;',$result->{$fieldname[1]});
                    $labelfields .= '"' . $child->getName() . '": "' . $pre . $varstring . $post . '", ';
                }
                
                
            } else {
                $labelfields .= '"' . $child->getName() . '": "' . $child . '", ';
            }
        }
        $labelfields = rtrim($labelfields, ", ");
        $labelfields = "{" . $labelfields . "}";
        
        return $labelfields;
    }
    
    function getproductlabelformat($formatid) {
        $labelformats = $this->prodlabel_model->getlabelformats();
        if ($formatid != null) {
            foreach ($labelformats->label as $child) {

                if (intval($child['id']) == intval($formatid)) {
                    $labelformat = $child;
                }
            }
        } else {
            $labelformat = $labelformats->label[0];
        }
        return $labelformat;
    }

    function getproductlabelsize($sizeid) {
        $labelsizes = $this->prodlabel_model->getlabelsizes();
        if ($sizeid != null) {
            foreach ($labelsizes->label as $child) {

                if (intval($child['id']) == intval($sizeid)) {
                    $labelsize = $child;
                }
            }
        } else {
            $labelsize = $labelsizes->label[0];
        }
        return $labelsize;
    }
    
    function printlabel($productid) {

        $this->load->model('inventory/prodlabel_model');
        // $pname = $this->input->post('productid');
            $result = $this->prodlabel_model->getproductdetails($productid);
//        print_r($result);exit;
        $this->load->library('Label_helper');
        $labelsizes = $this->prodlabel_model->getlabelsizes();

        $productxml = simplexml_load_string(htmlspecialchars_decode($result->ATTRIBUTES));
        $sizeid = null;
        if ($productxml && $productxml->label && $productxml->label['size']) {
            $sizeid = $productxml->label['size'];
        } else {
            $sizeid = 1;
        }
        $labelsize = $this->getproductlabelsize($sizeid);
        $formatid = null;
        if ($productxml && $productxml->label && $productxml->label['format']) {
            $formatid = $productxml->label['format'];
        }
        $labelformat = $this->getproductlabelformat($formatid);
        $currencyFormat = $this->formatslist->formatCurrency(0);
        $currencyDecimel = strlen(substr(strrchr($currencyFormat, "."), 1));
        foreach ($labelformat->children() as $child) {
            foreach ($child->attributes() as $a => $b) {
                if($child->getName()=='price') {
                    $cur = str_replace("{PRICESELL}"," ",$child);
                }
            }
        }
        $result_print=json_decode($this->getproductlabeldetails($productid), TRUE);
        $result_print["product"]   =   $result_print["product"];
//      print_r($result_print);exit;
        $data = array();
        $info = array();
        $n=0;
        // exit();
        foreach ($result_print as $key => $value) {
            if ($key != 'submit' && $key != 'productid') {
                if ($key == 'barcode') {
                    $info[$n]['barcode'] = $value;
                } else {
                    $info[$n]['value'] = $value;
                }
                foreach ($labelformat->children() as $child) {
                    foreach ($child->attributes() as $a => $b) {
                        if($child->getName()==$key)
                        {$info[$n][$a] = $b;}
                    }
                }
                $n=$n+1;
            }
        }
//        echo "<pre>";print_r($info);exit;
        for ($i = 0; $i < intval($labelsize->rows) * intval($labelsize->cols); $i++) {
            array_push($data, $info);
        }
//        echo"<pre>";print_r($labelformat);exit;
        $pdf = new labelTemplate($sizeid, $data, $labelsize, false); //without border
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor("Saleculator");
        $pdf->SetTitle("Product Labels");
        $pdf->SetSubject("Saleculator Product Labels");
        $pdf->SetKeywords("saleculator, label, product, saleculator");
        // remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        // remove default margin
        $pdf->SetHeaderMargin(0);
        $pdf->SetFooterMargin(0);
        $pdf->SetAutoPageBreak(true, 0);
        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        $pdf->Addlabel();
        // Affichage du document dans le navigateur
        // $pdf->Output("labels.pdf", "I");
        ob_clean();
        $pdf->Output("labels.pdf", "I");
    }

    public function addproducts() {
                
        $id = $this->input->post('id');
        $data = array(
            'REFERENCE' => $this->input->post('reference'),
            'CODE' => $this->input->post('code'),
            'NAME' => $this->input->post('name'),
            'PRICEBUY' => $this->input->post('pricebuy'),
            'PRICESELL' => $this->input->post('pricesell'),
            'CATEGORY' => $this->input->post('category'),
            'TAXCAT' => ($this->input->post('taxcat')?$this->input->post('taxcat'):'000'),
            'STOCKCOST' => ($this->input->post('stock_cost_by_year')),
            'STOCKVOLUME' => ($this->input->post('stock_volume')),                   
            'ATTRIBUTES' =>htmlspecialchars_decode($this->input->post('proporties')),  
            'CATORDER' =>$this->input->post('catorder'),
            'INCAT' => ($this->input->post('incat') ? 1 : 0),  
            'ISSCALE' => ($this->input->post('isscale') ? 1 : 0),  
            'ISCOM' => ($this->input->post('iscom') ? 1 : 0),
            'ITEMTYPE' => ($this->input->post('ITEMTYPE') ? 1 : 0),
            // 'IMAGE' =>base64_encode(file_get_contents($_POST['imgfile']))
        );
        $lastbuyprice = $this->input->post("pricebuy");
        if(isset($_FILES["productimage"]["tmp_name"])) {
            if($_FILES["productimage"]["tmp_name"]!='') {
                $file_tmp = $_FILES["productimage"]["tmp_name"];
                $type = pathinfo($file_tmp, PATHINFO_EXTENSION);
                $fileimage = file_get_contents($file_tmp);
                $fileimage = base64_encode($fileimage);
                $fileimage = explode(',',$fileimage);
                $data["IMAGE"] = base64_decode($fileimage[0]);   
            }
        }
        if($this->input->post('attributeset_id')=='') {
            $data['ATTRIBUTESET_ID'] = null;
        } else  {
            $data['ATTRIBUTESET_ID'] = $this->input->post('attributeset_id');
        }
        
        if($id == '') { 
            $data['ID'] = uniqid();
            $prodid = $data['ID'];
            $where_condition = "REFERENCE='".$data['REFERENCE']."' OR CODE='".$data['CODE']."' OR NAME ='".$data['NAME']."'";
            $existdata = $this->common->existdata('PRODUCTS',$where_condition);
            if($existdata) {
                $dataResp    =   'false';
            }else{
                $this->common->insert('PRODUCTS',$data);
                $configdata =   $this->common->getAll('CONFIGURATION');
                $config_data = array('NEXTBARCODE' => $configdata[0]->NEXTBARCODE+1,);
                $this->companyinfo_model->updatelocaleinfo($config_data);
                $this->session->set_flashdata('success_msg', 'The record is added successfuly.');
                $dataResp    =   json_encode($data);
           }
        } else {
            $prodid = $id;
            $where = array('ID' => $id);
            $this->session->set_flashdata('success_msg', 'The record has been updated successfuly.');
            $this->common->update('PRODUCTS',$where,$data);
            $dataResp    =   json_encode($data);
        }
        $data_brk = array(
            'MATERIAL' => $this->input->post('brk_material'),
            'AMOUNT' => $this->input->post('brk_units'),
            'brk_pdt' => $prodid,
        );
//        $productprice = 0;
        
        $this->db->delete('PRODUCTS_MAT', array('PRODUCT' => $prodid));
        if($data_brk['MATERIAL']!='') {
            foreach($data_brk['MATERIAL'] as $key => $val) {
                $mat_data['PRODUCT'] = $prodid;
                $mat_data['MATERIAL'] = $data_brk['MATERIAL'][$key];
                $mat_data['AMOUNT'] =  $data_brk['AMOUNT'][$key];
                $this->common->insert('PRODUCTS_MAT',$mat_data); 
            }
        }
        echo $dataResp;
    }
    
    public function editproducts($id) {
        $where = array('ID' => $id,);
        $data = $this->common->getWhere('PRODUCTS',$where);
        echo json_encode($data);
    }
    
    public function deleteproducts($id) {
        $this->db->trans_start();
        $this->db->trans_strict(FALSE);
        $where = array('ID' => $id);  
        $where_exist = "PRODUCT='".$id."'";
//        $existdata = $this->common->existdata('PRODUCTS_MAT',$where_exist);
//        if($existdata) {
//            echo "false";
//        } else {
        $this->db->delete('PRODUCTS_MAT',$where_exist);
        $this->db->delete('PRODUCTS',$where);
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            echo "false";
        } else {
            $this->db->trans_commit();
            echo "true";
//            $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
//            redirect('inventory/products');
        }
//         }
    }
    
    // AUXILIARY PRODUCTS
    public function auxiliaryproducts() {
        $data['categories'] = $this->common->getAll('CATEGORIES');
        $data['product'] = $this->common->getAll('PRODUCTS');
        
        
        $this->db->select('P.ID, P.NAME');
        $this->db->from('PRODUCTS AS P');
        $this->db->where('ISCOM=', 1);
        $data['auxilaryproduct'] = $this->db->get()->result();

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

    // GET AUXILIARY PRODUCTS
    public function getauxiliaryproducts() {
        $data['data'] = $this->products_model->getauxiliaryproducts();
        echo json_encode($data);
    }

    //ADD AUXILIARY PRODUCT
    public function addauxiliaryproduct() {
        $id = $this->input->post('id');
        $data = array(
            'PRODUCT' =>  $this->input->post('product'),
            'PRODUCT2' => $this->input->post('auxiliaryproduct')                  
        );
        if($id == '') { 
            $existdata = $this->common->existdata('PRODUCTS_COM',$data);
            if($existdata) {
                $this->session->set_flashdata('success_msg', 'The record is already exist');
            } else {
                $data['ID'] =  uniqid();
                $insertdata = $this->common->insert('PRODUCTS_COM',$data);
                if($insertdata == 'FALSE') {
                   $this->session->set_flashdata('success_msg', 'Name is already exist');
                } else {
                   $this->session->set_flashdata('success_msg', 'The record is added successfuly.');
                }
            }
        } else {
          $where = array('ID' => $id);
          $this->session->set_flashdata('success_msg', 'The record has been updated successfuly.');
          $this->common->update('PRODUCTS_COM',$where,$data);
        }
        redirect('inventory/products/auxiliaryproducts');
    }
//EDIT AUXILIARY PRODUCT
    public function editauxiliaryproduct($id) {
        $where = array('ID' => $id,);
        $data = $this->common->getWhere('PRODUCTS_COM',$where);

        echo json_encode($data);
    }
  
     function deleteauxilaryproduct($id)
    { 
          $where = array('ID' => $id);  
        $this->common->delete('PRODUCTS_COM',$where);
        $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
        redirect('inventory/products/auxiliaryproducts');
    }
  
    //GET PRODUCT CATEGORIES LIST
    private function _getProdCategories($id = NULL) {
        $this->load->model('inventory/categories_model');
        $catarr = $this->categories_model->getproductcategories();

        $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 CUSTOMER CATEGORY LIST
    private function _getCustCategories($id = NULL) {
        $this->load->model('inventory/products_model');
        $catarr = $this->products_model->getcustcategories();
        $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 _pidBBCode($code) {
        $this->load->model('inventory/products_model');
        return $this->products_model->pidbbcode($code);
    }

    private function _getProdByCat($id) {
        $this->load->model('inventory/products_model');
        $catarr = $this->products_model->getprodbycat($id);
        $data = '';
        for ($i = 0; $i < count($catarr); $i++) {
            $data .= "<option id=\"option_custom\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
        }
        return $data;
    }

    private function _warehousesPBW($id = NULL) {
        $this->load->model('inventory/products_model');
        $catarr = $this->products_model->getWarehousesPBW();
        $data = '';
        for ($i = 0; $i < count($catarr); $i++) {
            if ($id != NULL && $id == $catarr[$i]->ID)
                $data .= "<option onclick=\"document.location.href='" . site_url() . "inventory/products/productsbw/" . $catarr[$i]->ID . "' \"id=\"option_custom\" selected=\"yes\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
            else
                $data .= "<option onclick=\"document.location.href='" . site_url() . "inventory/products/productsbw/" . $catarr[$i]->ID . "'\" id=\"option_custom\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
        }
        return $data;
    }

    private function _getPIDbB($id) {
        $this->load->model('inventory/products_model');
        return $this->products_model->getPIDbB($id);
    }

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

    private function _getProdNamebPID($id) {
        $this->load->model('inventory/products_model');
        return $this->products_model->getProdnamebPID($id);
    }

    private function _getTariffName($id) {
        $this->load->model('inventory/products_model');
        return $this->products_model->getTariffname($id);
    }

    //GET LOCATION LIST
    private function _getLocations($id = NULL) {
        $this->load->model('inventory/products_model');
        $catarr = $this->products_model->getLocations();
        $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;
    }

    //GET TAX CATEGORY LIST
    private function _getTaxCategories($id = NULL) {
        $this->load->model('inventory/products_model');
        $catarr = $this->products_model->gettaxcat();
        $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;
    }

    //GET TAXES LIST
    private function _getParentTax($id = NULL) {
        $this->load->model('inventory/products_model');
        $catarr = $this->products_model->getparenttax();
        $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 _getTariffList($id = NULL) {
        $this->load->model('inventory/products_model');
        $catarr = $this->products_model->gettariff();
        $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;
    }

    public function order() {
        if ($this->uri->segment(4)) {
            $ord = ($this->uri->segment(5)) ? $this->uri->segment(5) : 'ASC';
            $this->index($this->uri->segment(4), $ord);
        }
    }

    public function setrecords() {
        if ($this->uri->segment(4) && is_numeric($this->uri->segment(4))) {
            $data = array('records' => $this->uri->segment(4));
        } else {
            $data = array('records' => 20);
        }
        $this->session->set_userdata($data);
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function formparse() {
        $fdata = array('msgt' => 'E', 'msg' => 'Nothing Selected.');
        switch ($this->input->post('location')) {
            case "products":
                if ($this->input->post('new_x'))
                    redirect(site_url() . 'inventory/products/add');
                elseif ($this->input->post('dosearch') && $this->input->post('search') != "")
                    redirect(site_url() . 'inventory/products/search/' . $this->input->post('search'));
                elseif ($this->input->post('edit_x') && $this->input->post('chk'))
                    redirect(site_url() . 'inventory/products/edit/' . $this->input->post('chk'));
                elseif ($this->input->post('delete_x') && $this->input->post('chk'))
                    redirect(site_url() . 'inventory/products/delete/' . $this->input->post('chk'));
                elseif ($this->input->post('addtocatalog_x') && $this->input->post('chk'))
                    redirect(site_url() . 'inventory/products/catalogadd/' . $this->input->post('chk'));
                elseif ($this->input->post('removecatalog_x') && $this->input->post('chk'))
                    redirect(site_url() . 'inventory/products/remfcat/' . $this->input->post('chk'));
                else {
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'inventory/products');
                }
                break;
            case 'customers':
                if ($this->input->post('new_x') or $this->input->post('new_y'))
                    redirect(site_url() . 'customers/add');
                elseif ($this->input->post('edit_x') && $this->input->post('chk'))
                    redirect(site_url() . 'customers/edit/' . $this->input->post('chk'));
                elseif ($this->input->post('delete_x') && $this->input->post('chk'))
                    redirect(site_url() . 'customers/delete/' . $this->input->post('chk'));
                elseif ($this->input->post('dosearch') && $this->input->post('search') != "")
                    redirect(site_url() . 'customers/search/' . $this->input->post('search'));
                else {
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'customers');
                }
                break;
            case 'warehouses':
                if ($this->input->post('new_x') or $this->input->post('new_y'))
                    redirect(site_url() . 'inventory/products/addwarehouse');
                elseif ($this->input->post('edit_x') && $this->input->post('chk'))
                    redirect(site_url() . 'inventory/products/warehouseEdit/' . $this->input->post('chk'));
                elseif ($this->input->post('delete_x') && $this->input->post('chk'))
                    redirect(site_url() . 'inventory/products/removewarehouse/' . $this->input->post('chk'));
                else {
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'inventory/products/warehouses');
                }
                break;
            case 'categories':
                if ($this->input->post('new_x'))
                    redirect(site_url() . 'categories/add');
                elseif ($this->input->post('edit_x') && $this->input->post('chk'))
                    redirect(site_url() . 'categories/edit/' . $this->input->post('chk'));
                elseif ($this->input->post('delete_x') && $this->input->post('chk'))
                    redirect(site_url() . 'categories/delete/' . $this->input->post('chk'));
                else {
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'categories');
                }
                break;
            case 'taxes':
                if ($this->input->post('new_x'))
                    redirect(site_url() . 'inventory/products/addtax');
                elseif ($this->input->post('edit_x') && $this->input->post('chk') != "")
                    redirect(site_url() . 'inventory/products/edittax/' . $this->input->post('chk'));
                elseif ($this->input->post('delete_x') && $this->input->post('chk'))
                    redirect(site_url() . 'inventory/products/removetax/' . $this->input->post('chk'));
                else {
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . ' inventory/products/taxes');
                }
                break;
            case 'users':
                if ($this->input->post('new_x'))
                    redirect(site_url() . 'settings/users/add');
                elseif ($this->input->post('edit_x') && $this->input->post('chk') != "")
                    redirect(site_url() . 'settings/users/edit/' . $this->input->post('chk'));
                elseif ($this->input->post('delete_x') && $this->input->post('chk') != "")
                    redirect(site_url() . 'settings/users/delete/' . $this->input->post('chk'));
                else {
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'settings/users');
                }
                break;
            case 'roles':
                if ($this->input->post('new_x'))
                    redirect(site_url() . 'settings/users/roleadd');
                elseif ($this->input->post('edit_x') && $this->input->post('chk') != "")
                    redirect(site_url() . 'settings/users/rolesedit/' . $this->input->post('chk'));
                elseif ($this->input->post('delete_x') && $this->input->post('chk') != "")
                    redirect(site_url() . 'settings/users/roledelete/' . $this->input->post('chk'));
                else {
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'settings/users/roles');
                }
                break;
            case 'customercat':
                if ($this->input->post('new_x'))
                    redirect(site_url() . 'customers/addcat');
                elseif ($this->input->post('edit_x') && $this->input->post('chk') != "")
                    redirect(site_url() . 'customers/editcat/' . $this->input->post('chk'));
                elseif ($this->input->post('delete_x') && $this->input->post('chk') != "")
                    redirect(site_url . 'customers/delcat/' . $this->input->post('chk'));
                else {
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'customers/categories');
                }
                break;
        }
    }

    public function _getCategoryName($id) {
        $this->load->model('inventory/products_model');
        return $this->products_model->getCategoryName($id);
    }

    public function _getTaxCatName($id) {
        $this->load->model('inventory/products_model');
        return $this->products_model->getTaxCatName($id);
    }

    public function _getLocName($id) {
        $this->load->model('inventory/products_model');
        return $this->products_model->getLocName($id);
    }

    public function _movementReason($id) {
        switch ($id) {
            case '1': return 'Purchase';
                break;
            case '2': return 'Refund (in)';
                break;
            case '4': return 'Movement (in)';
                break;
            case '5': return 'Production';
                break;
            case '-1': return 'Sale';
                break;
            case '-2': return 'Refund (out)';
                break;
            case '-3': return 'Break (out)';
                break;
            case '-4': return 'Movement (out)';
                break;
            case '999': return 'Request';
                break;
            case '1000';
                return 'Crossing';
                break;
        }
    }
    //PRODUCTS BY WAREHOUSE
    public function productsbw() {
        $data['warehouses'] = $this->_warehousesPBW();
        $this->load->view('settings/header');
        $this->load->view('productsbw_overview', $data);
        $this->load->view('settings/footer');
    }

    //GET PRODUCTS BY WAREHOUSE
    public function getproductsbw() {

        $this->load->model('inventory/products_model');
        echo $this->products_model->getproductsbw();
    }
    //EDIT TARIFF
    public function edittariff() {
        $this->load->model('inventory/products_model');
        $this->load->library('form_validation');
        $this->form_validation->set_rules('tariff', 'Tariff', 'trim|required');
        $this->form_validation->set_rules('lineitems', 'Products', 'trim|required');
        if ($this->input->post('update')) {
            $id = $this->uri->segment(4);
            $this->products_model->updateTariff(
                    $id,
                    $this->input->post('tariff')
            );
            $this->products_model->deleteLines($id);
            $plist = unserialize($this->input->post('lineitems'));
            foreach ($plist as $line) {
                $this->products_model->addTariffareas_prod(array(
                    'TARIFFID' => $id,
                    'PRODUCTID' => $this->_getPIDbN($line['PRODUCT']),
                    // 'PRICESELL' => $this->input->post('price')
                    'PRICESELL' => $line['PRICE']
                ));
            }
            $fdata = array('msgt' => 'S', 'msg' => 'Record updated successfully.');
            $this->session->set_flashdata($fdata);
            redirect(site_url() . 'products/tariff');
        } else {

            // $data['tariff'] = $this->products_model->tariffData($this->uri->segment(3));
            $data['tariff'] = $this->products_model->getGroupById($this->uri->segment(4));
            $lines = $this->products_model->getlines($id = $this->uri->segment(4));
            $data['lines'] = json_encode($lines);

            $this->load->view('settings/header');
            $this->load->view('tariff_edit_ovw', $data);
            $this->load->view('settings/footer');
        }
    }
    //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;
    }

   
    function exportcsv() {


        $file="products.csv";
        header("Content-Disposition: attachment; filename=" . urlencode($file));
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Description: File Transfer");
        header("Content-type: application/csv");
        header("Pragma: no-cache");
        header("Expires: 0");

        $export= $this->input->post('exportdata');
        $this->load->helper('download');
        force_download($file, $export);
    }
     //FOR AUTOCOMPLETE TO GET PRODUCTS FROM TABLE
    function getproductsautocomplete() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('inventory/products_model');
        $rows = $this->products_model->getproductsautocomplete($term);
        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, $row->NAME);
        echo json_encode($keywords);
    }
    
    function getname1() {
       
        $this->load->model('inventory/products_model');
        $rows = $this->products_model->getname1($term);
        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, $row->NAME);
        echo json_encode($keywords);
    }
     
    function productautocomplete() {
        $term = $this->input->get('term', TRUE);
        $this->load->model('inventory/Products_model');
        $rows = $this->Products_model->getitemsautocomplete($term);
        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, array(
                        'id' => $row->ID,
                        'reference' => $row->REFERENCE,
                        'value' => $row->NAME,
                        'price' => $row->PRICEBUY,
                        'code' => $row->CODE,
               //'description' => $row->DESCRIPTION
                    ));

        echo json_encode($keywords);
    }
       function record1()
    {
        $this->load->model('inventory/products_model');
        $oper = $this->input->post('oper');
        $id = uniqid();
        
        /*if($oper=='del')
        {
            $id = $this->input->post('id');
          
            if($id)
            {
                $this->products_model->delete1($id);
                $fdata = array('msgt' => 'S', 'msg' => 'Product deleted successfully.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'inventory/products/auxiliaryproducts');
            }
            else {
                $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete product.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'inventory/products/auxiliaryproducts');
            }
        }
        else{*/
            $form_data = array(
                     'ID' => $id,
                    'PRODUCT' => $this->_getPIDbN($this->input->post('PRODUCT')),
                    'PRODUCT2' => $this->_getPIDbN($this->input->post('PRODUCT2')),
                    
            );
           
                var_dump($form_data);
        
        if($oper=='add')
        {
             if ($this->products_model->add1($form_data) == TRUE) {
             $fdata = array('msgt' => 'S', 'msg' => 'Product added successfully.');
                $this->session->set_flashdata($fdata);
                return true;
         }
        }
        elseif($oper=='edit')
        {
            $id = $this->input->post('ID');
            if($id)
            {
               
                $this->products_model->update1($id, $form_data);   
            }
        }
        
    }
    function deleteproduct()
    { $this->load->model('inventory/products_model');
        if ($this->uri->segment(4)) 
            {
           $this->products_model->deleteproducts_cat($this->uri->segment(4));
            if($this->products_model->delete($this->uri->segment(4))==true){
            $fdata = array('msgt' => 'S', 'msg' => 'Product deleted successfully.');
            $this->session->set_flashdata($fdata);
            redirect(site_url() . 'inventory/products');
              }else{
            $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete product.');
            $this->session->set_flashdata($fdata);

            redirect(site_url() . 'inventory/products');
        }
    }}
   /***************************************************************/
    function getproductsfromcode() {
        $term = $this->input->get('term', TRUE);
        $this->load->model('inventory/products_model');
        $rows = $this->products_model->productfindcodewise($term);
        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, $row);
        echo json_encode($keywords);
    }



// edited by geethu
    function getConfiguration()
    {
         $data = $this->common->getAll('CONFIGURATION');
         // print_r($data);
         echo json_encode($data);  
    }

    public function getProductCategories() {
        $this->load->model('inventory/categories_model');
        $catarr = $this->categories_model->getproductcategories();
             echo  "<option id=\"option_custom\" value=''>--- Select ---</option>\n";
        foreach ($catarr as $key => $value) {
            echo  "<option id=\"option_custom\" value=\"" . $value->ID . "\">" . $value->NAME . "</option>\n";
        }
    }

     public function getProductMaterials() {
        $this->load->model('inventory/categories_model');
        if(isset($_POST['cate_id']))
            $cate_id = $_POST['cate_id'];
        else 
            $cate_id = '';
        $catarr = $this->categories_model->getProductmaterialsforBreak($cate_id);
            echo  "<option id=\"option_custom\" value=''>--- Select ---</option>\n";
        foreach ($catarr as $key => $value) {
            echo  "<option id=\"option_custom\" value=\"" . $value->ID . "\" data-buyprice=\"" . $value->PRICEBUY . "\">" . $value->NAME . "</option>\n";
        }
    }


    
    public function getproductdetailsWithID() {
        $sql = "SELECT P.ID,P.REFERENCE,P.CODE,P.CODETYPE,P.NAME,P.PRICEBUY,P.PRICESELL,P.CATEGORY,P.TAXCAT,P.ATTRIBUTESET_ID,P.STOCKCOST,"
                . "P.STOCKVOLUME,P.ISCOM,P.ISSCALE,P.ATTRIBUTES,P.INCAT,P.CATORDER,P.ITEMTYPE,C.NAME AS CATEGORYNAME FROM PRODUCTS P JOIN CATEGORIES C ON P.CATEGORY=C.ID"
                . " WHERE P.ID LIKE '".$_POST['pid']."'";
        // echo $sql;
            $data = $this->common->customquery($sql);
            $currencyFormat = $this->formatslist->formatCurrency(0);
            $currencyDecimel = strlen(substr(strrchr($currencyFormat, "."), 1));
            
            $data[0]->HDPRICESELL = $data[0]->PRICESELL;
            $data[0]->PRICESELL = number_format($data[0]->PRICESELL,$currencyDecimel);
            $data[0]->PRICEBUY = number_format($data[0]->PRICEBUY,$currencyDecimel);
            echo json_encode($data);
    }

    public function getBreakdownDetails() {
        $sql = "SELECT  M.PRODUCT,M.MATERIAL, M.AMOUNT AS AMOUNT,
            (SELECT NAME FROM PRODUCTS WHERE PRODUCTS.ID=M.MATERIAL) AS MATERIAL_NAME,
            (SELECT PRICEBUY FROM PRODUCTS WHERE PRODUCTS.ID=M.MATERIAL) AS MATERIAL_PRICEBUY,
            (SELECT `CODE` FROM PRODUCTS WHERE PRODUCTS.ID=M.MATERIAL) AS BARCODE,
            (SELECT `CATEGORY` FROM PRODUCTS WHERE PRODUCTS.ID=M.MATERIAL) AS CATEGORY_ID,
            (SELECT C.NAME FROM PRODUCTS LEFT JOIN CATEGORIES C ON C.ID=PRODUCTS.CATEGORY WHERE PRODUCTS.ID=M.MATERIAL) AS CATEGORY
            FROM PRODUCTS_MAT M WHERE  PRODUCT  LIKE '".$_POST['pid']."'";
            // echo $sql;
            $data = $this->common->customquery($sql);
            echo json_encode($data);
            
    }

    public function deleteBreakdownData()
    {
        $where = array('MATERIAL' => $_POST['delete_brk'],'PRODUCT'=>$_POST['pdt_id']);  
        $this->common->delete('PRODUCTS_MAT',$where);
       
    }
    public function datatableGetproductDetails() {
        $ownerid=$this->session->userid;
        $columns = array( 
            0 =>'sl', 
            1=> 'CATEGORY',
            2 =>'REFERENCE',
            3=> 'CODE',
            4=> 'NAME',
            5=> 'PRICEBUY',
            6=> 'PRICESELL',
            7=> 'taxcategory',
            8=> 'TAXRATE',
            9=> 'ID',
            10=> 'ITEMTYPE'
        );
        $limit = $this->input->post('length'); 
        $start = $this->input->post('start');
        if($this->input->post('order')[0]['column'])
            $order = $columns[$this->input->post('order')[0]['column']];
        else
            $order= '';
        $dir = $this->input->post('order')[0]['dir'];
        $search_array = array();  
        if($this->input->post('search')['value']) {
            $search_array['search'] = $this->input->post('search')['value'];
        }
        if($this->input->post('searchbarcode')){
            $search_array['searchbarcode'] = $this->input->post('searchbarcode');
        }
        if($this->input->post('searchbyitemtype')){
            $search_array['searchbyitemtype'] = $this->input->post('searchbyitemtype');
        }
        if($this->input->post('searchbycategory')){
            $search_array['searchbycategory'] = $this->input->post('searchbycategory');
        }
        if(count($search_array)==0) {
            $totalData = $this->products_model->all_products_count();
            $totalFiltered = $totalData[0]->total;
            $productslist = $this->products_model->all_products($limit,$start,$dir, $ownerid,$order);
            if($totalData[0]->total>0) {
                $totcount   =   $totalData[0]->total;
            } else {
                $totcount   =   0;
            }
        } else {
            $productslist =  $this->products_model->products_search($limit,$start,$search_array,$dir,$ownerid,$order);
            $totalFiltered = $this->products_model->products_search_count($search_array,$ownerid);
            if($totalFiltered>0) {
                $totcount   =   $totalFiltered;
            } else {
                $totcount   =   0;
            }
        }
        $data = array();
        if($productslist) {
            $account_id = 0;
            $j = $start+1;
            foreach ($productslist as $row){
                $nestedData['sl'] = $j;
                $nestedData['categoryname'] =   $row->categoryname;
                $nestedData['REFERENCE']    =   $row->REFERENCE;
                $nestedData['CODE']         =   $row->CODE;
                $nestedData['NAME']         =   '<a href="'.base_url('inventory/products/productdetails/').$row->ID.'">'.$row->NAME.'</a>';
                $nestedData['PRICEBUY']     =   $this->formatslist->formatCurrencywithHash($row->PRICEBUY);
                $nestedData['PRICESELL']    =   $this->formatslist->formatCurrencywithHash($row->PRICESELL);
                $nestedData['taxcategory']  =   $row->taxcategory;
                $nestedData['TAXRATE']      =   $this->formatslist->formatCurrencywithHash($row->TAXRATE);
                $nestedData['ID']           =   '<a class="btn btn-info btn-xs" onclick="return myFunction(\''.$row->ID.'\')" data-toggle="modal" data-target="#myModal" id='.$row->ID.' href="#"><i class="fa fa-edit"></i></a>&nbsp;&nbsp;<a class="btn btn-danger btn-xs" data-toggle="modal" data-target="#confirmmodal" onclick="return confirmFunction(\''.$row->ID.'\')" id='.$row->ID.' href="#"><i class="fa fa-trash"></i></a>&nbsp;&nbsp;<a class="btn btn-success btn-xs" onclick="printFunction(\''.$row->ID.'\')" id='.$row->ID.' href="#"><i class="fa fa-print"></i></a>';
                
//                $nestedData['ISMAT']        =   ($row->ISMAT==1 ? 'M' : 'P');
                $data[] = $nestedData;
                $j++;
            }
        }       
        $json_data = array(
            "draw"            => intval($this->input->post('draw')),  
            "recordsTotal"    => intval($totcount),  
            "recordsFiltered" => intval($totalFiltered), 
            "data"            => $data   
        );
        echo json_encode($json_data);
        
    }

    public function excelExportData()
    {
      // $this->load->library('excel');
      $this->excel->setActiveSheetIndex(0);
      $this->excel->getActiveSheet()->setCellValue('A1', "Category Data - Printed on : ".date(time()));
      $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007');
      $fileName = 'products.xls';
      header('Content-type: application/vnd.ms-excel');
      header('Content-Disposition: attachment; filename='.$fileName.'');
      // $objWriter->save('php://output');

    }
    public function exportXMLData()
  {

  $this->load->dbutil(); // call db utility library
  $this->load->helper('download'); // call download helper

  $query = $this->db->query("SELECT * FROM products"); // whatever you want to export to CSV, just select in query

      $config = array (
        'root'          => 'root',
        'element'       => 'element',
        'newline'       => "\n",
        'tab'           => "\t"
      ); // define XML document structure

  $filename = 'products.xml'; // name of csv file to download with data
  force_download($filename, $this->dbutil->xml_from_result($query, $config)); // download file

  }
  public function exportPDFData($parm='')
        {
            $this->load->library('pdf');    
            $obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);  
            $obj_pdf->SetCreator(PDF_CREATOR);  
            $obj_pdf->SetTitle("PRODCUTS DATA");  
            $obj_pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);  
            $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));  
            $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));  
            $obj_pdf->SetDefaultMonospacedFont('helvetica');  
            $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);  
            $obj_pdf->SetMargins(PDF_MARGIN_LEFT, '10', PDF_MARGIN_RIGHT);  
            $obj_pdf->setPrintHeader(false);  
            $obj_pdf->setPrintFooter(false);  
            $obj_pdf->SetAutoPageBreak(TRUE, 10);  
            $obj_pdf->SetFont('helvetica', '', 11);  
            $obj_pdf->AddPage();  
            // $content = 'PRODCUTS';  
            $content = '  
            <table border="1" cellspacing="0" cellpadding="3">  
                 <tr>  
                      <th width="15%">ID</th>  
                      <th width="30%">NAME</th>  
                      <th width="15%">CODE</th>  
                      <th width="15%">REFERENCE</th>  
                      <th width="15%">PRICEBUY</th>  
                      <th width="15%">PRICESELL</th>  
                 </tr>  
            ';  
             $content .= $this->fetch_data_for_PDF($parm);  
            $content .= '</table>';  
            $obj_pdf->writeHTML($content);  
            $obj_pdf->Output('file.pdf', 'D');  
        }

        public function fetch_data_for_PDF($parm='') {
           // $where = array('ID' => '5a1479af70eb5');
          $sql   =  "SELECT P.*,T.NAME AS taxcategory, C.NAME AS categoryname,(((SELECT MAX(RATE) FROM TAXES WHERE CATEGORY=T.ID)*P.PRICESELL)+P.PRICESELL) AS TAXRATE FROM PRODUCTS P JOIN CATEGORIES C ON P.CATEGORY=C.ID LEFT JOIN TAXCATEGORIES T ON P.TAXCAT=T.ID WHERE P.CATEGORY!=-1";
          if($parm)
              $sql.=  " AND (C.NAME LIKE '%".$parm."%' OR P.REFERENCE LIKE '%".$parm."%' OR P.CODE LIKE '%".$parm."%' OR P.NAME LIKE '%".$parm."%' OR P.PRICEBUY LIKE '%".$parm."%' OR P.PRICESELL LIKE '%".$parm."%' OR T.NAME LIKE '%".$parm."%' )";
//          $sql.=   ' LIMIT 0, 10';
//          echo $sql;exit;
          $data = $this->common->customquery($sql);
          $output = '';
          if($data){
          foreach ($data as $key => $value) {
           $output .= '<tr>
           <td width="15%">'.$value->ID.'</td>  
            <td width="30%">'.$value->NAME.'</td>  
            <td width="15%">'.$value->CODE.'</td>  
            <td width="15%">'.$value->REFERENCE.'</td>  
            <td width="15%">'.$value->PRICEBUY.'</td>  
            <td width="15%">'.$value->PRICESELL.'</td>  
           </tr>';
          }
          return $output;
        }
        }
        function savetariff(){
            if($_POST["tariffid"]){
                $i=0;
                $this->tariff_model->deleteTariffbyproduct($_POST["prodId"]);
                foreach($_POST["tariffid"] as $tariff){
                    if($_POST["price"][$i]){
                        $dataArray["PRODUCTID"]    =   $_POST["prodId"];
                        $dataArray["TARIFFID"]    =   $tariff;
                        $dataArray["PRICESELL"]    =   $_POST["price"][$i];
                        $this->tariff_model->addTariffareas_prod($dataArray);
                    }
                    $i++;
                }
            }
            $this->session->set_flashdata('success_msg1', 'The record has been updated successfuly.');
            redirect(site_url() . 'inventory/products/productdetails/'.$_POST["prodId"]);
        }
        function reorderlevel(){
            $this->load->model('inventory/stock_model');
            if($_POST){
                $k=0;
                $this->stock_model->deletereorderstock($_POST["prodId"]);
                foreach($_POST["LOCATION"] as $location){
                    $dataArray["ID"]            =   uniqid();
                    $dataArray["LOCATION"]      =   $location;
                    $dataArray["PRODUCT"]       =   $_POST["prodId"];
                    $dataArray["STOCKSECURITY"] =   $_POST["minimum"][$k];
                    $dataArray["STOCKMAXIMUM"]  =   $_POST["maxmimum"][$k];
                    $this->stock_model->addreorderstock($dataArray);
                    $k++;
                }
            }
            $this->session->set_flashdata('success_msg', 'The record has been updated successfuly.');
            redirect(site_url() . 'inventory/products/productdetails/'.$_POST["prodId"]);
        }
                
        function getproductsfromid() {
            $id = $this->input->get('id', TRUE);
            $this->load->model('inventory/products_model');
            $rows = $this->products_model->getproductbyidautofill($id);
            $keywords = array();
            foreach ($rows as $row)
                array_push($keywords, $row);
            echo json_encode($keywords);
        }
        
        function getproductimage($prid='') {
            $this->db->select('P.IMAGE');
            $this->db->from('PRODUCTS AS P');
            $where = "P.ID='".$prid."'";
            $this->db->where($where);
            $imagesrc   =   $this->db->get()->row()->IMAGE;
            echo base64_encode($imagesrc);
        }
        
        
        public function breakdownproductlistall(){
            $this->load->model('inventory/Products_model');
            $this->load->model('inventory/stock_model');
            // coulmn declaration
            $aColumns = array( 'C.NAME','P.CODE','P.NAME','P.PRICEBUY','P.PRICESELL');
            // 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 = "";
                }
            }
            $sWhere = "";
            if ( $_GET['sSearch'] != "" ) {
                $sWhere = "WHERE (";
                for ( $i=0 ; $i<4 ; $i++ ) {
                    $sWhere .= $aColumns[$i]." LIKE '%".$_GET['sSearch']."%' OR ";
                }
                $sWhere = substr_replace( $sWhere, "", -3 );
                $sWhere .= ')';
            }
            // get data
            $order = str_replace(" ORDER BY", '', $sOrder);  
            // echo $sLimit;
            $limit = ' '.$sLimit;
            if($sWhere!='') {
                //$where = ' AND ';
                $where = str_replace(" WHERE", '',$sWhere); 
            } else {
                $where = '';
            }
            $barcodesearchchar    =   $_GET["sSearch_0"];
            if($sWhere){
                if($barcodesearchchar){
                    $where .= " AND P.CODE='".$barcodesearchchar."'";
                }
            }else{
                if($barcodesearchchar){
                    $where .= " WHERE P.CODE='".$barcodesearchchar."'";
                }
            }
            // echo $where;exit;
            $sql = "SELECT P.*,C.NAME AS CATEGORYNAME from PRODUCTS P LEFT JOIN CATEGORIES C ON P.CATEGORY=C.ID ".$where.$sOrder.$limit;
            //echo $sql;  exit;
            $arr = $this->common->customquery($sql);
            $totalCount_sql   =  "SELECT count(*)AS total FROM PRODUCTS P LEFT JOIN CATEGORIES C ON P.CATEGORY=C.ID ".$where;
            $totalCount = $this->common->customquery($totalCount_sql);
            // echo"<pre>";print_r($totalCount);
            $iTotal  = $totalCount[0]->total;
            /*
             * Output
             */
            $output = array(
              "sEcho" => intval($_GET['sEcho']),
              "iTotalRecords" => $iTotal,
              "iTotalDisplayRecords" => $iTotal,
              "aaData" => array()
            );
            $j=1;
            unset($aColumns[1]);
            $aColumns[1] = 'categoryname';
            unset($aColumns[7]);
            $aColumns[7] = 'taxcategory';
            $currencyFormat = $this->formatslist->formatCurrency(0);
            $currencyDecimel = strlen(substr(strrchr($currencyFormat, "."), 1));
            // echo "<pre>";print_r($arr);
            // echo sizeof($arr);
            if($arr!='') {
                foreach ($arr as $key => $aRow) {
                    $row = array();
                    $row[0] = '<a href="javascript:void(0)" onclick="selectitemname(&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICESELL.'&quot;)">'.$aRow->CATEGORYNAME.'</a>';
                    $row[1] = '<a href="javascript:void(0)" onclick="selectitemname(&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICESELL.'&quot;)">'.$aRow->CODE.'</a>';
                    $row[2] = '<a href="javascript:void(0)" onclick="selectitemname(&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICESELL.'&quot;)">'.$aRow->NAME.'</a>';
                    $row[3] = '<a href="javascript:void(0)" onclick="selectitemname(&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICESELL.'&quot;)">'.$this->formatslist->formatCurrencywithHash($aRow->PRICEBUY).'</a>';
                    $row[4] = '<a href="javascript:void(0)" onclick="selectitemname(&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICESELL.'&quot;)">'.$this->formatslist->formatCurrencywithHash($aRow->PRICESELL).'</a>';
                    $compinfdet    =   $this->companyinfo_model->getlocaleinfo();
                    $stockdet    =   $this->stock_model->getproductstock($aRow->ID,$compinfdet->LOCATION);
                    $row[5] = '<a href="javascript:void(0)" onclick="selectitemname(&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;)">'.$stockdet[0]["UNITS"].'</a>';
                    $output['aaData'][] = $row;
                    $j++;
                }
            } else {

            }
            // print_r($output);
           echo json_encode( $output );
        }
        
}
