<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\User;
use Hash;
use Auth;
use Exception;
use Illuminate\Support\Facades\Password;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;

class AuthController extends Controller
{
    public function Index(Request $request)
    {
        if (Auth::user()) {
            return redirect()->route('dashboard');
        }

        $messages = [
            'errors' => $request->session()->get('errors'),
            'message' => $request->session()->get('message'),
            'success' => $request->session()->get('success'),
        ];

        return Inertia::render('Admin/Login')->with('messages', $messages);
    }

    public function ForgetPasswordIndex(Request $request)
    {
        if (Auth::user()) {
            return redirect()->route('dashboard');
        }

       
        $messages = [
            'errors' => $request->session()->get('errors'),
            'message' => $request->session()->get('message'),
            'success' => $request->session()->get('success'),
        ];


        return Inertia::render('Admin/ForgetPassword')->with('messages', $messages);
    
    }

    public function ForgetPasswordSendMail(Request $request)
    {
        $request->validate(['email' => 'required|email']);

        $status = Password::sendResetLink(
            $request->only('email')
        );

        if( $status === Password::ResetLinkSent) {
            session()->flash('success', 'Password reset link sent to your email.');
        } else {
            session()->flash('errors', 'Failed to send password reset link. Please try again.');
        }

        return redirect()->back();
    }

    public function ResetPasswordIndex(Request $request, $token)
    {
       
        $email = $request->query('email');

        // Check if token and email exist in the password_resets table
        $reset = DB::table('password_reset_tokens')
            ->where('email', $email)
            ->first();

            
        //check token expiration (default is 60 minutes)
        if (!$reset || !Hash::check($token, $reset->token) || Carbon::parse($reset->created_at)->addMinutes(60)->isPast()) {
            session()->flash('errors', 'Invalid or expired password reset token.');
            return redirect()->route('login');
        }


        $messages = [
            'errors' => $request->session()->get('errors'),
            'message' => $request->session()->get('message'),
            'success' => $request->session()->get('success'),
        ];


        return Inertia::render('Admin/ResetPassword')->with('messages', $messages);

    }

    public function ResetPassword(Request $request)
    {

        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function (User $user, string $password) {
                $user->forceFill([
                    'password' => Hash::make($password)
                ])->setRememberToken(Str::random(60));

                $user->save();

                event(new PasswordReset($user));
            }
        );

        if ($status === Password::PasswordReset) {
            session()->flash('success', 'Your password has been reset successfully.');
            return redirect()->route('login');
        }

        session()->flash('errors', 'Failed to reset password. Please try again.');
        return redirect()->back();
    }

    public function Login(Request $request)
    {
        try {

            $email = $request->get('email');

            $user = User::where('email', $email)->where('status',true)->first();

            #dd(Hash::make($request->get('password')));


            if (Hash::check($request->get('password'), $user->password, )) {
                Auth::login(($user));

                return redirect()->route('dashboard');
            } else {
                session()->flash('errors', 'Invalid username or password');
                return redirect()->back();
            }
        }catch (Exception $e) {
            session()->flash('errors', 'Invalid username or password');
            return redirect()->back();
        }
    }

    public function Logout(Request $request)
    {
        Auth::logout();

        return redirect()->route('login');
    }

}
