<?php

namespace Modules\Admin\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\User\Models\UserRole;
use Modules\User\Models\Role;
use Modules\User\Models\User;
class AdminController extends Controller
{
    public function index()
    {
        if (!$this->superAdminExists())
        {
            return $this->goToSuperAdminCreator();
        }
        return view('admin::index', [
           
        ]);
    }

    public function superAdminExists()
    {
        $count = UserRole::where('role_id', Role::SUPER_ADMIN)->count();
        if ($count == 0)
        {
            return false;
        }
        return true;
    }

    public function goToSuperAdminCreator()
    {
        return view('admin::setAdmin.index', [
            'users' => User::orderBy('name')->get()
        ]);
    }

    public function setSuperAdmin(Request $request)
    {
        if (!$this->superAdminExists())
        {
            $userId = false;
            $user = User::where('email', $request->email)->orWhere('phone', $request->phone);
            if ($user->count() == 1)
            {
                $user = $user->first();
                $userId = $user->id;
            }
            elseif ($user->count() > 1)
            {
                return to_route('admin.index');
            }
            else
            {
                $user = User::create($request->all());
                $userId = $user->id;
                $user->setForcedPassword();
            }
            UserRole::create([
                'user_id' => $userId,
                'role_id' => Role::SUPER_ADMIN
            ]);
        }
        return to_route('admin.index');
    }
}