<?php

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

class AIEO_SSO_Provider_GitHub extends AIEO_SSO_Provider_Base {

    const AUTH_URL    = 'https://github.com/login/oauth/authorize';
    const TOKEN_URL   = 'https://github.com/login/oauth/access_token';
    const PROFILE_URL = 'https://api.github.com/user';
    const EMAILS_URL  = 'https://api.github.com/user/emails';

    public function code()  { return 'github'; }
    public function label() { return 'GitHub'; }

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

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

    public function fetch_profile(array $token) {
        $access = (string) ($token['access_token'] ?? '');
        if ($access === '') { return new WP_Error('sso_no_token', 'GitHub did not return an access_token.'); }

        $profile = $this->http_get_authorised(self::PROFILE_URL, $access, array(
            'User-Agent' => 'AIEO-Social-Login',
        ));
        if (is_wp_error($profile)) { return $profile; }

        
        $email = '';
        $emails = $this->http_get_authorised(self::EMAILS_URL, $access, array(
            'User-Agent' => 'AIEO-Social-Login',
        ));
        if (!is_wp_error($emails) && is_array($emails)) {
            foreach ($emails as $e) {
                if (!empty($e['primary']) && !empty($e['verified']) && !empty($e['email'])) {
                    $email = (string) $e['email'];
                    break;
                }
            }
        }

        $name_full = (string) ($profile['name'] ?? '');
        if ($name_full === '') {
            $name_full = (string) ($profile['login'] ?? '');
        }
        list($first, $last) = $this->split_name($name_full);

        return array(
            'provider_uid' => (string) ($profile['id']        ?? ''),
            'email'        => $email,
            'first_name'   => $first,
            'last_name'    => $last,
            'avatar'       => (string) ($profile['avatar_url'] ?? ''),
            'raw'          => $profile,
        );
    }
}

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