<?php

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

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

class LoginController extends Controller
{
    private $callApiService;

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

    public function index()
    {
        [$oauth2InfoList, $develLoginInfo] = setupSsoClientOrLoginInfo();

//        dump($oauth2InfoList);

        return view('views.auth.member-login', compact('oauth2InfoList', 'develLoginInfo'));
    }

    public function store()
    {
        $validator = validator::make(request()->all(), [
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

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

        $data = [
            'Email' => request('email'),
            'Password' => request('password')
        ];
        $response = $this->callApiService->callApi([
            'url' => 'member-login',
            'data' => $data
        ]);

        if (isset($response['apiStatus'])) {
            switch ($response['apiStatus']) {
                case 228:
                    return redirect()->route('member-login', ['email' => request('email')])->with(['dormant_member' => true, 'dormant_member_id' => $response['body']->MemberId]);
                case 701:
                    return redirect()->route('member-verify-resend', ['email' => request('email')]);
                case 702:
                    notify()->error(__('Google 로그인으로 접속해주세요'), 'Error', 'bottomRight');
                    return redirect()->back()->withInput();
                case 703:
                    notify()->error(__('탈퇴 진행 중인 계정입니다'), 'Error', 'bottomRight');
                    return redirect()->back()->withInput();
                case 704:
                case 744:
                    notify()->error($response['body'], 'Error', 'bottomRight');
                    return redirect()->route('member-unlock.index')->with(['email' => request('email')]);
                case 709:
                    return redirect()->route('find-member-pw-verify.index', ['email' => request('email')]);
                default:
                    $mgs = $response['body'] ?? _e('API request failed. Please Check');
                    notify()->error($mgs, 'Error', 'bottomRight');
                    return redirect()->back()->withInput();
            }
        }

        session()->put('locale', \Str::of($response['CountryCode'])->explode('_')->first());
        session()->put('member', array_merge($response, ['is_member' => true, 'Ip' => request()->ip()]));
        session()->forget('user');

        $this->addCart();

        $redirectUrl = getLoginRedirectUrl(request('previous_url'));

        if (request('remember')) {
            $minutes = time() + 60 * 60 * 24 * 100;
            return redirect()->to($redirectUrl)->withCookie(cookie('dabory_member_info', serialize($data), $minutes));
        }

        return redirect()->to($redirectUrl)->withCookie(Cookie::forget('dabory_member_info'));
    }

    public function addCart()
    {
        $memberBuyerId = session('member')['MemberBuyerId'];
        $sessId = session()->get('sessId');
        $cartPage = $this->callApiService->callApi([
            'url' => 'cart-page',
            'data' => [
                'PageVars' => [
                    'Query' => "(session_id = '$sessId' and member_buyer_id = 0) or (member_buyer_id = $memberBuyerId)",
                    'Limit' => 100000,
                    'Offset' => 0
                ]
            ]
        ]);
        if (!empty($cartPage['Page'])) {
            $guestCart = collect($cartPage['Page'])->filter(function ($cart) use ($sessId) {
               return $cart['SessionId'] === $sessId and $cart['MemberBuyerId'] === 0;
            })->values()->toArray();
            $memberCart = collect($cartPage['Page'])->filter(function ($cart) use ($memberBuyerId) {
                return $cart['MemberBuyerId'] === $memberBuyerId;
            })->values()->toArray();

            foreach ($guestCart as $index => $cart1) {
                $overlap = collect($memberCart)->filter(function ($cart2) use ($cart1) {
                    return $cart2['ItemId'] === $cart1['ItemId'] && $cart2['Options'] === $cart1['Options'];
                })->toArray();
                if (! empty($overlap)) {
                    $guestCart[$index]['Id'] *= -1;
                }
            }

            $cartActReq = collect($guestCart)->map(function ($cart1) use ($memberBuyerId) {
                if ($cart1['Id'] < 0) {
                    return [
                        'Id' => $cart1['Id'],
                    ];
                }
                return array_merge($cart1, [
                    'SessionId' => '',
                    'MemberBuyerId' => $memberBuyerId,
                ]);
            })->toArray();

            if (! empty($cartActReq)) {
                $this->callApiService->callApi([
                    'url' => 'cart-act',
                    'data' => [
                        'Page' => $cartActReq
                    ]
                ]);
            }
        }
    }
}
