<?php

namespace App\Lib;

use DB;
use Auth;

class Prices
{

    public $data = [];


    public function __construct()
    {
        $this->setAttributes();
    }

    public function __set($index, $value){

        $this->data[$index] = $value;

    }


    public function __get($index){

        return $this->data[$index];

    }



    private function setAttributes(){

        $data = DB::table('config')->where('id', '=' ,1)->select('exrate','reg_disc','sale_status','sale_discount','sale_pricelim')->first();

        foreach($data as $key => $val){
            $this->{$key} = $val;
        }

        $this->ifUser  = (Auth::guard('web')->check()) ? 1 : 0;
        $this->ifAdmin = (Auth::guard('admin')->check()) ? 1 : 0;
        $this->ifSale  = ($this->sale_status) ? 1 : 0;
        $udisc         = (auth()->user()) ? auth()->user()->discount() : 0;
        $this->udisc   = (100-$udisc)/100;

        $this->currency = session('currency');

    }


    public static function formatPrice($price, $rsd = false){
        return number_format($price,2,',', '.').' '.((session('currency') == 'RSD' || $rsd) ? '' : '$');
    }


    public function getPrice($product, $rsd = false){

        // Odredjivanje korisnickog popusta

        if($this->ifUser && $this->udisc > 0){// Ako je korisnik ulogovan i ima popust
            $userDiscount = (100-$this->udisc)/100;
        } elseif ($this->ifUser) {// Ako je korisnik ulogovan a nema popust - COALESCE( c.`cat_reg_disc` , cf.`reg_disc` , 0 ) AS `regdisc`
            $userDiscount = (100-$product->regdisc)/100;
        } else {// Ako korisnik nije ulogovan
            $userDiscount = 1;
        }

        $vatRate = (100+$product->cat_vat)/100;
        $saleDiscount = ($this->sale_status && $product->prod_ifsale  && $product->prod_price >= $this->sale_pricelim) ? (100-$product->saledisc)/100 : 1;

        $price = $product->prod_price*$vatRate*$userDiscount*$saleDiscount;

        $price = ($this->currency == 'RSD' || $rsd) ? $price*$this->exrate : $price;

        //echo $product->prod_price.' '.$vatRate.' '.$price; exit;
        return $price;
    }

    public function getOldPrice($product, $rsd = false){

        $vatRate = (100+$product->cat_vat)/100;
        if(is_numeric($product->prod_oldprice)){
            $oldPrice = $product->prod_oldprice;
        } else if ($this->ifUser || $this->ifSale) {
            $oldPrice = $product->prod_price*$vatRate;
        } else {
            $oldPrice = 0;
        }

        $oldPrice = ($this->currency == 'RSD' || $rsd) ? $oldPrice*$this->exrate : $oldPrice;

        return $oldPrice;
    }

}