<?php

use Mtc\Core\PaginationTemplate;
use Mtc\Core\Currency;
use Mtc\Shop\Brand;
use Mtc\Shop\Category;
use App\MetaDataFactory;
use MtcPharmacy\Multisite\Classes\MultisiteManager;


/**
 * @var ProductFilter $filter
 */
$name_collection = $filter->getNameCollection();


$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) {
    $selections = [];

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

                break;

            case "category":
                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,
                    'type' => 'category',
                ];

                break;

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

                break;

            case "custom":
                $selections[] = [
                    'url' => $filter->generateURL([
                        'custom_remove' => $selection['value'],
                        'custom_field' => $selection['custom_field']
                    ]),
                    'value' => $selection['value'],
                    'type' => 'custom',
                ];

                break;
        }
    }


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

    $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;
        } else {
            $brand['selected'] = false;
        }

        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 (!empty($filter->results['price']['min'])) {
    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;
    }
} else {
    $prices['start_price'] = $filter->price_min;
}

if (!empty($filter->results['price']['max'])) {
    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;
    }
} 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);

$price_data = $params;


/*
 * Templates
 */

$items = [];



if (count($filter->items) > 0) {
    foreach ($filter->items as $item_id) {
        $items[] = \Mtc\Shop\Item::find($item_id);
    }
}



//Add main category
$items = collect($items)->map(function ($item) {
    //Vue
    $item_eloquent = $item;
    $item->in_stock = (bool) $item_eloquent->in_stock;
    $item->from_price = (float) $item_eloquent->from_price;
    $item->image = $item_eloquent->getImagePath('small');

    if (empty($item->image)) {
        $item->images = [];
    }

    $item->basket_button_data = $item_eloquent->getProductCardData();
    $item->main_category = $item_eloquent->getMainCategory();

    if (config('subscription.enabled')) {
        $item->mapSizePricesToSubscriptions();
    }

    return $item;
});



$page_url_suffix = '';

if (isset($_REQUEST['price_min'])) {
    $page_url_suffix .= '&price_min=' . $_REQUEST['price_min'];
}

if (isset($_REQUEST['price_max'])) {
    $page_url_suffix .= '&price_max=' . $_REQUEST['price_max'];
}

$pagination = new PaginationTemplate([
    'item_count' => $filter->item_count,
    'per_page' => $filter->max_per_page,
    'active_page' => $filter->page,
    'link_class' => 'js_filterLink',
    'pages_to_display' => 2,
    'page_url' => $filter->generateURL([
        'ignore_page' => 1
    ]),
    'url_suffix' => $page_url_suffix
]);


$pagination_pages = [];

$pagination_begin = $pagination->active_page;

if ($pagination->active_page > ($pagination->total_pages - 2) && $pagination->total_pages > 2) {
    $pagination_begin = $pagination->start + 1;
}

for ($p = $pagination_begin; $p <= $pagination->end; $p++) {

    $pagination_pages[] =
        [
            'url' => $pagination->pageUrl($p),
            'active' => (int) $p === (int) $pagination->active_page,
            'number' => $p
        ];
}

$pagination_vue = (array) $pagination;
$pagination_vue['show_previous'] = $pagination->showPrevious();
$pagination_vue['show_next'] = $pagination->showNext();
$pagination_vue['next_page_url'] = false;
$pagination_vue['previous_page_url'] = false;

$pagination_vue['last_page'] = false;

if (($pagination->active_page < ($pagination->total_pages - 2)) && $pagination->total_pages > 3) {
    $pagination_vue['last_page'] = [
        'url' => $pagination->pageUrl($pagination->total_pages),
        'active' => (int) $pagination->total_pages
            === (int) $pagination->active_page,
        'number' => $pagination->total_pages
    ];
}

//Set next link
if (($pagination->active_page + 1) <= $pagination->total_pages) {
    $pagination_vue['next_page_url'] = $pagination->pageUrl($pagination->active_page + 1);
}

//Set previous link
if (($pagination->active_page - 1) >= 1) {
    $pagination_vue['previous_page_url'] = $pagination->pageUrl($pagination->active_page - 1);
}



$pagination_vue['pages'] = $pagination_pages;



$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;
    }
}



$sort['options'] = [];
$option_id_selected = 'default';

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

    if ($filter->getSortby() == $option_id) {
        $option_id_selected = $option_id;
    }

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

$sort['option_selected'] = $option_id_selected;


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

if (!empty($params['sort']['options'])) {
    $sort_options = $params['sort']['options'];
}

$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;


//Build breadcrumbs
$breadcrumbs_data = [];
$breadcrumbs_search_found = preg_match_all('/href="(?<link>.*?)\".*?title="(?<title>.*?)\"/im', $breadcrumbs_html, $breadcrumb_matches);

if (!empty($breadcrumb_matches['link']) && !empty($breadcrumb_matches['title'])) {

    foreach ($breadcrumb_matches['link'] as $key => $link) {

        $title = $breadcrumb_matches['title'][$key];

        if (!empty($title) && !empty($link)) {

            $crumb = [
                'url' => $link,
                'name' => $title
            ];
            $breadcrumbs_data[] = $crumb;
        }

    }

}




if (!isset($selections)) {
    $selections = [];
}


$title_content_html = '';
if (!empty($category_data)) {
    $title_content_html = $category_data['description'] ?? null;
} elseif (!empty($brand_data)) {
    $title_content_html = $brand_data['description'] ?? null;
}


$root_segment = reset($filter->selections_all);
if ($root_segment) {
    $obj = null;
    switch ($root_segment['type']) {
        case 'brand':
            $obj = Brand::find($root_segment['value']);
            break;
        case 'category':
            $obj = Category::find($root_segment['value']);
            break;
    }

    if ($obj) {
        $multisite_manager = new MultisiteManager($obj);
        $obj_to_display = $multisite_manager->getDisplayEntity();

        $meta_data = new MetaDataFactory($obj_to_display);
        if ($meta_data) {
            $page_meta['title'] = $meta_data->getMetaTitle($page_meta['title']);
            $page_meta['description'] = $meta_data->getMetaDescription($page_meta['description']);
        }
    }
}



// Resolve the single category ID for entity blocks (when browsing one category only)
$browse_category_id = null;
if ($only_categories && !empty($filter->selections['categories'])) {
    $browse_category_id = (int) end($filter->selections['categories']);
}

$vue_data = [
    'products' => $items,
    'filters' => [
        'selections' => $selections,
        'categories' => $cats,
        'price' => $price_data,
        'brands' => $brands,
        'sort' => $sort,
        'product_count' => $product_count,
    ],
    'page' => [
        'title' => trim(strip_tags($title_html)),
        'title_content' => $title_content_html,
        'breadcrumbs' => $breadcrumbs_data,
    ],
    'pagination' => $pagination_vue,
    'redirect' => false,
    'page_meta' => $page_meta,
    'browse_category_id' => $browse_category_id,
];


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



