<?php
use Mtc\Core\PaginationTemplate;
use Mtc\Core\Currency;

/**
 * @var ProductFilter $filter
 */
$name_collection = $filter->getNameCollection();
$remove_icon = 'fal fa-times';

$property_types = []; //list of item property type IDs to be used in the filter

/*
 * Current Selections
 */

$selections_html = '';
if (!empty($filter->selections_all) || $filter->price_min || $filter->price_max) {
    $selection = [];

    foreach ($filter->selections_all as $selection) {
        switch ($selection['type']) {
            case "sale" :
                $selections[] = [
                    'url' => $filter->generateURL([
                            'sale_remove' => $selection['value']
                        ]),
                        'value' => 'Sale'
                    ];

                break;
            case "brand" :
                // Check if we can skip the query for brand name
                if (!empty($name_collection['brands'][$selection['value']])) {
                    $brand_name = $name_collection['brands'][$selection['value']];
                } else {
                    $brand_name = brand_name($selection['value']);
                }
                $selections[] = [
                    'url' => $filter->generateURL([
                        'brand_remove' => $selection['value']
                    ], $name_collection),
                    'value' => $brand_name,
                ];
                

                break;
            case "category" :
                // Check if we can skip the query for category name
                if (!empty($name_collection['categories'][$selection['value']])) {
                    $category_name = $name_collection['categories'][$selection['value']];
                } else {
                    $category_name = category_name($selection['value']);
                }
                $selections[] = [
                    'url' => $filter->generateURL([
                        'category_remove' => $selection['value']
                    ], $name_collection),
                    'value' => $category_name
                ];

                break;
            case "search" :
                $selections[] = [
                    'url' => $filter->generateURL([
                        'search_remove' => $selection['value']
                    ]),
                    'value' => $selection['value']
                ];

                break;
        }
    }

    $params = [
        'selections' => $selections,
        'remove_icon' => $remove_icon
    ];

    $selections_html = $twig->render('shop/browse/filter_sidebar_selections.twig', $params);
}


/*
 * Categories
 */

$cats = [];
$category_html = '';

if (!empty($filter->results['cats'])) {

    foreach ($filter->results['cats'] as $cat_id => $total) {

        $cat = [];
        $cat['id'] = $cat_id;

        if (in_array($cat_id, $filter->selections['categories'])) {
            $cat['selected'] = true;
        }

        if (in_array($cat_id, $filter->selections['categories'])) {
            $cat['url'] = $filter->generateURL([
                    'category_remove' => $cat_id
                ], $name_collection);
        } else {
            $cat['url'] = $filter->generateURL([
                    'category_add' => $cat_id
                ], $name_collection);
        }

        $cat['total'] = $total;

        $category = (new \Mtc\Shop\Category())->find($cat_id);
        if ($category->hide_pharmacy_items) {
            $twig->addGlobal('hide_pharmacy_items', true);
        }

        // fill with known values if possible
        if (!empty($name_collection['categories'][$cat_id])) {
            $cat['name'] = $name_collection['categories'][$cat_id];
        } else {
            $cat['name'] = $category->name;
        }

        $cats[] = $cat;
    }
    $params = [
        'cats' => $cats,
    ];

    $category_html = $twig->render('shop/browse/filter_sidebar_categories.twig', $params);

}

/*
 * Brands
 */

$brands = [];
$brands_html = '';
if (!empty($filter->results['brands'])) {

    foreach ($filter->results['brands'] as $brand_id => $total) {

        $brand = [];
        $brand['id'] = $brand_id;
        if (in_array($brand_id, $filter->selections['brands'])) {
            $brand['selected'] = true;
        }

        if (in_array($brand_id, $filter->selections['brands'])) {
            $brand['url'] = $filter->generateURL([
                'brand_remove' => $brand_id
            ]);
        } else {
            $brand['url'] = $filter->generateURL([
                'brand_add' => $brand_id
            ]);
        }

        // fill with known values if possible
        if (!empty($name_collection['brands'][$brand_id])) {
            $brand['name'] = $name_collection['brands'][$brand_id];
        } else {
            $brand['name'] = brand_name($brand_id);
        }

        $brand['total'] = $total;

        $brands[] = $brand;

    }
    $params = [
        'brands' => $brands
    ];
    $brands_html = $twig->render('shop/browse/filter_sidebar_brands.twig', $params);
}

/*
 * Price
 */

$currency_data = Currency::getCurrencyFromCode($_SESSION['selected_currency'] ?? null);

$prices = [];

$prices['price_min'] = (isset($query_values['price_min'])) ? $query_values['price_min'] : $filter->results['price']['min'] ?? 0;
$prices['price_max'] = (isset($query_values['price_max'])) ? $query_values['price_max'] : $filter->results['price']['max'] ?? 0;

$prices['result_price_min'] = $filter->results['price']['min'] ?? 0;
$prices['result_price_max'] = $filter->results['price']['max'] ?? 0;
$prices['current_url'] = $filter->generateURL([
    'price_min' => 0,
    'price_max' => 0
]);

if ($filter->price_min == '' || $filter->price_min  < $filter->results['price']['min'] * $currency_data['ratio']) {
    $prices['start_price'] = ($filter->results['price']['min'] ?? 0) * $currency_data['ratio'];
} else {
    $prices['start_price'] = $filter->price_min;
}

