<?php

namespace App\Helpers\SocialHelper;

use Exception;
use GuzzleHttp\Client;
use Namshi\JOSE\JWS;
use phpseclib\Crypt\RSA;
use phpseclib\Math\BigInteger;

class AppleLogin implements SocialLoginInterface
{
    private $identityToken = '';

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

    public function getUser()
    {
        try {
            $jws = JWS::load($this->identityToken);

            $keyID = $jws->getHeader()['kid'] ?? '';

            $guzzleClient = new Client();

            $appleKeys = collect(
                json_decode($guzzleClient->get("https://appleid.apple.com/auth/keys")->getBody())->keys
            )->keyBy('kid');

            $identityKey = $appleKeys[$keyID];

            $rsa = new RSA();

            $modulus = new BigInteger($this->base64url_decode(urldecode($identityKey->n)), 256);
            $exponent = new BigInteger($this->base64url_decode(urldecode($identityKey->e)), 256);

            $rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
            $rsa->setPublicKey();

            $pub_key = $rsa->getPublicKey();

            if ($jws->verify($pub_key))
                return $jws->getPayload();
            return null;
        } catch (Exception $e) {
            return null;
        }
    }

    private function base64url_decode($data)
    {
        return base64_decode(strtr($data, '-_', '+/') . str_repeat('=', 3 - (3 + strlen($data)) % 4));
    }

    public static function mapUserData($userInfoResponse)
    {
        return [
            'email' => $userInfoResponse['email'],
            'social_id' => $userInfoResponse['sub'],
            'social_platform' => 'apple'
        ];
    }
}
