<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Hash;


class AuthController extends Controller
{
    public function sendResetLinkEmail(Request $request)
    {
        // Validate the incoming request
        $request->validate(['email' => 'required|email']);

        // Send the password reset email
        $status = Password::sendResetLink(
            $request->only('email')
        );

        if ($status === Password::RESET_LINK_SENT) {
            return response()->json(['message' => __($status)], 200);
        }

        return response()->json(['message' => __($status)], 400);
    }

    public function reset(Request $request)
    {
        // Validate the incoming request
        $request->validate([
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|min:8|confirmed',
        ]);

        // Reset the password
        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function ($user, $password) {
                $user->password = Hash::make($password);
                $user->save();
            }
        );

        if ($status === Password::PASSWORD_RESET) {
            // If it's an API request, return a JSON response
            if ($request->wantsJson()) {
                return response()->json(['message' => __($status)], 200);
            }

            // If it's a web request, redirect to a success page
            return redirect()->route('password.success');
        }

        // Handle failure
        if ($request->wantsJson()) {
            return response()->json(['message' => __($status)], 400);
        }

        return redirect()->back()->withErrors(['email' => __($status)]);
    }
}
