<?php
// Check for redirects
if (isset($_GET['make'])) {
    $redirect = false;
    $urlmake = get_term_by('id', $_GET['make'], 'models');
    $querystring = '?';
    foreach ($_GET as $k => $v) {
        if ($k != 'make' && $v) {
            $querystring .= $k . '=' . $v . '&';
        } else {
            $redirect = true;
        }
    }
    if ($querystring == '?') $querystring = '';
    if ($redirect && $urlmake) wp_redirect(get_site_url() . '/used-cars-for-sale/' . $urlmake->slug . '/' . $querystring);
}
$urlmake = get_query_var('make');
$urlmake = $urlmake ? get_term_by('slug', $urlmake, 'models') : null;

$PERPAGE = 25;

// Select sort field and order
$SORT_FIELD = isset($_COOKIE['sort-field']) && in_array($_COOKIE['sort-field'], ['date', 'price', 'km']) ? $_COOKIE['sort-field'] : 'date';
$SORT_ORDER = isset($_COOKIE['sort-order']) && in_array($_COOKIE['sort-order'], ['asc', 'desc']) ? $_COOKIE['sort-order'] : 'desc';
if (isset($_POST['sort'])) {
    $sort = explode('|', $_POST['sort']);
    if (in_array($sort[0], ['date', 'price', 'km']) && in_array($sort[1], ['asc', 'desc'])) {
        setcookie('sort-field', $sort[0], time() + YEAR_IN_SECONDS, '/');
        setcookie('sort-order', $sort[1], time() + YEAR_IN_SECONDS, '/');
        $SORT_FIELD = $sort[0];
        $SORT_ORDER = $sort[1];
    }
}

// Perform vehicle query
$args = [
    'post_type' => 'vehicles',
    'posts_per_page' => $PERPAGE,
    'paged' => max(1, (int) ($_GET['pag'] ?? 1)),
    'order' => $SORT_ORDER,
];

// Sort fields
if ($SORT_FIELD === 'price') {
    $args['orderby'] = 'meta_value_num';
    $args['meta_key'] = 'price';
} elseif ($SORT_FIELD === 'km') {
    $args['orderby'] = 'meta_value_num';
    $args['meta_key'] = 'kilometers';
} else {
    $args['orderby'] = 'date';
}

// Filters
$meta_query = [];
if (isset($_GET['model']) && $_GET['model']) {
    $meta_query[] = [
        'key' => 'model',
        'value' => $_GET['model'],
    ];
} elseif ($urlmake) {
    // Get all models under this make
    $models = [$urlmake->term_id];
    $terms = get_terms('models', ['hide_empty' => false, 'parent' => $urlmake->term_id]);
    foreach ($terms as $term) {
        $models[] = $term->term_id;
    }
    $meta_query[] = [
        'key' => 'model',
        'value' => $models,
    ];
}

foreach (['body', 'color', 'transmission', 'fueltype', 'status'] as $key) {
    if (isset($_GET[$key]) && $_GET[$key]) {
        $meta_query[] = [
            'key' => $key,
            'value' => $_GET[$key],
        ];
    }
}

foreach (['seats', 'doors'] as $key) {
    if (isset($_GET[$key]) && $_GET[$key]) {
        $compare = strstr($_GET[$key], '+') ? '>=' : '=';
        $meta_query[] = [
            'key' => $key,
            'value' => (int) $_GET[$key],
            'compare' => $compare,
        ];
    }
}

foreach (['km-from' => 'kilometers', 'km-to' => 'kilometers', 'year-from' => 'year', 'year-to' => 'year'] as $key => $meta_key) {
    if (isset($_GET[$key]) && $_GET[$key]) {
        $compare = strpos($key, '-from') !== false ? '>=' : '<=';
        $meta_query[] = [
            'key' => $meta_key,
            'value' => $_GET[$key],
            'compare' => $compare,
        ];
    }
}

if (isset($_GET['price']) && $_GET['price']) {
    $price = explode('-', $_GET['price']);
    $meta_query[] = [
        'key' => 'price',
        'value' => $price[0],
        'compare' => '>=',
        'type' => 'numeric',
    ];
    if ($price[1] !== '+') {
        $meta_query[] = [
            'key' => 'price',
            'value' => $price[1],
            'compare' => '<=',
            'type' => 'numeric',
        ];
    }
}

if ($meta_query) {
    $args['meta_query'] = $meta_query;
}

$Q = new WP_Query($args);

get_header();
?>
<?php get_template_part('search-bar'); ?>

<?php if ($Q->have_posts()) : ?>

<section class="inventory-section">
    <div class="search-navi">
        <div class="search-results">
            <h1>Showing <?= (($Q->query_vars['paged'] ?? 1) - 1) * $Q->query_vars['posts_per_page'] + 1; ?> to <?= min($Q->found_posts, ($Q->query_vars['paged'] ?? 1) * $Q->query_vars['posts_per_page']); ?> of <?= $Q->found_posts; ?> used cars for sale in Nova Scotia</h1>
        </div>
    </div>
    <ol class="vehicles-list">
        <?php while ($Q->have_posts()) : $Q->the_post(); ?>
            <li>
                <?php get_template_part('vehicles-list-item'); ?>
            </li>
        <?php endwhile; ?>
    </ol>
    <div class="pagination">
        <?= paginate_links([
            'format' => '?pag=%#%',
            'current' => max(1, (int) ($_GET['pag'] ?? 1)),
            'total' => $Q->max_num_pages,
            'prev_text' => 'Previous',
            'next_text' => 'Next',
        ]); ?>
    </div>
</section>

<?php else : ?>
    <div class="empty">
        <h1>No Vehicles Found</h1>
        <p>We didn't find anything matching your criteria. <a href=".">Try searching again.</a></p>
    </div>
<?php endif; ?>

<?php get_footer(); ?>
