<?php

namespace Themes\kbgolf\pro\app\Http\Controllers\Auth;

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

class CompanySignupController 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-company-signup', [
            'policyDesc' => $passwdPolicy['PolicyDesc'],
        ]);
    }

    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 (request('van')) {
            $company_json = json_encode([
                'Van' => request('van'),
                'VanId' => request('van_id'),
                'VanPw' => request('van_pw'),
            ]);
        }

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

                'Sort' => '1',

                'CompanyName' => request('company_name'),
                'CompanyClass' => 'BB',
                'TaxNo' => request('tax_no'),
                'President' => request('president'),
                'TelNo' => request('tel_no'),
                'BizType' => request('biz_type'),
                'DealItem' => request('deal_item'),

                'ZipCode' => request('zip_code'),
                'Addr1' => request('addr1'),
                'Addr2' => request('addr2'),

                'CertImg' => $this->uploadCertImage(),

                'CompanyJson' => $company_json ?? ''
            ]
        ]);

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

        // 가입확인 메일 보내는 이벤트
        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 uploadCertImage()
    {
        if (request()->hasFile('cert_img')) {
            return File::uploadImg(request()->file('cert_img'));
        }

        return null;
    }
}
