<?php
namespace Themes\kbgolf\pro\app\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use SocialiteProviders\Apple\Provider;
use Laravel\Socialite\Facades\Socialite;
use Laravel\Socialite\Two\GoogleProvider;
use Laravel\Socialite\Two\FacebookProvider;
use SocialiteProviders\Kakao\KakaoProvider;
use App\Providers\Socialite\OAuth2\DaboryProvider;
use SocialiteProviders\Naver\Provider as NaverProvider;
use Illuminate\Http\Request;

class SocialTalkController extends Controller
{
    private $appleTokenService;
    private $oauth2Info;
    private $target;

    public function redirectToProvider($provider)
    {
        $this->oauth2Info = request('oauth2Info');
        // dump($this->oauth2Info);
        return $this->setConfig($provider, request('target'))->redirect();
    }

    public function login($provider)
    {
        [$this->target, $ssoBrand] = explode('-', $provider);
        if ($this->target == 'member') {
            if ($ssoBrand == 'naver') {
                return Redirect::away('https://talk.naver.com/ct/w5ubd2');
            }elseif($ssoBrand == 'kakao'){
                return Redirect::away('https://pf.kakao.com/_aAAGj/chat');
            }
        }
    }

    public function setConfig($provider, $target)
    {
        $config = [
            'client_id' => $this->oauth2Info['ClientId'],
            'client_secret' => $this->oauth2Info['ClientSecret'],
            'redirect' => "/social/$target-$provider/callback"
        ];

        switch ($provider) {
            case 'dabory':
                $driver = Socialite::buildProvider(DaboryProvider::class, [
                    'client_id' => config('app.api.main.ClientId'),
                    'client_secret' => config('app.api.main.ClientSecret'),
                    'redirect' => $config['redirect']
                ]);
                break;
            case 'facebook':
                $driver = Socialite::buildProvider(FacebookProvider::class, $config);
                break;
            case 'kakao':
                $driver = Socialite::buildProvider(KakaoProvider::class, $config);
                break;
            case 'google':
                $driver = Socialite::buildProvider(GoogleProvider::class, $config);
                break;
            case 'naver':
                $driver = Socialite::buildProvider(NaverProvider::class, $config);
                break;
            case 'apple':

                $config['client_secret'] = $this->appleTokenService->generate(
                    $this->oauth2Info['PrivateKey'],
                    $this->oauth2Info['ClientId'],
                    $this->oauth2Info['TeamId'],
                    $this->oauth2Info['KeyId'],
                );

                $driver = Socialite::buildProvider(Provider::class, $config);
                break;
        }
        return $driver;
    }
}
