<?php

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

abstract class AIEO_SSO_Provider_Base {

    
    abstract public function code();

    
    abstract public function label();

    
    public function credentials() {
        $settings = AIEO_SSO_Buttons_Data::get_settings();
        $row = isset($settings['providers'][$this->code()]) ? $settings['providers'][$this->code()] : array();
        return array(
            'client_id'     => isset($row['client_id'])     ? (string) $row['client_id']     : '',
            'client_secret' => isset($row['client_secret']) ? (string) $row['client_secret'] : '',
            'enabled'       => !empty($row['enabled']),
        );
    }

    
    abstract public function auth_url($state, $redirect_uri);

    
    abstract public function exchange_token($code, $redirect_uri);

    
    abstract public function fetch_profile(array $token);

    
    protected function split_name($name) {
        $name = trim((string) $name);
        if ($name === '') { return array('', ''); }
        $parts = preg_split('/\s+/u', $name, 2);
        return array(
            (string) ($parts[0] ?? ''),
            (string) ($parts[1] ?? ''),
        );
    }

    
    protected function http_post_form($url, array $body, array $headers = array()) {
        $resp = wp_remote_post($url, array(
            'timeout'     => 15,
            'redirection' => 0,
            'headers'     => array_merge(array('Accept' => 'application/json'), $headers),
            'body'        => $body,
        ));
        return $this->decode_json_response($resp);
    }

    
    protected function http_get_authorised($url, $access_token, array $extra_headers = array()) {
        $resp = wp_remote_get($url, array(
            'timeout'     => 15,
            'redirection' => 0,
            'headers'     => array_merge(array(
                'Authorization' => 'Bearer ' . $access_token,
                'Accept'        => 'application/json',
            ), $extra_headers),
        ));
        return $this->decode_json_response($resp);
    }

    private function decode_json_response($resp) {
        if (is_wp_error($resp)) { return $resp; }
        $code = (int) wp_remote_retrieve_response_code($resp);
        $body = (string) wp_remote_retrieve_body($resp);
        $json = json_decode($body, true);
        if ($code < 200 || $code >= 300) {
            
            return new WP_Error('sso_http_' . $code, sprintf( __( 'HTTP %1$d from %2$s: %3$s', 'ai-eshop-optimizer' ), $code, $this->code(), substr($body, 0, 300)));
        }
        if (!is_array($json)) {
            
            return new WP_Error('sso_bad_json', sprintf( __( 'Non-JSON from %1$s: %2$s', 'ai-eshop-optimizer' ), $this->code(), substr($body, 0, 200)));
        }
        return $json;
    }
}
