<?php


if(!function_exists("currency_main"))
{

	function currency_main($amount, $rate = 1, $hasDiscount = false, $discount = 0, $hasCoupon = false, $coupon = 0)
	{

		if($hasDiscount == true && $discount > 0){
			$amountDiscount = ($discount/100) * $amount;
			$amount = $amount - $amountDiscount;
		}

		if($hasCoupon == true && $coupon > 0){
			$amountCoupon = ($coupon/100) * $amount;
			$amount = $amount - $amountCoupon;
		}

		$amount = $amount * $rate;
		return floor($amount*100)/100;
	}

}


if(!function_exists("currency_main_symbol"))
{

	function currency_main_symbol($amount, $rate = 1, $hasDiscount = false, $discount = 0, $hasCoupon = false, $coupon = 0)
	{
		$CI = get_instance();
		$CI->load->model('settings_m');

		// Default currency is USD
		$default_currency = "USD";
		
		// Try to get currency symbol from database, fallback to $ if not found
		$currency = $CI->settings_m->getOneCurrency(array('currency' => $default_currency));
		$symbol = $currency ? $currency->symbol : '$';

		if($hasDiscount == true && $discount > 0){
			$amountDiscount = ($discount/100) * $amount;
			$amount = $amount - $amountDiscount;
		}

		if($hasCoupon == true && $coupon > 0){
			$amountCoupon = ($coupon/100) * $amount;
			$amount = $amount - $amountCoupon;
		}

		$amount = $amount * $rate;
		$formatted = number_format(floor($amount*100)/100, 2);
		
		return $symbol.$formatted;
	}

}

if(!function_exists("currency_coupon_main"))
{

	function currency_coupon_main($amount, $rate = 1, $coupon = 0)
	{

		if($coupon > 0){
			$amount = ($coupon/100) * $amount;
		}

    return floor($amount*100)/100;
	}

}

if(!function_exists("getVAT"))
{

	function getVAT($amount)
	{

		$CI =get_instance();
		$CI->load->model('settings_m');
		$CI->load->model('users_m');

		$vat = $CI->settings_m->getOne(array('s_key' => 'vat'))->s_value;

		if($amount > 0){
			$amount = ($vat * $amount);
		}

    return floor($amount*100)/100;
	}

}

if(!function_exists("getDeliveryType"))
{

	function getDeliveryType($country = "", $no_of_items = 0)
	{
		$CI = get_instance();
		$CI->load->model('settings_m');

		// Default delivery fee from settings
		$delivery_setting = $CI->settings_m->getOne(array('s_key' => 'delivery_fee'));
		$delivery_fee = $delivery_setting ? $delivery_setting->s_value : 0;
		$delivery_type = "standard_delivery";

		// Check for free shipping threshold
		$free_shipping = $CI->settings_m->getOne(array('s_key' => 'free_shipping_threshold'));
		if ($free_shipping && $free_shipping->s_value > 0) {
			// Free shipping logic can be applied at checkout based on cart total
		}

		return [
			"delivery_fee" => $delivery_fee,
			"delivery_type" => $delivery_type
		];

	}

}
?>
