<?php

// check if any duplicates in url and redirect to correct url
$url = explode('/', rtrim($_SERVER['REQUEST_URI'],'/'));
if (array_unique($url) !== $url) {
    $_SERVER['REQUEST_URI'] = implode('/', array_unique($url)) . '/';
    header("HTTP/1.1 301 Moved Permanently");
    header('Location: ' . $_SERVER['REQUEST_URI']);
    exit;
}

// If a URL contains multiple consecutive dashes, redirect user to a cleaned version with single dashes.
$url_dirty = $_SERVER['REQUEST_URI'];
$pattern_multi_hyphen = "/-{2,}/";
$pattern_trailing_hyphen = "/-+$/";
$match_multiple_hyphens = preg_match_all($pattern_multi_hyphen, $url_dirty);
$match_trailing_hyphen = preg_match_all($pattern_trailing_hyphen, $url_dirty);
if ($match_multiple_hyphens > 0 || $match_trailing_hyphen > 0) {
    if ($match_multiple_hyphens > 0) {
        $url_clean = preg_replace($pattern_multi_hyphen, "-", $url_dirty);
    }
    if ($match_trailing_hyphen > 0) {
        $url_clean = preg_replace($pattern_trailing_hyphen, '', $url_dirty);
    }

    header("HTTP/1.1 301 Moved Permanently");
    header('Location: ' . $url_clean);
    exit;
}

$page = [];

/*
 * This controller can be called as part of the templating
 * previews found in /css and uses this code to load the
 * includes it needs for this.
 */
if (empty($css_templating)) {
    $path = "../../";
    require_once $path . 'core/includes/header.inc.php';
    //$twig_template_name = 'shop/browse/index.twig';
    $twig_template_name = 'shop/browse/index_vue.twig';
}



redirect_if_trailing_slash();

if (strpos($_SERVER['REQUEST_URI'], 'browse') === false && strpos($_SERVER['REDIRECT_URL'], 'browse')) {
    $_SERVER['REQUEST_URI'] = $_SERVER['REDIRECT_URL'];
}

$filter = new ProductFilter();

$filter->urlToSelections($_SERVER['REQUEST_URI']);

if (isset($_REQUEST['page']) && is_numeric($_REQUEST['page'])) {
    $filter->page = $_REQUEST['page'];
}

$filter->multi_categories = true;

if (!empty($_REQUEST['sortby'])) {
    $filter->setSortby($_REQUEST['sortby']);
}

if (isset($_REQUEST['ps']) && is_numeric($_REQUEST['ps'])) {
    $filter->max_per_page = $_REQUEST['ps'];
}


if (filter_input(INPUT_GET, 'view_all')) {
    $filter->max_per_page = PHP_INT_MAX;
    $page_meta['robots'] = 'noindex, nofollow';
}

if (isset($_REQUEST['price_min']) && is_numeric($_REQUEST['price_min'])) {
    $filter->price_min = (float) $_REQUEST['price_min'];
    $query_values['price_min'] = (float) $_REQUEST['price_min'];
}

if (isset($_REQUEST['price_max']) && is_numeric($_REQUEST['price_max'])) {
    $filter->price_max = (float) $_REQUEST['price_max'];
    $query_values['price_max'] = (float) $_REQUEST['price_max'];
}


$inaccessible_item = false;
if (!empty($_GET['inaccessible_item_id'])) { //redirected from deleted item
    $inaccessible_item = new Item($_GET['inaccessible_item_id']);
}

$filter->start();

//include $path . "shop/browse/templates/ajax.include.php";


include $path . "shop/browse/templates/ajax_vue.include.php";

if ($filter->nofollow
    || preg_match('#/cf-[^/]*#', $_SERVER['REQUEST_URI'])
    || isset($filter->price_min)
    || isset($filter->price_max)
) {
    $vue_data['page_meta']['robots'] = 'noindex, nofollow';
}

// If a child category is accessed directly (without parent in URL), set canonical to full parent+child path
if (!$filter->nofollow
    && count($filter->selections['categories']) === 1
    && is_array($seoadmin->data) && empty($seoadmin->data['canonical'])
) {
    $cat_id = $filter->selections['categories'][0];
    $parents = \Mtc\Shop\Category::allParents($cat_id);
    if (!empty($parents)) {
        $canonical = rtrim(browse_url($cat_id), '/');
        $seoadmin->data['canonical'] = $canonical;
        $twig->addGlobal('seo_tags', $seoadmin->data);
    }
}

$browse_title = trim(strip_tags($title_html));

if (empty($browse_title)) {
    $browse_title = 'Shop';
}

$breadcrumbs_search = preg_match_all('/href="(?<link>.*?)\".*?title="(?<title>.*?)\"/im', $breadcrumbs_html, $matches);

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

    $breadcrumbs_array = [];

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

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

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

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

    }

} else {
    $breadcrumbs_array = [];
}

//dd($vue_data);

if (empty($_REQUEST['ajax_request'])) {
    echo template($twig_template_name, $vue_data);
} else {
    header('Content-Type: application/json; charset=utf-8');
    exit(json_encode($vue_data));
}
