<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Requests\Dashboard\EmailSettingsRequest;
use App\Http\Requests\Dashboard\PasswordSettingsRequest;
use App\Http\Requests\Dashboard\UsernameSettingsRequest;
use App\Models\User;
use App\Http\Controllers\Controller;
use App\Notifications\VerifyNewEmail;
use Carbon\Carbon;

class SettingsController extends Controller
{
    public function settings()
    {
        return view("dashboard.settings.index")->with([
            "user" => auth()->user(),
            "adminAndEditors" => User::where("role_id", 1)->orWhere("role_id", 2)->get(),
        ]);
    }

    public function updateUsername(UsernameSettingsRequest $request)
    {
//        if($request->validated()){
//        $user = auth()->user();
//        $user->username = $request->username;
//        $user->save();
//
//        auth()->logout();
//        session()->flush();
//
//        return redirect()->route("auth.loginShow");
//        }
//        else {
            return back()->withInput(['tab'=>'security']);
       // }
    }

    public function updatePassword(PasswordSettingsRequest $request)
    {
        $user = auth()->user();
        $user->password = bcrypt($request->password);
        $user->save();

        auth()->logout();
        session()->flush();

        return redirect()->route("auth.loginShow");
    }

    public function updateEmail(EmailSettingsRequest $request)
    {
        $user = auth()->user();

        $user->email = $request->email;
        $user->is_active = false;
        $user->security_code = $user->generateSecurityCode();
        $user->verify_token = $user->generateVerifyToken();

        $user->save();

        $user->notify(new VerifyNewEmail($user));

        auth()->logout();
        session()->flush();

        return redirect()->route("auth.loginShow");
    }

}
