<?php
$path = '../../';
$exclude_header_inc['not_for_ajax'] = true;
$exclude_header_inc['cms'] = true;
$exclude_header_inc['cross_platform_controller'] = true;
require_once ($path . 'core/includes/header.inc.php');

/*
 * Since the full url is in the variable we need to
 * process the query string manually
 */

$url = filter_input(INPUT_POST, 'url') ?: '';
$query_string = '';
if ($url) {
    $url_parts = explode("?", $url);
    $query_string = $url_parts[1] ?? '';
}
parse_str($query_string, $query_values);

$default_query_values = [
    'page' => null,
    'sortby' => null,
    'ps' => null,
    'price_min' => null,
    'price_max' => null,
    'view_all' => null,
    'currency_ratio' => null,
];

$query_values += $default_query_values;


$filter = new ProductFilter(true);

$url = str_replace('nicocig-nicolites', 'browse/c-Smoking-Cessation-1755/c-Electronic-Cigarettes-1257/c-Nicolites-3445', $url);
$url = str_replace('flexiseq', 'browse/c-Pain-Relief-810/c-flexiseq-3449', $url);
$url = str_replace('vivid-liquids', 'browse/c-Smoking-Cessation-1755/c-Electronic-Cigarettes-1257/c-Vivid-3446', $url);

$filter->urlToSelections($url);

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

$filter->multi_categories = true;

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

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

if ($query_values['view_all']) {
    $filter->max_per_page = PHP_INT_MAX;
}

if (is_numeric($query_values['price_min'])) {
    $filter->price_min = round($query_values['price_min'], 2);
}

if (is_numeric($query_values['price_max'])) {
    $filter->price_max = round($query_values['price_max'], 2);
}

if (is_numeric($query_values['currency_ratio'])) {
    $filter->currency_ratio = $query_values['currency_ratio'] == 0 ? 1 : $query_values['currency_ratio'];
}

$filter_response = $filter->start();

$response = [];

if ($filter_response === true) {

    require_once __DIR__ . "/templates/ajax.include.php";

    $response['category_html'] = $category_html;

    $response['brands_html'] = $brands_html;

    $response['selections_html'] = $selections_html;

    $response['sizes_html'] = $sizes_html;

    $response['price_html'] = $price_html;

    $response['items_html'] = $items_html;

    $response['pagenumber_html'] = $pagenumber_html;

    $response['sort_html'] = $sort_html;

    $response['breadcrumbs_html'] = $breadcrumbs_html;

    $response['seo_title'] = $seoadmin->data['title'];

    $response['title_html'] = $title_html;

    $response['product_count'] = $product_count;

} else {
    $response['redirect'] = $filter_response;
}

exit(json_encode($response));
