<?php

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

class Taxes extends MY_Controller {

    function __construct() {
        parent::__construct();
          $this->load->model('settings/taxes_model');
    }
    public function index() {
         $data['tax_cat'] = $this->common->getAll('TAXCATEGORIES');
         $data['taxcustcat'] = $this->common->getAll('TAXCUSTCATEGORIES');
         $data['parenttaxlist'] = $this->common->getAll('TAXES');
         $data['template'] = 'settings/taxes_ovw';
         $this->load->view('template',$data);
    }

    //GET TAXES
    public function gettax() {
        $data['data'] = $this->taxes_model->gettax();
        echo json_encode($data);
    }
    
    public function addtax() {
        $id = $this->input->post('id');
        $custcategory    =   !empty($this->input->post('custcategory'))?$this->input->post('custcategory'):NULL;
        $parentcat    =   !empty($this->input->post('PARENTID'))?$this->input->post('PARENTID'):NULL;
        if($this->input->post('ratecascade')==1) $ratecascade=1; else $ratecascade=0;
        $ratetax = explode("%",$this->input->post('rate'));
        if(count($ratetax)==1) 
            $ratetax = $this->input->post('rate');
        else 
            $ratetax = $ratetax[0];
        
        if($id == '') {
            $data = array(   
                'ID' => uniqid(), 
                'NAME' => $this->input->post('name'),
                'CATEGORY' => $this->input->post('category'),
                'CUSTCATEGORY' => $custcategory,
                'RATE' => ($ratetax/100),
                'RATECASCADE' => $ratecascade,
                'RATEORDER' => $this->input->post('rateorder'),
                'PARENTID' => $parentcat,
            );
            $existdata = $this->common->existdata('TAXES',$data);
            // print_r( $existdata);die();
            if(!empty($existdata)){
              $this->session->set_flashdata('success_msg', 'The record is already exist');
            }else{
                 $this->common->insert('TAXES',$data);
                 $this->session->set_flashdata('success_msg', 'The record is added successfuly.');
            }
        } else {
            $data = array(
            'NAME' => $this->input->post('name'),
            'CATEGORY' => $this->input->post('category'),
            'CUSTCATEGORY' => $custcategory,
            'RATE' => ($ratetax/100),
            'RATECASCADE' => $ratecascade,
            'RATEORDER' => $this->input->post('rateorder'),
                'PARENTID' => $parentcat,
        );
          $where = array('ID' => $id);
          $this->session->set_flashdata('success_msg', 'The record has been updated successfuly.');
          $this->common->update('TAXES',$where,$data);
        }
        redirect('settings/taxes');
    }
    
      public function edittax($id) {
        $where = array('ID' => $id,);
        $data = $this->common->getWhere('TAXES',$where);
        $data[0]->RATE =   $data[0]->RATE*100;
        echo json_encode($data);
 
    }

      function deletetaxes($id)
    { 
         $where = array('ID' => $id);  
        $this->common->delete('TAXES',$where);
        $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
        redirect('settings/taxes');
    }

    //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 TAXCATEGORY AUTOCOMPLETE
    function gettaxcategoryautocomplete() {
          $term = $this->input->post('term', TRUE);
            $this->load->model('settings/taxes_model');
            $rows = $this->taxes_model->gettaxcategoryautocomplete($term);
            $keywords = array();
            foreach ($rows as $row)
            array_push($keywords, array(
                'label' => $row->NAME,
                'value' => $row->ID
            ));

            echo json_encode($keywords);
    }
    
