<?php

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

class AIEO_DataForSEO {

	const OPTION   = 'aieo_dataforseo_auth';
	const BASE_URL = 'https://api.dataforseo.com';
	const TIMEOUT  = 30;

	
	
	

	
	public static function is_connected() {
		return '' !== self::auth_b64();
	}

	
	public static function auth_b64() {
		$v = get_option( self::OPTION, '' );
		return is_string( $v ) ? trim( $v ) : '';
	}

	
	public static function login() {
		$raw = base64_decode( self::auth_b64(), true );
		if ( ! is_string( $raw ) || false === strpos( $raw, ':' ) ) {
			return '';
		}
		list( $login ) = explode( ':', $raw, 2 );
		return $login;
	}

	
	public static function save_credentials( $raw ) {
		$raw = trim( (string) $raw );
		if ( '' === $raw ) {
			return new WP_Error( 'aieo_dfs_empty', __( 'Paste the API credentials first.', 'ai-eshop-optimizer' ) );
		}
		if ( false !== strpos( $raw, ':' ) ) {
			
			$b64 = base64_encode( $raw );
		} else {
			
			$decoded = base64_decode( $raw, true );
			if ( ! is_string( $decoded ) || false === strpos( $decoded, ':' ) ) {
				return new WP_Error( 'aieo_dfs_invalid', __( 'That does not look like login:password or the Base64 string from the DataForSEO dashboard.', 'ai-eshop-optimizer' ) );
			}
			$b64 = $raw;
		}
		update_option( self::OPTION, $b64, false ); 
		return true;
	}

	
	public static function disconnect() {
		delete_option( self::OPTION );
	}

	
	
	

	
	public static function get( $path ) {
		return self::call( 'GET', $path, null );
	}

	
	public static function post( $path, array $payload ) {
		return self::call( 'POST', $path, array( $payload ) );
	}

	
	private static function call( $method, $path, $body ) {
		$auth = self::auth_b64();
		if ( '' === $auth ) {
			return new WP_Error( 'aieo_dfs_unconfigured', __( 'DataForSEO is not connected on this site (SEO → General).', 'ai-eshop-optimizer' ) );
		}
		$args = array(
			'method'  => $method,
			'timeout' => self::TIMEOUT,
			'headers' => array(
				'Authorization' => 'Basic ' . $auth,
				'Content-Type'  => 'application/json',
			),
		);
		if ( null !== $body ) {
			$args['body'] = wp_json_encode( $body );
		}
		$res = wp_remote_request( self::BASE_URL . $path, $args );
		if ( is_wp_error( $res ) ) {
			return $res;
		}
		$code    = (int) wp_remote_retrieve_response_code( $res );
		$decoded = json_decode( (string) wp_remote_retrieve_body( $res ), true );
		if ( 401 === $code ) {
			return new WP_Error( 'aieo_dfs_auth', __( 'DataForSEO rejected the credentials (401). Re-check them on the API Access page — and note a fresh account must verify its e-mail before the API works.', 'ai-eshop-optimizer' ) );
		}
		if ( $code < 200 || $code >= 300 || ! is_array( $decoded ) ) {
			return new WP_Error(
				'aieo_dfs_http',
				sprintf(  __( 'DataForSEO returned HTTP %d.', 'ai-eshop-optimizer' ), $code )
			);
		}
		
		if ( isset( $decoded['status_code'] ) && 20000 !== (int) $decoded['status_code'] ) {
			return new WP_Error(
				'aieo_dfs_api',
				sprintf(
					
					__( 'DataForSEO error %1$d: %2$s', 'ai-eshop-optimizer' ),
					(int) $decoded['status_code'],
					isset( $decoded['status_message'] ) ? (string) $decoded['status_message'] : ''
				)
			);
		}
		return $decoded;
	}

	
	
	

	
	public static function test_connection() {
		$res = self::get( '/v3/appendix/user_data' );
		if ( is_wp_error( $res ) ) {
			return $res;
		}
		$item = isset( $res['tasks'][0]['result'][0] ) && is_array( $res['tasks'][0]['result'][0] )
			? $res['tasks'][0]['result'][0]
			: array();
		return array(
			'login'    => isset( $item['login'] ) ? (string) $item['login'] : self::login(),
			'balance'  => isset( $item['money']['balance'] ) ? (float) $item['money']['balance'] : null,
			'currency' => 'USD',
			'limits'   => isset( $item['rates'] ) ? $item['rates'] : null,
		);
	}
}
