<?php

namespace Modules\Invite\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Modules\Invite\Models\InviteAgent;
use Ramsey\Uuid\Uuid;

use Modules\Invite\Models\Invite;
use Modules\User\Models\User;
use Modules\User\Models\Role;
use Modules\User\Models\UserRole;
use Modules\Main\Models\Company\Company;
use Modules\Main\Models\Company\CompanyAdmin;
use Modules\Main\Models\Agent\Agent;
use Modules\CityManager\Models\CityManager;

class InviteController extends Controller
{
    public function index(Company $company = null)
    {
        $companies = [];
        //$companiesIds = UserRole::where('user_id', auth()->user()->id)->pluck('company_id')->toArray();
        if (!$company) {
            if (auth()->user()->hasRole(Role::CITY_MANAGER)) {
                $citiesIds = CityManager::where('user_id', auth()->user()->id)->pluck('city_id')->toArray();
                foreach (Company::whereIn('city_id', $citiesIds)->get() as $company) {
                    $companies[] = $company;
                }
            }
            if (auth()->user()->hasRole(Role::COMPANY_ADMIN)) {
                $companyAdmin = CompanyAdmin::where('user_id', auth()->user()->id)->first();
                $companies[] = $companyAdmin->company;
            }
            if (count($companies) > 1) {
                return view('invite::companies', [
                    'companies' => $companies
                ]);
            } else {
                return to_route('company.invites', [
                    'company' => $companies[0]
                ]);
            }
        } 
        return view('invite::index', [
            'company' => $company,
            'invites' => Invite::where('company_id', $company->id)->get()
        ]);
    }
    public function create(Request $request, Company $company) {
        Invite::create([
            'hash' => Uuid::uuid4(),
            'company_id' => $company->id
        ]);
        return back();
    }
    public function open(Request $request, $hash) {
        if (!$invite = Invite::where('hash', $hash)->first()) {
            return back();
        }
        return view('invite::form', [
            'invite' => $invite
        ]);
        return back();
    }

    public function process(Request $request, $hash) {
        if (!$invite = Invite::where('hash', $hash)->first()) {
            return back();
        }
        $user = User::where('email', $request->email)->orWhere('phone', $request->phone)->first();
        
        if ($user) {
            if (UserRole::where('user_id', Role::AGENT)->get()) {
                return back()->withInput()->withErrors('Агент с данным телефоном или электронной почтой уже зарегистрирован');
            }
        } else {
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'phone' => $request->phone
            ]);
        }
        $agent = Agent::create([
            'company_id' => $invite->company_id,
            'user_id' => $user->id
        ]);
        if (!$agent && $user->wasRecentlyCreated) {
            $user->delete();
            return back()->withInput()->withErrors('При создании учетной записи возникла ошибка. Попробуйте сделать это немного позже');
        }
        $registration = InviteAgent::create([
            'invite_id' => $invite->id,
            'agent_id' => $agent->id
        ]);
        if (!$registration) {
            $agent->forceDelete();
            return back()->withInput()->withErrors('При создании учетной записи возникла ошибка. Попробуйте сделать это немного позже');
        }
        $user->setForcedPassword();
        return to_route('company.invite.success', [
            'hash' => $invite->hash
        ]);
    }

    public function success(Request $request, $hash) {
        if (!$invite = Invite::where('hash', $hash)->first()) {
            return back();
        }
        return view('invite::success', [
            'invite' => $invite
        ]);
    }
    public function delete (Invite $invite) {
        $invite->delete();
        return back()->withSuccess('Ссылка-приглашение была успешно удалена');
    }
    public function agents(Invite $invite) {
        return view('invite::agents', [
            'invite' => $invite
        ]);
    }
}