<?php

namespace App\Http\Controllers\Web\Auth;

use App\Http\Controllers\Controller;
use App\Services\EmailVerificationService;
use Illuminate\Http\Request;

class EmailVerificationController extends Controller
{
    public function requiredPage(Request $request, EmailVerificationService $svc)
    {
        $au = $svc->getAuthUserFromSession($request);
        if (!$au) {
            return redirect()->route('web.home')
                ->with('ui_dialog', [
                    'type' => 'alert',
                    'title' => '안내',
                    'message' => '잘못된 접근입니다.',
                ]);
        }

        return view('web.auth.email_required', [
            'email' => $au['email'],
            'memNo' => $au['mem_no'],
        ]);
    }

    public function sendVerify(Request $request, EmailVerificationService $svc)
    {
        $au = $svc->getAuthUserFromSession($request);
        if (!$au) {
            return redirect()->route('web.home')
                ->with('ui_dialog', [
                    'type' => 'alert',
                    'title' => '안내',
                    'message' => '잘못된 접근입니다.',
                ]);
        }

        try {
            $res = $svc->sendVerifyMail($request, (int)$au['mem_no'], (string)$au['email']);

            return back()->with('ui_dialog', [
                'type' => 'alert',
                'title' => '안내',
                'message' => $res['message'] ?? '인증메일을 발송했습니다. 메일함을 확인해 주세요.',
            ]);
        } catch (\Throwable $e) {
            \Log::error('Email verify send failed', [
                'mem_no' => $au['mem_no'],
                'email'  => $au['email'],
                'error'  => $e->getMessage(),
            ]);
            return back()->with('ui_dialog', [
                'type' => 'alert',
                'title' => '오류',
                'message' => '인증메일 발송 중 오류가 발생했습니다.',
            ]);
        }
    }


    public function verify(Request $request, EmailVerificationService $svc)
    {
        $memNo = (int)$request->query('mem_no', 0);
        $k     = (string)$request->query('k', '');

        $res = $svc->verifySignedLink($request, $memNo, $k);

        if (!($res['ok'] ?? false)) {
            return redirect('/')->with('alert', $res['message'] ?? '잘못된 접근입니다.');
        }

        // 인증 완료 후 임시세션 제거
        $request->session()->forget('auth_user');

        return view('web.auth.email_verified', [
            'email' => (string)($res['email'] ?? ''),
            'loginUrl' => route('web.auth.login'),
        ]);
    }
}
