<?php

namespace Acms\Services\Auth;

use Acms\Contracts\Factory as BaseFactory;
use App;
use DB;
use SQL;

class Factory extends BaseFactory
{
    /**
     * Factory
     *
     * @return mixed
     */
    public function createInstance()
    {
        if ( $this->isRoleAvailableUser() ) {
            return new Role;
        } else if ( SUID && config('subscriber_view_mode') === 'on' ) {
            $app = App::getInstance();
            $Q =& $app->getQueryParameter();
            $admin = $Q->get('admin');
            if ( empty($admin) ) {
                return new SimulateSubscriber;
            }
        }
        return new General;
    }

    /**
     * ロールによる権限チェッックを行うユーザーか
     *
     * @return bool
     */
    protected function isRoleAvailableUser()
    {
        if ( !editionIsEnterprise() ) {
            return false;
        }

        $user = loadUser(SUID);
        if ( 1
            && intval($user->get('blog_id')) === RBID
            && in_array(\ACMS_RAM::userAuth(SUID), array('administrator', 'subscriber'))
        ) {
            return false;
        }

        $DB = DB::singleton(dsn());
        $SQL = SQL::newSelect('usergroup_user');
        $SQL->addSelect('usergroup_id');
        $SQL->addWhereOpr('user_id', SUID);

        if ( $usergroups = $DB->query($SQL->get(dsn()), 'all') ) {
            if ( is_array($usergroups) && !empty($usergroups) ) return true;
        }
        return false;
    }
}