<?php

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

    class Pricecheck extends CI_Controller {

        function __construct() {

            parent::__construct();
                    $this->load->library('Formatslist');

            
        }

        function index()
        {
           
              $this->load->view('pricecheck_view');
        }

        public function searchcode() {

         

        if (isset($_GET['barcode'])) {
    $barcode = $_GET['barcode'];
        $sql = "SELECT * FROM PRODUCTS WHERE CODE LIKE '" . $barcode . "' ORDER BY NAME;";

        
        //return $this->getmenu($sql);
        //exit;

        $arr = $this->db->query($sql)->result();

        $data = array();
    
        if ($arr) {
            
                    echo json_encode(['name' => $arr[0]->NAME, 'price' => str_replace(',', '', number_format($this->calculatetax($arr[0]->ID),2))]);

            
        } else {
        // Item not found
        echo json_encode(['name' => 'Not found', 'price' => 'N/A']);
    }

   
    } else {
        // Item not found
        echo json_encode(['name' => 'Not found', 'price' => 'N/A']);
    }
        }
        
        public function calculatetax($pid){
        
        $sql = "SELECT PRICESELL, TAXCAT FROM PRODUCTS WHERE ID LIKE '" . $pid . "';";
        $arr = $this->db->query($sql)->result();
        
        $sql = "SELECT RATE, RATECASCADE, RATEORDER FROM TAXES WHERE CATEGORY LIKE '" . $arr[0]->TAXCAT . "' AND PARENTID IS NULL;";
         $arrtax = $this->db->query($sql)->result();
         $tax1 = 0;
        $tax2 = 0;
        $tax3=0;
        if($arr[0]->PRICESELL >0)
            {
        foreach($arrtax as $key => $aRow)
        {
            $rate = $aRow->RATE;
            if($rate != 0) {
                if($aRow->RATECASCADE == 0)
                {
                    $tax1 = $tax1 + ($arr[0]->PRICESELL * $rate);
                }
                else if($aRow->RATECASCADE != 0)
                {
                    $tax2 = ($tax1+$arr[0]->PRICESELL) * $rate;
                }
                    $tax3 = $tax1 + $tax2;
                
            }
            else {
                $tax3=0;
            }
        }
        return $this->formatslist->formatCurrencywithHash($arr[0]->PRICESELL+$tax3);
    }
 else {
        return $this->formatslist->formatCurrencywithHash(0);
    }
}

    }
