<?php

namespace App\Master\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Master\Http\Requests\SiteRequest;
use App\Master\Http\Resources\UserListResource;
use App\Master\Http\Resources\UserViewResource;
use App\Notifications\PasswordResetNotification;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\TwoFactorRememberedDevice;
use Mtc\MercuryDataModels\User;

class AllUserController extends Controller
{
    public function __construct()
    {
        $this->middleware([
            'permission:manage-sites'
        ]);
    }

    /**
     * Display a list of users in system.
     *
     * @return UserListResource
     */
    public function index(SiteRequest $request)
    {
        $term = $request->input('term');
        $users = User::query()
            ->when(
                $request->filled('term'),
                fn($query) => $query->where(fn($termQuery) => $termQuery->where('name', 'like', "%$term%")
                    ->orWhere('email', 'like', "%$term%"))
            )
            ->when(
                $request->filled('role'),
                fn($query) => $query->whereIn('id', function ($subquery) use ($request) {
                    $subquery->select('model_id')
                        ->from('model_has_roles')
                        ->join('roles', 'roles.id', '=', 'model_has_roles.role_id')
                        ->where('roles.name', $request->input('role'));
                })
            )
            ->orderBy('name')
            ->with([
                'tenants',
            ])
            ->paginate($request->input('per_page', 15));
        return new UserListResource($users);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param User $allUser
     * @return UserViewResource
     */
    public function show(User $allUser)
    {
        return new UserViewResource($allUser);
    }

    public function destroy(User $allUser)
    {
        $allUser->delete();
    }

    public function reset2FactorAuth(User $user)
    {
        $user->two_factor_secret = null;
        $user->two_factor_recovery_codes = null;
        $user->two_factor_confirmed_at = null;
        $user->save();

        TwoFactorRememberedDevice::query()
            ->where('user_id', $user->id)
            ->delete();

        return new UserViewResource($user);
    }

    public function requirePasswordChange(User $user)
    {
        $user->update([
            'requires_password_change' => true,
        ]);

        return new UserViewResource($user);
    }

    public function resetPassword(User $user)
    {
        $password = Str::random(12);
        $user->update([
            'password' => bcrypt($password),
        ]);

        $user->notify(new PasswordResetNotification($password));
        return new UserViewResource($user);
    }
}
