<?php

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

class AIEO_SSO_Provider_Facebook extends AIEO_SSO_Provider_Base {

    const GRAPH_VER  = 'v18.0';
    const AUTH_URL   = 'https://www.facebook.com/v18.0/dialog/oauth';
    const TOKEN_URL  = 'https://graph.facebook.com/v18.0/oauth/access_token';
    const PROFILE_URL = 'https://graph.facebook.com/v18.0/me';

    public function code()  { return 'facebook'; }
    public function label() { return 'Facebook'; }

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

    public function exchange_token($code, $redirect_uri) {
        $cfg = $this->credentials();
        
        
        $url = self::TOKEN_URL . '?' . http_build_query(array(
            'code'          => $code,
            'client_id'     => $cfg['client_id'],
            'client_secret' => $cfg['client_secret'],
            'redirect_uri'  => $redirect_uri,
        ));
        $resp = wp_remote_get($url, array('timeout' => 15));
        if (is_wp_error($resp)) { return $resp; }
        $body = (string) wp_remote_retrieve_body($resp);
        $code_http = (int) wp_remote_retrieve_response_code($resp);
        $json = json_decode($body, true);
        if ($code_http < 200 || $code_http >= 300 || !is_array($json)) {
            return new WP_Error('sso_facebook_token', sprintf('Facebook token exchange HTTP %d: %s', $code_http, substr($body, 0, 200)));
        }
        return $json;
    }

    public function fetch_profile(array $token) {
        $access = (string) ($token['access_token'] ?? '');
        if ($access === '') {
            return new WP_Error('sso_no_token', 'Facebook did not return an access_token.');
        }
        $url = self::PROFILE_URL . '?' . http_build_query(array(
            'fields'       => 'id,first_name,last_name,email,picture.type(large)',
            'access_token' => $access,
        ));
        $resp = wp_remote_get($url, array('timeout' => 15));
        if (is_wp_error($resp)) { return $resp; }
        $code_http = (int) wp_remote_retrieve_response_code($resp);
        $body = (string) wp_remote_retrieve_body($resp);
        $json = json_decode($body, true);
        if ($code_http < 200 || $code_http >= 300 || !is_array($json)) {
            return new WP_Error('sso_facebook_profile', sprintf('Facebook profile HTTP %d: %s', $code_http, substr($body, 0, 200)));
        }
        return array(
            'provider_uid' => (string) ($json['id']         ?? ''),
            'email'        => (string) ($json['email']      ?? ''), 
            'first_name'   => (string) ($json['first_name'] ?? ''),
            'last_name'    => (string) ($json['last_name']  ?? ''),
            'avatar'       => isset($json['picture']['data']['url']) ? (string) $json['picture']['data']['url'] : '',
            'raw'          => $json,
        );
    }
}

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