<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class ResetPasswordController extends Controller
{
    // Method untuk reset password
    public function reset(Request $request)
    {
        // Validasi input
        $request->validate([
            'token' => 'required|string',
            'email' => 'required|email',
            'password' => 'required|string|min:8|confirmed',  // Pastikan password panjangnya min 8 karakter
        ]);

        // Cari token di database
        $passwordReset = DB::table('password_resets')
            ->where('token', $request->token)
            ->where('email', $request->email)
            ->first();

        if (!$passwordReset) {
            return response()->json(['message' => 'Token atau email tidak valid'], 400);
        }

        // Periksa apakah token sudah kadaluarsa (misalnya 60 menit)
        $expiresAt = Carbon::parse($passwordReset->created_at)->addMinutes(60);
        if (Carbon::now()->isAfter($expiresAt)) {
            return response()->json(['message' => 'Token kadaluarsa'], 400);
        }

        // Reset password
        $user = User::where('email', $request->email)->first();
        if ($user) {
            $user->password = Hash::make($request->password);
            $user->save();

            // Hapus token setelah digunakan
            DB::table('password_resets')->where('email', $request->email)->delete();

            return response()->json(['message' => 'Password berhasil direset'], 200);
        }

        return response()->json(['message' => 'Email tidak ditemukan'], 404);
    }
}
