<?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 SignupController extends Controller
{
    private $callApiService;

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

    public function index()
    {
        $passwdPolicy = setupPasswdPolicy('member');

        $smsCert = session('smsCert');

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

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

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

        return view('views.auth.member-signup', [
            'passwdPolicy' => $passwdPolicy,
        ]);
    }

    public function store()
    {
        $passwdPolicy = setupPasswdPolicy('member');

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

        $passwdRules = makePasswdRules($passwdPolicy);

        $validator = validator::make(request()->all(), [
            'email' => ['required', 'email'],
            'password' => $passwdRules,
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        if ($this->checkDormantMember(request('email'))) {
            notify()->error('휴면상태로 전환된 계정입니다. 로그인을 하시면 휴면 상태를 해제하실 수 있습니다.', 'Error', 'bottomRight');
            return redirect()->back();
        }

        $response = $this->callApiService->callApi([
            'url' => 'member-signup',
            'data' => [
                'Email' => request('email'),
                'Password' => request('password'),
                'SgroupCode' => request('sgroup_code'),
                'MobileNo' => formatPhone(request('mobile_no')),
                'FirstName' => request('first_name'),
            ]
        ]);

        if (isset($response['apiStatus'])) {
            notify()->error($response['body'], 'Error', 'bottomRight');
            return redirect()->back();
        }

        // 가입확인 메일 보내는 이벤트
        event(new UserCreated([
            'email' => request('email'),
            'activate_code' => $response['ActivateCode']
        ]));

        session()->forget('smsCert');

        notify()->success(_e('Action completed'), 'Success', 'bottomRight');
        return redirect()->route('member-go-email');
    }

    public function checkDormantMember($email)
    {
        $b64Email = base64_encode($email);
        $memberPage = $this->callApiService->callApi([
            'url' => 'member-page',
            'data' => [
                'PageVars' => [
                    'Query' => "email = '$b64Email' and status = '5'",
                    'Limit' => 1, 'Offset' => 0
                ]
            ]
        ]);

        if ($this->callApiService->verifyApiError($memberPage)) {
            return false;
        }

        $member = $memberPage['Page'][0];

        if (isset($member) && $member['Status'] === '5') {
            return true;
        }

        return false;
    }

    public function activateCodeResend()
    {
        $response = $this->callApiService->callApi([
            'url' => 'member-pick',
            'data' => [
                'Page' => [
                    [ 'Email' => request('email') ]
                ]
            ]
        ]);

        if ($this->callApiService->verifyApiError($response)) {
            notify()->error('이메일 계정이 존재하지 않습니다', 'Error', 'bottomRight');
            return redirect()->back();
        }

        event(new UserCreated([
            'email' => request('email'),
            'activate_code' => $response['Page'][0]['ActivateCode']
        ]));

        notify()->success(_e('Action completed'), 'Success', 'bottomRight');
        return redirect()->route('member-go-email');
    }

    public function confirm()
    {
        $response = $this->callApiService->callApi([
            'url' => 'member-activate',
            'data' => [
                'ActivateCode' => request('code'),
            ],
        ]);

        if (isset($response['apiStatus'])) {
            return redirect()->route('member-activate-failed');
        } else {
            return redirect()->route('member-verify-ok');
        }
    }
}