if ($filter->price_max == '' || $filter->price_max > $filter->results['price']['max'] * $currency_data['ratio']) {
    $prices['to_price'] = ($filter->results['price']['max'] ?? 0) * $currency_data['ratio'];
} else {
    $prices['to_price'] = $filter->price_max;
}

$params = [
    'currency_data' => $currency_data,
    'prices' => $prices
];

if (empty($query_values['price_max'])) {
    $params['prices']['price_max_foreign_currency'] = $params['prices']['price_max'] * $params['currency_data']['ratio'];
}

if (empty($query_values['price_min'])) {
    $params['prices']['price_min_foreign_currency'] = $params['prices']['price_min'] * $params['currency_data']['ratio'];
}

$price_html = $twig->render('shop/browse/filter_sidebar_prices.twig', $params);

/*
 * Templates
 */

$items = [];
if (count($filter->items) > 0) {
    foreach ($filter->items as $item_id) {
        $item = new Item();
        $item->loadItemSmall($item_id);
        $items[] = $item;


        if (count($item->sizes) > 0) {
            foreach ($item->sizes as $size) {
                // If sale price set, use that
                if ($size['sale_price'] > 0) {
                    $size_price = $size['sale_price'];
                } else {
                    $size_price = $size['price'];
                }
                // If the new price is lower, set that as item From price
                if (($size_price < $item->from_price || empty($item->from_price)) && $size_price > 0) {
                    $item->from_price = $size_price;
                    if ($size['sale_price'] > 0) {
                        // If we have a sale price, set the Item sale price and Percentage off
                        $item->sale_price = $size['sale_price'];
                        $item->price = $size['price'];
                        $item->percentage_off = round(($item->price - $item->sale_price) / $item->price * 100);
                    } else {
                        $item->sale_price = 0;
                        $item->price = $size['price'];
                    }
                }
            }
        } else {
            $item->from_price = $item->sale_price > 0 ? $item->sale_price : $item->price;
        }
        if (!empty($item->size_strengths)) {
            foreach ($item->size_strengths as $strength => $sizes) {
                foreach ($sizes as $k => $size) {
                    if (!empty($size['quantity'])) {
                        $item->has_quantities = true;
                    }
                }
            }
        }



    }

}

//Add main category
$items = collect($items)->map(function($item){


    $temp_item = new Item();
    $temp_item->Get_Item($item->id);

    $main_category = collect($temp_item->categories)
        ->reject(function ($category) {
            return strtolower($category['name']) == "doctor" || strtolower($category['name']) == "pharmacy" || strtolower($category['name']) == "general" || strtolower($category['name']) == "shop";
        })->first();

    if(!empty($main_category['name'])) {
        $item->main_category = $main_category['name'];
    }else{
        $item->main_category = '';
    }
    return $item;
});


$items_html = $twig->render('shop/browse/filter_items.twig', [
    'items' => $items
]);

$pagination = new PaginationTemplate([
    'item_count' => $filter->item_count,
    'per_page' => $filter->max_per_page,
    'active_page' => $filter->page,
    'link_class' => 'js_filterLink',
    'page_url' => $filter->generateURL([
        'ignore_page' => 1
    ])
]);
$pagenumber_html = $pagination->render($twig);

$sort_options = [
    'default' => 'Most Relevant',
    'best-selling' => 'Best Selling',
    'price-high-low' => 'Price High - Low',
    'price-low-high' => 'Price Low - High',
];

if (!empty($filter->selections['searches'])) {
    $sort_options['relevance'] = 'Order By Relevance';
}

$sort = [];

$only_categories = collect($filter->selections_all)
    ->where('type', '!=', 'category')
    ->count() == 0;

if ($only_categories) {
    $category_id = end($filter->selections['categories']);
    $category = \Mtc\Shop\Category::query()->find($category_id);
    if ($category) {
        $seoadmin->data['page_content'] = $category->description;
        $seoadmin->data['category_cautions'] = $category->cautions;
        $seoadmin->data['category_side_effects'] = $category->side_effects;
        $seoadmin->data['category_information_leaflet'] = $category->information_leafelet;
    }
}

if (isset($secondary)) {
    $sort['secondary'] = $secondary;
} else {
    $sort['secondary'] = null;
}

$sort['options'] = [];
$option_selected = false;

foreach ($sort_options as $option_id => $option_name) {
    $option = [];
    $option['url'] = $filter->generateURL(array('sortby' => $option_id));
    $option['name'] = $option_name;

    if ($filter->getSortby() == $option_id) {
        $option['selected'] = true;
        $option_selected = true;
    }

    $sort['options'][] = $option;
}

if(!$option_selected) {
    $sort['options'][0]['selected'] = true;
}

$params = [
    'sort' => $sort
];

$sort_html = $twig->render('shop/browse/filter_sort.twig', $params);

ob_start();
include __DIR__ . "/breadcrumbs.php";
$breadcrumbs_html = ob_get_clean();

ob_start();
include  __DIR__ . "/title.php";
$title_html = ob_get_clean();

$product_count = $filter->item_count;

