<?php

function pixelcms_articlesBuildRoute(&$query)
{
    $segments = array();
    if (isset($query['articleId'])) {
        $segments[] = is_array($query['articleId']) ? implode(',', $query['articleId']) : $query['articleId'] ;
        unset($query['articleId']);
    };
    unset($query['print_btn']);
    unset($query['price_style']);
    unset($query['tracktorpool_alias']);
    unset($query['view']);
    unset($query['model']);
    unset($query['page_size']);
    unset($query['disable_title_image']);
    unset($query['show_contact']);
    unset($query['decimals']);
    unset($query['show_gallery_desc']);
    return $segments;
}

function pixelcms_articlesParseRoute(&$segments)
{
    $vars = [];
    $app = JFactory::getApplication();
    $menu = $app->getMenu();
    $item = $menu->getActive();
    // Count segments
    $count = count($segments ?? []);
    // Handle View and Identifier
    $vars['view'] = $item->query['view'];
    $vars['model'] = $item->query['model'] ?? 'pixelcms_articles';

    // The last segment is always an article ID
    $vars['articleId'] = array_pop($segments);

    /**
     * In order for 404 pages to work we handle 2 things here
     *
     * 1. When there are segments left, we are in an invalid path.
     * 2. When layout single is used and an articleId gets passed in we are also in an invalid path.
     */
    if (!empty($segments) || ($item->query['layout'] === 'single' && !empty($vars['articleId']))) {
        // Raising an error here breaks joomla plugins... so we just set the articleId to an invalid one!
        $vars['articleId'] = -1;
    }

    return $vars;
}
