<?php

namespace Themes\Pro\modunawa\app\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Services\CallApiService;
use Illuminate\Support\Facades\Validator;
use App\Events\UserCreated;

class FindMemberIdController extends Controller
{
    private $callApiService;

    public function __construct(CallApiService $callApiService)
    {
        $this->callApiService = $callApiService;
    }

    public function index()
    {
        $smsCert = session('smsCert');

        if (empty($smsCert) || empty($smsCert['code'])) {
            notify()->error('잘못된 접근입니다', 'Error', 'bottomRight');
            return redirect()->route('find-member-id-verify.index');
        }

        if ($smsCert['code'] !== 201) {
            notify()->error('인증실패', 'Error', 'bottomRight');
            return redirect()->route('find-member-id-verify.index');
        }

        if (date('YmdHis') - $smsCert['date'] > 500) {
            session()->forget('smsCert');
            notify()->error('인증 시간이 만료되었습니다', 'Error', 'bottomRight');
            return redirect()->route('find-member-id-verify.index');
        }

        $mobileNo = formatPhone($smsCert['mobile_no']);

        $memberExtPage = $this->callApiService->callApi([
            'url' => 'member-ext-page',
            'data' => [
                'PageVars' => [
                    'Query' => "mobile_no = '$mobileNo'",
                    'Desc' => 'Id',
                    'Limit' => 99999,
                    'Offset' => 0
                ]
            ]
        ]);

        if ($this->callApiService->verifyApiError($memberExtPage)) {
            notify()->error($memberExtPage['body'], 'Error', 'bottomRight');
            return redirect()->back();
        }

        $memExtIds = collect($memberExtPage['Page'])->pluck('Id')->implode(',');

        $memberPage = $this->callApiService->callApi([
            'url' => 'member-page',
            'data' => [
                'PageVars' => [
                    'Query' => "id IN ($memExtIds)",
                    'Desc' => 'Id',
                    'Limit' => 99999,
                    'Offset' => 0
                ]
            ]
        ]);

        if ($this->callApiService->verifyApiError($memberPage)) {
            notify()->error($memberPage['body'], 'Error', 'bottomRight');
            return redirect()->back();
        }

//        dump($memberPage);
        return view('views.auth.find-member-id', compact('memberPage'))->with('codeTitle', [
            "status('member')",
        ]);
    }
}
