<?php
$LoginConfig = [
    'callback' => APP_URL . '/account',
    'providers' => [
        'Google' => [
            'enabled' => (GOOGLE_APP_ID && GOOGLE_APP_SECRET) ? true : false,
            'keys' => [
                'key' => GOOGLE_APP_ID,
                'secret' => GOOGLE_APP_SECRET,
            ],
        ],
        'Facebook' => [
            'enabled' => (FACEBOOK_APP_ID && FACEBOOK_APP_SECRET) ? true : false,
            'keys' => [
                'id' => FACEBOOK_APP_ID,
                'secret' => FACEBOOK_APP_SECRET,
            ],
        ],
    ],
];

use Hybridauth\Exception\Exception;
use Hybridauth\Hybridauth;
use Hybridauth\HttpClient;
use Hybridauth\Storage\Session;

$getRedirect = filter_input(INPUT_GET, 'redirect', FILTER_SANITIZE_URL);
$getProvider = filter_input(INPUT_GET, 'provider', FILTER_SANITIZE_STRING);
$getLogout =   filter_input(INPUT_GET, 'logout', FILTER_SANITIZE_STRING);
try {
    $hybridauth = new Hybridauth($LoginConfig);
    $storage = new Session();
    $error = false;

    if ($getLogout) {
        $hybridauth->disconnectAllAdapters();
        $storage->set('identifier', null);
        $storage->set('login_via', null);
    }

    if ($getProvider) {
        if (in_array($getProvider, $hybridauth->getProviders())) {
            $storage->set('provider', $getProvider);
        } else {
            $error = $getProvider;
        }
    }


    if ($error) {
        error_log('Hybridauth Error: Provider ' . json_encode($error) . ' not found or not enabled in $config');
        // Close the pop-up window
        echo "<script>
                if (window.opener.closeAuthWindow) {
                    window.opener.closeAuthWindow();
                }
            </script>";
        exit;
    }


    if ($provider = $storage->get('provider')) {
        $hybridauth->authenticate($provider);
        $storage->set('provider', null);
        $adapter = $hybridauth->getAdapter($provider);
        $userProfile = $adapter->getUserProfile();
        $accessToken = $adapter->getAccessToken();

        $data = [
            'provider' => $provider,
            'token' => $accessToken,
            'identifier' => $userProfile->identifier,
            'email' => $userProfile->email,
            'first_name' => $userProfile->firstName,
            'last_name' => $userProfile->lastName,
            'photoURL' => strtok($userProfile->photoURL, '?'),
        ];
        if (RegisterUser($data)) {
            $storage->set('identifier', $userProfile->identifier);
            $storage->set('login_via', $provider);
        }
        echo "<script>
            if (window.opener.closeAuthWindow) {
                window.opener.closeAuthWindow();
            }
        </script>";
        exit;
    }

    HttpClient\Util::redirect(APP_URL);
} catch (Exception $e) {
    echo $e->getMessage();
}
