<?php

/**
 * @package Dotclear
 * @subpackage Core
 *
 * @copyright Olivier Meunier & Association Dotclear
 * @copyright AGPL-3.0
 */
declare(strict_types=1);

namespace Dotclear\Schema\Extension;

use Dotclear\App;
use Dotclear\Database\MetaRecord;
use Dotclear\Interface\Core\AuthInterface;

/**
 * @brief Dotclear dates Record helpers.
 *
 * This class adds new methods to database dates results.
 * You can call them on every record comming from Auth::checkUser and
 * Users::getUsers.
 *
 * @warning You should not give the first argument (usualy $rs) of every described
 * function.
 */
class User
{
    /**
     * Returns a user option.
     *
     * @param      MetaRecord   $rs         Invisible parameter
     * @param      string       $name       The name of option
     *
     * @return     mixed
     */
    public static function option(MetaRecord $rs, string $name)
    {
        $options = self::options($rs);

        return $options[$name] ?? null;
    }

    /**
     * Returns all user options.
     *
     * @param      MetaRecord   $rs       Invisible parameter
     *
     * @return     array<array-key, mixed>
     *
     * @deprecated 2.40 it's recommended to use user preferences rather than this field
     */
    public static function options(MetaRecord $rs): array
    {
        $user_options = $rs->strField('user_options');
        if ($user_options !== '') {
            $options = @unserialize($user_options);
            if (is_array($options)) {
                return $options;
            }
        }

        return [];
    }

    /**
     * Returns admin status of the current user
     *
     * @param      MetaRecord   $rs       Invisible parameter
     */
    public static function admin(MetaRecord $rs): string
    {
        if ($rs->boolField('user_super')) {
            return AuthInterface::PERMISSION_SUPERADMIN;
        }

        $user_id = $rs->strField('user_id');
        if ($user_id !== '') {
            $permissions = App::users()->getUserPermissions($user_id);
            if (isset($permissions[App::blog()->id()]['p'][AuthInterface::PERMISSION_ADMIN])) {
                return AuthInterface::PERMISSION_ADMIN;
            }
        }

        return '';
    }

    /**
     * Converts this Record to a Dotclear\Database\StaticRecord instance.
     *
     * @param      MetaRecord   $rs       Invisible parameter
     *
     * @deprecated since 2.39 use MetaRecord::toStatic() instead
     */
    public static function toExtStatic(MetaRecord $rs): MetaRecord
    {
        $rs->toStatic();

        return $rs;
    }
}
