<?php

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

class AIEO_MOI_OAuth {

    
    public static function access_token(array $vendor, callable $refresh, $skew = 120) {
        $creds = isset($vendor['credentials']) && is_array($vendor['credentials']) ? $vendor['credentials'] : array();
        $oauth = isset($creds['oauth']) && is_array($creds['oauth']) ? $creds['oauth'] : array();
        $now   = time();

        if (!empty($oauth['access_token']) && !empty($oauth['expires_at']) && ((int) $oauth['expires_at'] - $skew) > $now) {
            return (string) $oauth['access_token'];
        }

        $res = call_user_func($refresh, $oauth, $creds);
        if (is_wp_error($res)) { return $res; }
        if (!is_array($res) || empty($res['access_token'])) {
            return new WP_Error('moi_oauth_no_token', __('Token endpoint returned no access_token.', 'ai-eshop-optimizer'));
        }

        $oauth['access_token'] = (string) $res['access_token'];
        $oauth['expires_at']   = $now + (int) (isset($res['expires_in']) ? $res['expires_in'] : 3600);
        if (!empty($res['refresh_token'])) {
            $oauth['refresh_token'] = (string) $res['refresh_token']; 
        }
        $creds['oauth'] = $oauth;
        if (!empty($vendor['id'])) {
            AIEO_MOI_Vendor_Manager::update_credentials((int) $vendor['id'], $creds);
        }
        return (string) $oauth['access_token'];
    }

    
    public static function refresh_token($oauth_state, array $credentials, $seed_key = 'refresh_token') {
        if (!empty($oauth_state['refresh_token'])) { return (string) $oauth_state['refresh_token']; }
        return (string) ($credentials[$seed_key] ?? '');
    }

    
    public static function token_request($url, array $body, $basic = null, array $extra_headers = array()) {
        $headers = array_merge(array(
            'Content-Type' => 'application/x-www-form-urlencoded',
            'Accept'       => 'application/json',
        ), $extra_headers);
        if (is_array($basic)) {
            $headers['Authorization'] = 'Basic ' . base64_encode((string) ($basic['user'] ?? '') . ':' . (string) ($basic['pass'] ?? ''));
        }

        $resp = wp_remote_post($url, array(
            'timeout' => 25,
            'headers' => $headers,
            'body'    => $body, 
        ));
        if (is_wp_error($resp)) { return $resp; }

        $code = (int) wp_remote_retrieve_response_code($resp);
        $raw  = (string) wp_remote_retrieve_body($resp);
        $json = json_decode($raw, true);
        if ($code >= 400 || !is_array($json)) {
            $msg = is_array($json) && !empty($json['error_description']) ? (string) $json['error_description']
                : (is_array($json) && !empty($json['error']) ? (string) $json['error']
                
                : sprintf(__('Token endpoint HTTP %d', 'ai-eshop-optimizer'), $code));
            return new WP_Error('moi_oauth_token_failed', $msg, array('status' => $code, 'body' => $raw));
        }
        return $json;
    }
}
