<?php

function array_remove(&$array, $key, $default = null)
{
    $value = getVal($key, $array, $default);
    unset($array[$key]);

    return $value;
}

function smarty_function_admin_url($params, &$smarty)
{
    global $cfg;

    $adminUrl = trim($cfg['Path']['admin'], '/');

    $url = array_remove($params, 'url', $adminUrl.'/launch.php');

    if (array_remove($params, 'absolute')) {
        $url = $cfg['Addr']['full'].$url;
    } else {
        $url = $cfg['Addr']['rel'].$url;
    }

    $s = array_remove($params, 's');
    if (!$s) {
        $type = array_remove($params, 'type');
        if (empty($type)) {
            throw new InvalidArgumentException("Missing parameter 'type' in smarty function 'admin_url'!");
        }
        switch ($type) {
            case 'user':
            case 'users':
                $s = 'users';
                $email = array_remove($params, 'email');
                if ($email) {
                    $user = sqlFetchAssoc(sqlQueryBuilder()->select('id')
                        ->from('users')
                        ->where(\Query\Operator::equals(['email' => $email]))
                        ->execute());
                    if ($user) {
                        $params['ID'] = $user['id'];
                    }
                }
                break;

            case 'order':
            case 'orders':
                $s = 'orders';
                break;

            default:
                $s = $type;
        }
        if (empty($params['acn'])) {
            $params['acn'] = 'edit';
        }
    }

    $params = ['s' => "{$s}.php"] + $params;

    return $url.'?'.http_build_query($params);
}
