<?php

function pixelcms_articlesBuildRoute(&$query)
{
    $segments = array();
    if (isset($query['articleId'])) {
        $segments[] = is_array($query['articleId']) ? implode(',', $query['articleId']) : $query['articleId'] ;
    };

    foreach ($query as $key => $value) {
        if (in_array(strtolower($key), [
            'option',
            'format',
            'itemid',
            'lang',
        ])) {
            continue;
        }

        unset($query[$key]);
    }

    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'];
    // Model Is only overridden for the products otherwise it's the same as view!
    $vars['model'] = $item->query['model'];

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