<?php

namespace Velis\Mvc\Controller;

trait ListPresentationHelpersTrait
{
    /**
     * Shortcut function for retrieving page number from filter
     * @param string $pageVarName
     * @return int
     */
    public function page(string $pageVarName = 'page'): int
    {
        return $this->params->getInt($pageVarName)
            ? $this->params->getInt($pageVarName)
            : 1;
    }

    /**
     * Function for retrieving order field from params
     * eg. ?sort=name:asc|last_name|date:desc|priority,status:asc
     * @param array<string, string> $overrides
     */
    public function order(string $default = '', array $overrides = []): string
    {
        $sortParam = trim($this->params['sort']);

        $sortArray = explode('|', $sortParam);
        $parts = [];

        if (!strlen($sortParam)) {
            return $default;
        }

        foreach ($sortArray as $sortElement) {
            $splitted = explode(':', $sortElement);
            $fields = $splitted[0];
            $order = $splitted[1];

            // Split fields by comma, but not by comma in brackets
            // required for handling db functions as sort parameters
            $fieldsArray = preg_split('/,(?![^\(]*\))/', $fields);

            foreach ($fieldsArray as $field) {
                if (array_key_exists($field, $overrides)) {
                    $field = $overrides[$field];
                }
                if ($field && !$order) {
                    $parts[] = $field;
                } elseif ($field && $order && (strtolower($order) == 'asc' || strtolower($order) == 'desc')) {
                    $parts[] = $field . ' ' . strtoupper($order);
                }
            }
        }

        return implode(', ', $parts);
    }
}
