<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Tariff extends MY_Controller {
    function __construct() {
        parent::__construct();
        $this->load->model('inventory/tariff_model');
        $this->load->library('Formatslist');
    }
    //TARIFF
    public function index() {
        $data['product'] = $this->common->getAll('PRODUCTS');
        $data['template'] = 'inventory/tariff_ovw';
        $this->load->view('template',$data);
    }
    function gettariffautocomplete() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('inventory/tariff_model');
        $rows = $this->tariff_model->gettariffautocomplete($term);
        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, $row->NAME);
        echo json_encode($keywords);
    }
    //GET TARIFF
    function gettariff() {
        $data['data'] = $this->common->getAll('TARIFFAREAS');
        echo json_encode($data);
    }
    //ADD  TARIFF
    public function addtariff() {
       $id = $this->input->post('id');
       if($id == '') { 
            $data = array(   
                'NAME' => $this->input->post('NAME')
            );
            $existdata = $this->common->existdata('TARIFFAREAS',$data);
            if(!empty($existdata)) {
                $this->session->set_flashdata('success_msg', 'The record is already exist');
            } else {
                $data['ID']             = uniqid();
                $data['TARIFFORDER']    =   ($this->input->post('TARIFFORDER')=='' ? 0 : $this->input->post('TARIFFORDER'));
                $this->common->insert('TARIFFAREAS',$data);
                $this->session->set_flashdata('success_msg', 'The record is added successfuly.');
           }
       } else {   
       	    $data = array(   
                'NAME' => $this->input->post('NAME')
            );
            $existdata = $this->common->existdata('TARIFFAREAS',$data);
            if(!empty($existdata)) {
                $this->session->set_flashdata('success_msg', 'The record is already exist');
            } else {
                $data['TARIFFORDER']    =   ($this->input->post('TARIFFORDER')=='' ? 0 : $this->input->post('TARIFFORDER'));
                $where = array('ID' => $id);
                $this->common->update('TARIFFAREAS',$where,$data);
                $this->session->set_flashdata('success_msg', 'The record has been updated successfuly.');
            }
       }
       redirect('inventory/tariff');  
    }
    //EDIT TARIFF
    public function edittariff($id) {
         $sql = "SELECT * FROM TARIFFAREAS WHERE ID='".$id."'";
         $data = $this->common->customquery($sql);
         echo json_encode($data);
    }
    //DELETE TARIFF
    public function deletetariff($id) {
        $where = array('ID' => $id);  
        $this->common->delete('TARIFFAREAS',$where);
        $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
        redirect('inventory/tariff');
    }
    function record() {   
        $oper = $this->input->post('oper');
        $id = uniqid();
        $lineid = md5(time());
        $plist = unserialize($this->input->post('lineitems'));
        $this->load->model('partner/customers_model');
        if($oper=='del') {
            $id = $this->input->post('id');
            if($id) {
                $this->customers_model->delete($id);
                $fdata = array('msgt' => 'S', 'msg' => 'Product deleted successfully.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'partner/customers');
            } else {
                $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete product.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'partner/customers');
            }
        } else {
            $form_data = array(
                'TARIFFID' => $lineid,
                'PRODUCTID' => $this->_getPIDbN($line['product']),
                'PRICESELL' => $line['price'] 
            );
            var_dump($form_data);
            if($oper=='add') {
                if ($this->customers_model->add($form_data) == TRUE) {
                    $fdata = array('msgt' => 'S', 'msg' => 'Product added successfully.');
                    $this->session->set_flashdata($fdata);
                    return true;
                }
            } else if($oper=='edit') {
                $id = $this->input->post('ID');
                if($id) {
                    $this->customers_model->update($id, $form_data);   
                }
            }
        }
    }
    
    function addtariffproducts($tid='') {
        if($tid) {
            $where = array('ID=' => $tid);
            $data['tariffname'] = $this->common->getWhere('TARIFFAREAS',$where);
            $data["tariffid"]     =   $tid;
            $where = array('ID!=' => -1);
            $data['categories'] = $this->common->getWhere('CATEGORIES',$where);
            $data['template'] = 'inventory/tariff_add_ovw';
            $this->load->view('template',$data);
        } else {
            redirect('inventory/tariff');  
        }
    }
    
    
    public function GetproductList() {
        $ownerid=$this->session->userid;
        $columns = array( 
            0=> 'NAME',
            1=> 'ID'
        );
        $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(!empty($this->input->post('searchtext'))){
            $search_array['searchtext'] = $this->input->post('searchtext');
        }
        if(!empty($this->input->post('searchcategory'))){
            $search_array['searchcategory'] = $this->input->post('searchcategory');
        }
        if(!empty($this->input->post('tariffid'))){
            $search_array['tariffid'] = $this->input->post('tariffid');
        }
        if(count($search_array)==0) {
            $totalData = $this->tariff_model->all_products_count();
            $totalFiltered = $totalData[0]->total;
            $productslist = $this->tariff_model->all_products($limit,$start,$order,$dir, $ownerid,$this->input->post('tariffid'));
            if($totalData[0]->total>0) {
                $totcount   =   $totalData[0]->total;
            } else {
                $totcount   =   0;
            }
        } else {
            $productslist =  $this->tariff_model->products_search($limit,$start,$search_array,$dir,$ownerid,$order);
            $totalFiltered = $this->tariff_model->products_search_count($search_array,$ownerid);
            if($totalFiltered>0) {
                $totcount   =   $totalFiltered;
            } else {
                $totcount   =   0;
            }
        }
        
        $data = array();
        if(!empty($productslist)) {
            $account_id = 0;
            $j = 1;
            foreach ($productslist as $row){
                $nestedData['NAME']         =   $row->NAME;
                $nestedData['PRICESELL']    =   $this->formatslist->formatCurrency($row->PRICESELL);
                $nestedData['PRICESELLTAX']    =   $this->formatslist->formatCurrency($row->PRICESELL*(1+$row->TAXRATE));
                $nestedData['TAXRATE']    =   $this->formatslist->formatCurrency($row->TAXRATE);
                $nestedData['TARIFFPRICE']    =   $this->formatslist->formatCurrency(($row->TARIFFPRICE === NULL ? '' : $row->TARIFFPRICE));
                $nestedData['ID']           =   $row->ID;
                $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);
    }

    function managetariffproduct() {
        $where  =   "PRODUCTID='".$this->input->post("prid")."' AND TARIFFID='".$this->input->post("tariffid")."'";
        $this->common->delete('TARIFFAREAS_PROD',$where);
        $datainsert["PRODUCTID"]    =   $this->input->post("prid");
        $datainsert["TARIFFID"]     =   $this->input->post("tariffid");
        $datainsert["PRICESELL"]    =   ($this->input->post("amount")*100)/(100+(100*$this->input->post("taxrate")));
        if($this->input->post("amount")!='')
            $this->common->insert('TARIFFAREAS_PROD',$datainsert);
        $json_data = array(
            "msg"  => 'Success',
            "prid" => $this->input->post("prid")
        );
        echo json_encode($json_data);
    }
    
    function updateallproductstariffprices() {
        $percentagevar  =   substr_count($this->input->post("commontxtval"),"%");
        $plusvar        =   substr_count($this->input->post("commontxtval"),"+");
        $minusvar       =   substr_count($this->input->post("commontxtval"),"-");
        $Rvalue         =   str_replace("%","",$this->input->post("commontxtval"));
        $Rvalue         =   str_replace("+","",$Rvalue);
        $Rvalue         =   str_replace("-","",$Rvalue);
        if($Rvalue) {
            if($percentagevar==1) {
                if($plusvar==0 && $minusvar==0) {
                    $wherecond  =   "(((PRODUCTS.PRICESELL*(A.MAXRATE+1))*".$Rvalue."/100)+(PRODUCTS.PRICESELL*(A.MAXRATE+1)))";
                } else if($plusvar==1) {
                    $wherecond  =   "(((PRODUCTS.PRICESELL*(A.MAXRATE+1))*".$Rvalue."/100)+(PRODUCTS.PRICESELL*(A.MAXRATE+1)))";
                }  else if($minusvar==1) {
                    $wherecond  =   "((PRODUCTS.PRICESELL*(A.MAXRATE+1))-((PRODUCTS.PRICESELL*(A.MAXRATE+1))*".$Rvalue."/100))";
                }
            } else if($percentagevar==0) {
                if($plusvar==0 && $minusvar==0) {
                    $wherecond  =   "(".$Rvalue."+(PRODUCTS.PRICESELL*(A.MAXRATE+1)))";
                } else if($plusvar==1) {
                    $wherecond  =   "(".$Rvalue."+(PRODUCTS.PRICESELL*(A.MAXRATE+1)))";
                }  else if($minusvar==1) {
                    $wherecond  =   "((PRODUCTS.PRICESELL*(A.MAXRATE+1))-".$Rvalue.")";
                }
            }
            $sql    =   "SELECT PRODUCTS.ID,".$wherecond." AS TARIFFPRICE FROM PRODUCTS LEFT JOIN TAXCATEGORIES ON PRODUCTS.TAXCAT=TAXCATEGORIES.ID"
                    . " LEFT JOIN (SELECT MAX(RATE) AS MAXRATE,CATEGORY FROM TAXES GROUP BY CATEGORY) A ON TAXCATEGORIES.ID=A.CATEGORY";
            $sqlwhere = ' WHERE 1';
            if($this->input->post("searchval")){
                $sqlwhere .= ' and (NAME like "%'.$this->input->post("searchval").'%" || PRICESELL like "%'.$this->input->post("searchval").'%"'
                    . ' || CODE like "%'.$this->input->post("searchval").'%")';
            }
            if($this->input->post("searchcategory")){
                $sqlwhere .= ' and CATEGORY="'.$this->input->post("searchcategory").'"';
            }
            $sql=$sql.$sqlwhere;
            
            $query = $this->db->query($sql);
            $Arrrec =   $query->result(); 
            if($Arrrec) {
                foreach($Arrrec as $ArrrecVal) {
                    $where  =   "PRODUCTID='".$ArrrecVal->ID."' AND TARIFFID='".$this->input->post("tariffid")."'";
                    $this->common->delete('TARIFFAREAS_PROD',$where);
                    $datainsert["PRODUCTID"]   =   $ArrrecVal->ID;
                    $datainsert["TARIFFID"]   =   $this->input->post("tariffid");
                    $datainsert["PRICESELL"]   =   $ArrrecVal->TARIFFPRICE;
                    if($ArrrecVal->TARIFFPRICE!='')
                        $this->common->insert('TARIFFAREAS_PROD',$datainsert);
                } 
            }
        }
        $json_data = array(
            "msg"            => 'Success'
        );
        echo json_encode($json_data);
    }
}