<?php
/******************************************************************************/
//                                                                            //
//                             Smarty plugin                                  //
//                            @package Smarty                                 //
//							 @subpackage plugins                              //
//                        http://life-style.uz/                               //
//                   produced by Life Style, life-style.uz                    //
//                                                                            //
/******************************************************************************/

use Mnv\Core\Uploads\ImageSizes;
use Mnv\Core\Utilities\Cookie\Session;

function smarty_function_fetch_cart($params, &$smarty) {
	
	$assign               = fetch_getParam('assign', $params, 'carts');
	$cart_total_amount    = fetch_getParam('cart_total_amount', $params, 'total_amount');
	$cart_count_products  = fetch_getParam('cart_count_products', $params, 'count_products');
	
	if (empty($assign)) {
		$smarty->_trigger_fatal_error('fetch_cart: "assign" must not be empty');
		return;
	}

    $total = 0;
    $count = 0;
    $product_data = [];
    $stock_balance = 0;
    if ( Session::has('token_cart_id')) {
        if ($carts = connect()->table('shop_cart')->select('cartId, productId, options, quantity')->where('token', Session::get('token_cart_id'))->getAll('array')) {
            foreach ($carts as $cart) {
                $stock = true;

                $product_query = connect('products')->select('productId, sectionId, title, brand, url, price, old_price, quantity, special, shipping, subtract')->where('productId', $cart['productId'])->get('array');
                $product_query = prepareProduct($product_query);
//                $brand = connect('brands')->select('name')->where('fileName', $product_query['brand'])->getValue();

                $option_data = array();
                $option_price = 0;

                foreach (json_decode($cart['options'], true) as $product_option_id => $value) {
                    $option_query = connect('product_option')
                        ->join('options', 'optionId', '=', 'option_id')
                        ->select('product_option_id, product_id, option_id, value, name, type, orderBy')
                        ->where('product_option_id', $product_option_id)
                        ->where('product_id', $product_query['productId'])->get('array');

                    if ($option_query) {
                        foreach ($value as $product_option_value_id) {
                            $option_value_query = connect('product_option_value')
                                ->join('options', 'optionId', '=', 'option_value_id')
                                ->select('option_value_id, name, quantity, subtract, price, price_prefix')
                                ->where('product_option_value_id', $product_option_value_id)
                                ->where('product_option_id', $product_option_id)
                                ->get('array');
                            if ($option_value_query) {
                                if ($option_value_query['price_prefix'] == '+') {
                                    $option_price += $option_value_query['price'];
                                } elseif ($option_value_query['price_prefix'] == '-') {
                                    $option_price -= $option_value_query['price'];
                                }

                                if ($option_value_query['subtract'] && (!$option_value_query['quantity'] || ($option_value_query['quantity'] < $cart['quantity']))) {
                                    $stock = false;
                                }

                                if ($option_value_query['subtract'] && ($option_value_query['quantity'] != 0)) {
                                    $stock_balance = $option_value_query['quantity'];
                                }

                                $option_data[] = array(
                                    'product_option_id'         => $product_option_id,
                                    'product_option_value_id'   => $product_option_value_id,
                                    'option_id'                 => $option_query['option_id'],
                                    'option_value_id'           => $option_value_query['option_value_id'],
                                    'name'                      => $option_query['name'],
                                    'value'                     => $option_value_query['name'],
                                    'type'                      => $option_query['type'],
                                    'order'                     => $option_query['orderBy'],
                                    'quantity'                  => $option_value_query['quantity'],
                                    'subtract'                  => $option_value_query['subtract'],
                                    'price'                     => $option_value_query['price'],
                                );
                            }
                        }
                    };
                }

                $price = $product_query['price'];

//            print_r($stock_balance.PHP_EOL);
                if ($stock_balance == 0) {
                    if ($product_query['subtract'] && ($product_query['quantity'] != 0)) {
                        $stock_balance = $product_query['quantity'];
                    } else {
                        $stock_balance = 10;
                    }
                } else {
                    $stock_balance = 10;
                }

                if (!$product_query['quantity'] || ($product_query['quantity'] < $cart['quantity'])) {
                    $stock = false;
                }

//            print_r("======".PHP_EOL);
//            print_r($stock_balance.PHP_EOL);

                usort($option_data, 'sortBySortOptions');

                $product_data[] = array(
                    'cartId'        => $cart['cartId'],
                    'productId'     => $product_query['productId'],
                    'category'      => $product_query['section']['name'] ?? '',
                    'title'         => $product_query['title'],
                    'url'           => $product_query['url'],
                    'shipping'      => $product_query['shipping'],
                    'image'         => $product_query['image'],
                    'option'        => $option_data,
                    'quantity'      => $cart['quantity'],
                    'subtract'      => $product_query['subtract'],
                    'stock'         => $stock,
                    'stock_balance' => $stock_balance,
                    'old_price'     => ($product_query['old_price'] + $option_price),
                    'price'         => ($product_query['price'] + $option_price),
                    'total'         => ($product_query['price'] + $option_price) * $cart['quantity'],
//                    'brand' => $brand,


                );

                $total += (($price + $option_price) * $cart['quantity']);
                $count += $cart['quantity'];
            }
        }

//    print_r($total);

//	print_r($product_data);

    }

    $smarty->assign($assign, $product_data);
    $smarty->assign($cart_total_amount, $total);
    $smarty->assign($cart_count_products, $count);

}
function firstElement($params = array())
{
    if(!is_array($params)) {
        return false;
    }
    return reset($params);
}

function sortBySortOptions(&$a, &$b) {
    return ($a['order'] < $b['order']) ? -1 : 1;
}
?>