<?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\Http\Request;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\User;

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

    /**
     * Display a list of sites in system.
     *
     * @return UserListResource
     */
    public function index(SiteRequest $request)
    {
        $term = $request->input('term');
        $sites = User::query()
            ->when(
                $request->filled('term'),
                fn($query) => $query->where('name', 'like', "%$term%")->orWhere('email', 'like', "%$term%")
            )
            ->orderBy('name')
            ->with([
                'tenants',
            ])
            ->paginate($request->input('per_page', 15));
        return new UserListResource($sites);
    }

    /**
     * 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->save();
        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);
    }
}