    //GET CUSTOMER CATEGORY LIST
    private function _getCustCategories($id = NULL) {
        $this->load->model('inventory/products_model');
        $catarr = $this->products_model->getcustcategories();
        $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 TAXES LIST
    private function _getParentTax($id = NULL) {
        $this->load->model('products_model');
        $catarr = $this->products_model->getparenttax();
        $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;
    }

    //TAX CATEGORIES
    public function taxcats() {
        
          $data['template'] = 'settings/taxcats_ovw';
         $this->load->view('template',$data);
    }

    //GET TAX CATEGORIES
    public function gettaxcats() {
        $data['data'] = $this->common->getAll('TAXCATEGORIES');
        echo json_encode($data);
    }
    
   
       public function addtaxcats() {
        $id = $this->input->post('id');
        $data = array( 
            'NAME' => $this->input->post('name')
        );
       if($id == '')
       { 
           $data['ID']=uniqid();
          $existdata = $this->common->existdata('TAXCATEGORIES',$data);
          // print_r( $existdata);die();
           if(!empty($existdata))
           {
           
             $this->session->set_flashdata('success_msg', 'The record is already exist');
           }
           else
           {

              $this->common->insert('TAXCATEGORIES',$data);
              $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('TAXCATEGORIES',$where,$data);
       }
        redirect('settings/taxes/taxcats');
 
    }
    
      public function edittaxcats($id) {
        $where = array('ID' => $id,);
        $data = $this->common->getWhere('TAXCATEGORIES',$where);

        echo json_encode($data);
 
    }
       public function deletetaxcats($id) {

        $where = array('ID' => $id);  
        $this->common->delete('TAXCATEGORIES',$where);
        $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
        redirect('settings/taxes/taxcats');
 
    }

     private function getcat($name) {
        $this->load->model('settings/taxes_model');
        return $this->taxes_model->getcat($name);
    }
    private function getcustcat($name) {
        $this->load->model('partner/suppliers_model');
        return $this->suppliers_model->getcustcat($name);
    }
     
    //GET CUST CATEGORY AUTOCOMPLETE
    function getcustcatautocomplete() {
            $term = $this->input->post('term', TRUE);
            $this->load->model('partner/customers_model');
            $rows = $this->customers_model->getcustcatautocomplete($term);
            $keywords = array();
            foreach ($rows as $row)
            array_push($keywords, array(
                'label' => $row->NAME,
                'value' => $row->ID
            ));

            echo json_encode($keywords);
    } 
    //TAXES AUTOCOMPLETE
    function gettaxocomplete(){
            $term = $this->input->post('term',TRUE);
            $this->load->model('settings/taxes_model');
            $rows = $this->taxes_model->gettaxocomplete($term);
            $keywords = array();
            foreach ($rows as $row)
                array_push($keywords, $row->NAME);
            echo json_encode($keywords);
     }
     
    //TAXCATEGORY AUTOCOMPLETE
    function taxcategoriesautocomplete() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('settings/taxes_model');
        $rows = $this->taxes_model->taxcategoriesautocomplete($term);
        
        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, $row->NAME);
        echo json_encode($keywords);
    }
      //GET CUST CATEGORY AUTOCOMPLETE
    function getcategoriesautocomplete() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('partner/customers_model');
        $rows = $this->customers_model->getcategoriesautocomplete($term);
        $keywords = array();
        foreach ($rows as $row)
        array_push($keywords, $row->TAXCATEGORY);
        echo json_encode($keywords);
    }
  
    //  ADD-EDIT-DELETE TAXCATEGORIES  
    function taxcat()
    {      
            $oper = $this->input->post('oper');
            $this->load->model('settings/taxes_model');
           /* if($oper=='del')
            {
                $id = $this->input->post('id');
                if($id)
                {
                    $this->taxes_model->delete($id);
                    $fdata = array('msgt' => 'S', 'msg' => 'Unit deleted successfully.');
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'settings/taxes/taxcat');
                }
                else 
                {
                $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete Unit.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'settings/taxes/taxcat');
                }
            }*/
             $this->load->library('form_validation');
       $this->form_validation->set_rules('NAME', 'NAME', 'trim|required');
                

            if ($this->form_validation->run() == true) {
                $form_data =  array(
                                'NAME' => $this->input->post('NAME')
                             );
                if($oper=='add')
                {
                    array_push($form_data, 'ID', uniqid());
                    if ($this->taxes_model->add($form_data) == TRUE) {
                            $fdata = array('msgt' => 'S', 'msg' => 'Unit added successfully.');
                            $this->session->set_flashdata($fdata);
                            return true;
                    }
                }
                elseif($oper=='edit')
                {
                    $id = $this->input->post('ID');
                    if($id)
                    {
                            $this->taxes_model->update($id, $form_data);   
                    }       
                }
             }
       }
     
     // ADD-EDIT-DELETE TAXES  
    function record()
    {      
            $oper = $this->input->post('oper');
            $id = uniqid();
            $rate = $this->input->post('RATE');
            $rateinp = ($rate/100);
           
                           
            $this->load->model('settings/taxes_model');
           /* if($oper=='del')
            {
                $id = $this->input->post('id');
                if($id)
                {
                    $this->taxes_model->deletetax($id);
                    $fdata = array('msgt' => 'S', 'msg' => 'Tax deleted successfully.');
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'settings/taxes/taxcat');
                }
                else 
                {
                $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete Tax.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'settings/taxes/taxcat');
                }
            }
            else
            {*/
                $form_data =  array(
                                'ID' => $id,
                                'NAME' => $this->input->post('NAME'),
                                'CATEGORY' =>  $this->input->post('CATID'),
                                'CUSTCATEGORY' => $this->input->post('CUSTCATID'),
                                'PARENTID' => ($this->input->post('PARENTID')),
                                'RATE' => ($rateinp) ? $rateinp : 0,
                                'RATEORDER' => ($this->input->post('RATEORDER')) ? $this->input->post('RATEORDER') : 0,
                                'RATECASCADE' => ($this->input->post('RATECASCADE')) ? 1 : 0,
                                'PARENTID' => ($this->input->post('PARENTID')) ? $this->input->post('PARENTID') : NULL
                            );
                var_dump($form_data);
               
                if($oper=='add')
                {
                    if ($this->taxes_model->addtax($form_data) == TRUE) {
                            $fdata = array('msgt' => 'S', 'msg' => 'Unit added successfully.');
                            $this->session->set_flashdata($fdata);
                            return true;
                    }
                }
                elseif($oper=='edit')
                {
                    $id = $this->input->post('id');
                    if($id)
                    {
                            $this->taxes_model->updatetax($id, $form_data);   
                    }       
                }
             
     }
  function deletetaxcat()
    {
        $this->load->model('settings/taxes_model');
        if ($this->uri->segment(4))
        {
            if($this->taxes_model->delete($this->uri->segment(4))==true){
            $fdata = array('msgt' => 'S', 'msg' => 'Tax category deleted successfully.');
            $this->session->set_flashdata($fdata);
            redirect(site_url() . 'settings/taxes/taxcats');
        } 
        else{
            $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete Tax category.');
            $this->session->set_flashdata($fdata);
            redirect(site_url() . 'settings/taxes/taxcats');
        }
    } }
  
    function addt(){
        
        $this->load->model('settings/taxes_model');
        if ($this->uri->segment(4))
        {
            $this->taxes_model->delete($this->uri->segment(4));
            $fdata = array('msgt' => 'S', 'msg' => 'Tax category deleted successfully.');
            $this->session->set_flashdata($fdata);
            redirect(site_url() . 'settings/taxes/taxcats');
        } 
        else{
            $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete Tax category.');
            $this->session->set_flashdata($fdata);
            redirect(site_url() . 'settings/taxes/taxcats');
        }
    }

    public function taxCalcultion() {
        if($_POST['tax_id']){
            $sql =  "select max(RATE) as MAXRATE from TAXES where CATEGORY='".$_POST['tax_id']."'";
            $data = $this->common->customquery($sql);
            $taxRate = $data[0]->MAXRATE;
            if($data[0]->MAXRATE=='')
                echo 'false';
            else
                echo json_encode($data);
        } else {
            echo 'false';
        }
    }
}
