<?php

namespace App\Http\Controllers\Auth;

use App\Helpers\Cart;
use Illuminate\Support\Str;
use Socialite;
use App\Http\Controllers\Controller;
use App\Model\User;


class LoginFacebookController extends Controller
{
    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider()
    {
        if (!Str::contains(url()->previous(), 'login')) {
            session()->put('url.intended', url()->previous());
        }

        config(['services.facebook.redirect' => (config('services.facebook.redirect'))]);

        return Socialite::driver('facebook')
            ->scopes(['email'])
            ->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback()
    {
        try {
            // somehow it doesnt work with state, it's not being set into session.
            $facebookUser = Socialite::driver('facebook')
                ->stateless()
                ->user();
        } catch (\Exception $exception) {
            return redirect()->route('site.')->with('error', 'Nu ati aprobat conectarea sau eroare interna. Incercati din nou');
        }

        // try to find the user in our system.
        $user = User::where('email', $facebookUser->getEmail())
            ->orWhere('facebook_id', $facebookUser->getId())
            ->first();

        // if user doesnt exist, create it.
        if (!$user) {
            $user = User::create([
                'email' => $facebookUser->getEmail(),
                'name' => $facebookUser->getName(),
                'facebook_id' => $facebookUser->getId(),
                'facebook_data' => $facebookUser,
                'ua' => request()->server('HTTP_USER_AGENT'),
                'ip' => request()->ip(),
            ]);
            // otherwise update facebook id, if needed
        } elseif (!$user->facebook_id) {
            $user->facebook_id = $facebookUser->getId();
            $user->facebook_data = $facebookUser;
            $user->save();
        }


        // login user
        auth()->login($user, true);

        return redirect()->intended(route('site.'));

        // redirect to checkout if needed
        if ((new Cart)->count()) {
            return redirect()->route('site.checkout');
        }

        return redirect(route('client.'));
    }
}