<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Mail\IPRSRegisterUser;
use App\Models\Contract;
use App\Models\User;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\View\View;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Str;

class UserController extends Controller
{
    protected PasswordBroker $passwordBroker;
    protected string $roles_tbl;

    public function __construct(PasswordBroker $passwordBroker)
    {
        $this->passwordBroker = $passwordBroker;
        $this->roles_tbl = Role::class;
    }
    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        $users = User::with('contract.client')->get();
        $roles= $this->roles_tbl::all();
        //dd($contracts);
        return view('user.user', [ 'users' => $users, 'roles'=>$roles ]);
    }

    /**
     * Show the form for creating a new resource.
     * @return view
     */
    public function create(): View
    {
        $roles= $this->roles_tbl::where('for_contract', false)->get();
        return view('user.userForm', ['roles'=>$roles]);
    }

    /**
     * Store a newly created resource in storage.
     * @param StoreUserRequest $request
     * @return RedirectResponse
     */
    public function store(StoreUserRequest $request): RedirectResponse
    {
        // get the validated data
        $validated = $request->validated();
        $plainPassword = $validated['password'] ?? Str::random(8);
        // store the data
        $user = User::create([
            //'id'=>'2',
            'contract_rid' => $validated['contract_id'],
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => bcrypt($plainPassword),
           // 'password' => bcrypt($validated['password'] ?? "Enc@@##?2024x"),
            'status_l' => $validated['status']
        ]);

        $user->syncRoles($validated['role']);
        //get a token
          //$resetToken= $this->passwordBroker->createToken($user);
        //generate link
        $resetUrl='';
            //$resetUrl = url('/password/reset/'.$resetToken.'?email='.$user['email']);
        //mail with custom template
            //Mail::to($user['email'])->send(new IPRSRegisterUser($user, $resetUrl));
        Mail::to($user['email'])->send(new IPRSRegisterUser($user,$plainPassword,$resetUrl));
        // return a response to the user and redirect
        return redirect()->route('user.index')
            ->with("success", "User created successfully, an email was sent to ".$user['email']." to complete registration!");
    }

    /**
     * Display the specified resource.
     * @param User $user
     * @return view
     */
    public function show(User $user): View
    {
        $roles = $user->getRoleNames();
        return view('user.userDetails', ['user' => $user, 'roles' => $roles]);
    }

    /**
     * Show the form for editing the specified resource.
     * @param User $user
     * @return view
     */
    public function edit(User $user): View
    {
        $roles =Role::where('for_contract', false)->get();
        $userRoles = $user->roles->pluck('name')->toArray();
        return view('user.userEdit', ['user' => $user, 'roles'=>$roles, 'userRoles'=> $userRoles]);
    }

    /**
     * Update the specified resource in storage.
     * @param User $user
     * @param UpdateUserRequest $request
     * @return RedirectResponse
     */
    public function update(UpdateUserRequest $request, User $user): RedirectResponse
    {
        // get the validated data
        $validated = $request->validated();
        // store the data
        User::query()->where('id', $user->id)->update([
            'contract_rid' => $validated['contract_id'],
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => $request->filled('password') ? bcrypt($validated['password']) : $user->password, // check if password is filled else pick the same stored pass
            'status_l' => $validated['status']
        ]);

        //sync role
        $user->syncRoles($validated['role']);
        if ($request->filled("reset")) {
            //get a token
            $resetToken = $this->passwordBroker->createToken($user);
            //generate link
            $resetUrl = url('/password/reset/' . $resetToken . '?email=' . $user['email']);
            //mail with custom template
            Mail::to($user['email'])->send(new IPRSRegisterUser($user, $resetUrl));
        }
        // return a response to the user and redirect
        return redirect()->route('user.index')->with("success", "User updated successfully!");
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id): RedirectResponse
    {
        // Delete a specific post
       $delete= User::find($id);
       $delete->delete();
        //redirect
       return redirect()->route('user.index')->with('success', 'User Deleted!');
    }
}
