<?php

namespace App\Http\Controllers\Auth;

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

class ResetPasswordController extends Controller
{
    public function showResetForm(Request $request)
    {
        $token = $request->query('token');
        $email = $request->query('email');
        return view('auth.reset-password', compact('token', 'email'));
    }

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

        // トークンチェック
        $record = DB::table('password_reset_tokens')
            ->where('ope_mail', $request->email)
            ->where('token', $request->token)
            ->first();

        if (!$record) {
            return back()->withErrors(['email' => '無効なトークンまたはメールアドレスです。']);
        }

        // パスワード更新
        $user = Ope::where('ope_mail', $request->email)->first();
        if (!$user) {
            return back()->withErrors(['email' => 'ユーザーが見つかりません。']);
        }
        $user->password = Hash::make($request->password);
        $user->save();

        // トークン削除
        DB::table('password_reset_tokens')->where('ope_mail', $request->email)->delete();

        return redirect()->route('login')->with('status', 'パスワードを再設定しました。');
    }
}