<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_SSO_Provider_LinkedIn extends AIEO_SSO_Provider_Base {

    const AUTH_URL    = 'https://www.linkedin.com/oauth/v2/authorization';
    const TOKEN_URL   = 'https://www.linkedin.com/oauth/v2/accessToken';
    const PROFILE_URL = 'https://api.linkedin.com/v2/userinfo';

    public function code()  { return 'linkedin'; }
    public function label() { return 'LinkedIn'; }

    public function auth_url($state, $redirect_uri) {
        $cfg = $this->credentials();
        if ($cfg['client_id'] === '') {
            return new WP_Error('sso_no_client_id', 'LinkedIn client_id missing.');
        }
        return self::AUTH_URL . '?' . http_build_query(array(
            'response_type' => 'code',
            'client_id'     => $cfg['client_id'],
            'redirect_uri'  => $redirect_uri,
            'scope'         => 'openid profile email',
            'state'         => $state,
        ));
    }

    public function exchange_token($code, $redirect_uri) {
        $cfg = $this->credentials();
        return $this->http_post_form(self::TOKEN_URL, array(
            'grant_type'    => 'authorization_code',
            'code'          => $code,
            'redirect_uri'  => $redirect_uri,
            'client_id'     => $cfg['client_id'],
            'client_secret' => $cfg['client_secret'],
        ));
    }

    public function fetch_profile(array $token) {
        $access = (string) ($token['access_token'] ?? '');
        if ($access === '') { return new WP_Error('sso_no_token', 'LinkedIn did not return an access_token.'); }
        $resp = $this->http_get_authorised(self::PROFILE_URL, $access);
        if (is_wp_error($resp)) { return $resp; }
        return array(
            'provider_uid' => (string) ($resp['sub']         ?? ''),
            'email'        => !empty($resp['email_verified']) ? (string) ($resp['email'] ?? '') : '',
            'first_name'   => (string) ($resp['given_name']  ?? ''),
            'last_name'    => (string) ($resp['family_name'] ?? ''),
            'avatar'       => (string) ($resp['picture']     ?? ''),
            'raw'          => $resp,
        );
    }
}

add_filter('aieo_sso_providers', static function (array $providers) {
    if (!isset($providers['linkedin']) && class_exists('AIEO_SSO_Provider_LinkedIn')) {
        $providers['linkedin'] = new AIEO_SSO_Provider_LinkedIn();
    }
    return $providers;
});
