<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * @return array{ok: bool, message: string, http: int, token_len: int, token_md5: string, url_host: string}
 */
function elementsell_billing_probe_credentials() {
    $token = function_exists( 'elementsell_telemetry_get_token' ) ? (string) elementsell_telemetry_get_token() : '';
    $token = trim( $token );
    $url   = 'https://elementsell.cz/credentials.php?token=' . rawurlencode( $token );

    $result = [
        'ok'        => false,
        'message'   => '',
        'http'      => 0,
        'token_len' => strlen( $token ),
        'token_md5' => $token !== '' ? md5( $token ) : '',
        'url_host'  => 'elementsell.cz',
    ];

    if ( $token === '' || $token === 'your_secret_token' ) {
        $result['message'] = 'Na webu běží vývojová verze bez release tokenu. Nahraj release ZIP z elementsell.cz (ne soubory z Cursoru).';
        return $result;
    }

    $response = wp_remote_get(
        $url,
        [
            'timeout'     => 15,
            'redirection' => 3,
            'sslverify'   => true,
            'headers'     => [
                'Accept'     => 'application/json',
                'User-Agent' => 'ElementSellBilling/1.0; ' . home_url( '/' ),
            ],
        ]
    );

    if ( is_wp_error( $response ) ) {
        $result['message'] = 'Nepodařilo se spojit s elementsell.cz (credentials): ' . $response->get_error_message();
        return $result;
    }

    $code = (int) wp_remote_retrieve_response_code( $response );
    $raw  = (string) wp_remote_retrieve_body( $response );
    $body = json_decode( $raw, true );
    $result['http'] = $code;

    if ( $code < 200 || $code >= 300 ) {
        $err = is_array( $body ) && ! empty( $body['error'] ) ? (string) $body['error'] : ( 'HTTP ' . $code );
        $result['message'] = 'credentials.php: ' . $err;
        if ( is_array( $body ) && ! empty( $body['token_md5'] ) && ! empty( $body['secret_md5_list'] ) ) {
            $result['message'] .= ' (token_md5 pluginu=' . $result['token_md5'] . ', server očekává jiné md5)';
        }
        return $result;
    }

    if (
        ! is_array( $body )
        || empty( $body['merchant_id'] )
        || ! isset( $body['project_id'] )
        || (int) $body['project_id'] <= 0
        || empty( $body['api_password'] )
    ) {
        $result['message'] = 'credentials.php vrátil neúplná ThePay data (doplň $ELEMENTSELL_BILLING_THEPAY v elementsell-secrets.php).';
        return $result;
    }

    if ( ! class_exists( '\ThePay\ApiClient\TheConfig' ) ) {
        $autoload = dirname( __DIR__, 2 ) . '/vendor/autoload.php';
        if ( file_exists( $autoload ) ) {
            require_once $autoload;
        }
    }

    if ( ! class_exists( '\ThePay\ApiClient\TheConfig' ) ) {
        $result['message'] = 'Chybí ThePay SDK (vendor/autoload.php) v pluginu na tomto webu.';
        return $result;
    }

    $result['ok']      = true;
    $result['message'] = 'OK — credentials i ThePay SDK jsou dostupné. Zkus znovu Změnit kartu.';
    return $result;
}

/**
 * @return array{merchant_id: string, project_id: int|string, api_password: string, environment: string}|null
 */
function elementsell_billing_get_remote_credentials() {
    $credentials_url = apply_filters(
        'elementsell_billing_credentials_url',
        'https://elementsell.cz/credentials.php?token=' . rawurlencode( elementsell_telemetry_get_token() )
    );

    $response = wp_remote_get(
        $credentials_url,
        [
            'timeout'     => 15,
            'redirection' => 3,
            'sslverify'   => true,
            'headers'     => [
                'Accept'     => 'application/json',
                'User-Agent' => 'ElementSellBilling/1.0; ' . home_url( '/' ),
            ],
        ]
    );

    if ( is_wp_error( $response ) ) {
        elementsell_billing_set_last_credentials_error( $response->get_error_message() );
        return null;
    }

    $code = (int) wp_remote_retrieve_response_code( $response );
    $raw  = (string) wp_remote_retrieve_body( $response );
    $body = json_decode( $raw, true );

    if ( $code < 200 || $code >= 300 ) {
        $hint = is_array( $body ) && ! empty( $body['error'] ) ? (string) $body['error'] : ( 'HTTP ' . $code );
        elementsell_billing_set_last_credentials_error( $hint );
        return null;
    }

    if (
        ! is_array( $body )
        || empty( $body['merchant_id'] )
        || ! isset( $body['project_id'] )
        || (int) $body['project_id'] <= 0
        || empty( $body['api_password'] )
        || empty( $body['environment'] )
    ) {
        $hint = 'Neplatná odpověď credentials.php (chybí merchant/project/heslo).';
        if ( is_array( $body ) && ! empty( $body['error'] ) ) {
            $hint = (string) $body['error'];
        }
        elementsell_billing_set_last_credentials_error( $hint );
        return null;
    }

    elementsell_billing_set_last_credentials_error( '' );

    return $body;
}

/**
 * @param string $message
 * @return void
 */
function elementsell_billing_set_last_credentials_error( $message ) {
    $GLOBALS['elementsell_billing_credentials_error'] = sanitize_text_field( (string) $message );
}

/**
 * @return string
 */
function elementsell_billing_get_last_credentials_error() {
    return isset( $GLOBALS['elementsell_billing_credentials_error'] )
        ? (string) $GLOBALS['elementsell_billing_credentials_error']
        : '';
}

/**
 * @return \ThePay\ApiClient\TheClient|null
 */
function elementsell_billing_get_thepay_client() {
    if ( ! class_exists( '\ThePay\ApiClient\TheConfig' ) ) {
        $autoload = dirname( __DIR__, 2 ) . '/vendor/autoload.php';

        if ( file_exists( $autoload ) ) {
            require_once $autoload;
        }
    }

    $credentials = elementsell_billing_get_remote_credentials();

    if ( ! $credentials ) {
        return null;
    }

    $urls = elementsell_get_thepay_urls_for_environment(
        $credentials['environment'] === 'production' ? 'production' : 'demo'
    );
    $api_url  = $urls['api_url'];
    $gate_url = $urls['gate_url'];

    $config = new \ThePay\ApiClient\TheConfig(
        $credentials['merchant_id'],
        (int) $credentials['project_id'],
        $credentials['api_password'],
        $api_url,
        $gate_url
    );

    $signature_service = new \ThePay\ApiClient\Service\SignatureService( $config );
    $http_client       = new \GuzzleHttp\Client();
    $request_factory   = new \GuzzleHttp\Psr7\HttpFactory();
    $stream_factory    = new \GuzzleHttp\Psr7\HttpFactory();
    $api_service       = new \ThePay\ApiClient\Service\ApiService(
        $config,
        $signature_service,
        $http_client,
        $request_factory,
        $stream_factory
    );

    return new \ThePay\ApiClient\TheClient( $config, $api_service );
}
