<?php

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

class AIEO_SSO_Provider_Twitter extends AIEO_SSO_Provider_Base {

    const AUTH_URL    = 'https://twitter.com/i/oauth2/authorize';
    const TOKEN_URL   = 'https://api.twitter.com/2/oauth2/token';
    const PROFILE_URL = 'https://api.twitter.com/2/users/me?user.fields=name,profile_image_url,verified';

    public function code()  { return 'twitter'; }
    public function label() { return 'X.com'; }

    public function auth_url($state, $redirect_uri) {
        $cfg = $this->credentials();
        if ($cfg['client_id'] === '') {
            return new WP_Error('sso_no_client_id', 'Twitter client_id missing.');
        }
        
        $verifier  = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
        $challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
        
        set_transient('aieo_sso_twitter_pkce_' . md5($state), $verifier, 600);

        return self::AUTH_URL . '?' . http_build_query(array(
            'response_type'         => 'code',
            'client_id'             => $cfg['client_id'],
            'redirect_uri'          => $redirect_uri,
            'scope'                 => 'tweet.read users.read',
            'state'                 => $state,
            'code_challenge'        => $challenge,
            'code_challenge_method' => 'S256',
        ));
    }

    public function exchange_token($code, $redirect_uri) {
        $cfg = $this->credentials();

        
        
        
        $state = isset($_GET['state']) ? (string) wp_unslash($_GET['state']) : '';
        $verifier_key = 'aieo_sso_twitter_pkce_' . md5($state);
        $verifier = (string) get_transient($verifier_key);
        delete_transient($verifier_key);
        if ($verifier === '') {
            return new WP_Error('sso_pkce_missing', 'X.com PKCE verifier expired — try again.');
        }

        return $this->http_post_form(self::TOKEN_URL, array(
            'grant_type'    => 'authorization_code',
            'code'          => $code,
            'redirect_uri'  => $redirect_uri,
            'client_id'     => $cfg['client_id'],
            'code_verifier' => $verifier,
        ), array(
            'Authorization' => 'Basic ' . base64_encode($cfg['client_id'] . ':' . $cfg['client_secret']),
        ));
    }

    public function fetch_profile(array $token) {
        $access = (string) ($token['access_token'] ?? '');
        if ($access === '') { return new WP_Error('sso_no_token', 'X.com did not return an access_token.'); }
        $resp = $this->http_get_authorised(self::PROFILE_URL, $access);
        if (is_wp_error($resp)) { return $resp; }
        $data = isset($resp['data']) && is_array($resp['data']) ? $resp['data'] : array();

        list($first, $last) = $this->split_name((string) ($data['name'] ?? ''));
        return array(
            'provider_uid' => (string) ($data['id'] ?? ''),
            'email'        => '', 
            'first_name'   => $first,
            'last_name'    => $last,
            'avatar'       => (string) ($data['profile_image_url'] ?? ''),
            'raw'          => $resp,
        );
    }
}

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