<?php

namespace App\Http\Controllers;

use App\Mail\IPRSRegisterUser;
use App\Models\User;
use App\Notifications\AccountDeactivated;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use Spatie\Permission\Models\Role;

class SubAccountController extends Controller
{
    protected PasswordBroker $passwordBroker;

    /**
     * @param PasswordBroker $passwordBroker
     */
    public function __construct(PasswordBroker $passwordBroker)
    {
        $this->passwordBroker = $passwordBroker;
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $contracts = auth()->user()->contract->client->contracts;
        return view('sub-accounts.account', ['contracts' => $contracts, 'roles' => Role::all()]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $roles = Role::where('for_iprs_admins', false)->get();
        $contracts = auth()->user()->contract->client->contracts;
        return view('sub-accounts.accountForm', ['user' => null, 'contracts' => $contracts, 'roles' => $roles]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'contract_id' => ['required', 'numeric'],
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'status' => ['required', 'string', 'max:1'],
            'role'=> ['nullable'],
        ]);

        $user = User::create([
            'contract_rid' => $validated['contract_id'],
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => bcrypt($validated['password']??'Enc@2024'),
            'status_l' => $validated['status']
        ]);

        $validated['role'][] = 'client';
        $user->syncRoles($validated['role']);
        //get a token
        $resetToken= $this->passwordBroker->createToken($user);
        //generate link
        $resetUrl = url('/password/reset/'.$resetToken.'?email='.$user['email']); // /password/reset/{token}?email=chebonv@gmail.com
        //mail with custom template
        Mail::to($user['email'])->send(new IPRSRegisterUser($user, $resetUrl));
        return redirect()->route('sub-account.index')->with("success", "User created successfully!");
    }

    /**
     * Display the specified resource.
     */
    public function show(User $user)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $roles = Role::where('for_iprs_admins', false)->get();
        $contracts = auth()->user()->contract->client->contracts;
        $user = User::find($id);
        return view('sub-accounts.accountEdit', ['user' => $user, 'contracts' => $contracts, 'roles' => $roles]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        // get the validated data
        $validated = $request->validate([
            'contract_id' => ['required', 'numeric'],
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,' . $id],
            //'password' => ['nullable', 'string', 'min:8'],
            'status' => ['required', 'string', 'max:1'],
            'role'=> ['nullable'],
        ]);
        // store the data
        $user = User::query()->find($id);
        $user->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
        // add client role to user by default
        $validated['role'][] = 'client';
        $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));
        }

        // send a notification if account is deactivated
        if ($validated['status'] == 0)
        {
            Notification::send($user, new AccountDeactivated($user));
        }

        // return a response to the user and redirect
        return redirect()->route('sub-account.index')->with("success", "User updated successfully!");
    }

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