<?php
/**
 * Volade API — Client HTTP pour Vercel endpoints
 *
 * @package Volade\SDK
 * @license GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

class Volade_API {

	private static $instance = null;
	private $api_url         = '';
	private $api_key         = '';
	private $timeout         = 15;

	public static function get_instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
			if ( ! self::$instance->is_configured() ) {
				self::$instance = null;
			}
		}
		return self::$instance;
	}

	public function __construct() {
		$default_url   = 'https://volade.com/api';
		$this->api_url = defined( 'VOLADE_API_URL' ) ? VOLADE_API_URL : get_option( 'volade_api_url', $default_url );
		$this->api_key = defined( 'VOLADE_API_KEY' ) ? VOLADE_API_KEY : get_option( 'volade_api_key', '' );
		if ( empty( $this->api_url ) ) {
			$this->api_url = $default_url;
		}
	}

	public function configure( $api_url, $api_key = '' ) {
		$this->api_url = trailingslashit( $api_url );
		$this->api_key = $api_key;
		update_option( 'volade_api_url', $this->api_url );
		if ( $api_key ) {
			update_option( 'volade_api_key', $api_key );
		}
	}

	public function is_configured() {
		return ! empty( $this->api_url );
	}

	public function get( $endpoint, $params = array() ) {
		return $this->request( 'GET', $endpoint, $params );
	}

	public function post( $endpoint, $data = array() ) {
		return $this->request( 'POST', $endpoint, $data );
	}

	public function put( $endpoint, $data = array() ) {
		return $this->request( 'PUT', $endpoint, $data );
	}

	public function delete( $endpoint, $params = array() ) {
		return $this->request( 'DELETE', $endpoint, $params );
	}

	private function request( $method, $endpoint, $body = array() ) {
		if ( ! $this->is_configured() ) {
			return new WP_Error( 'api_not_configured', __( 'L\'API Volade n\'est pas configurée.', 'core-version-switcher-by-volade' ) );
		}

		$url = $this->api_url . ltrim( $endpoint, '/' );

		$args = array(
			'method'      => $method,
			'timeout'     => $this->timeout,
			'redirection' => 3,
			'headers'     => array(
				'Content-Type' => 'application/json',
				'Accept'       => 'application/json',
			),
		);

		if ( $this->api_key ) {
			$args['headers']['X-API-Key'] = $this->api_key;
		}

		$user = $this->get_current_user_for_api();
		if ( $user && ! empty( $user['token'] ) ) {
			$args['headers']['Authorization'] = 'Bearer ' . $user['token'];
		}

		if ( ! empty( $body ) ) {
			if ( $method === 'GET' || $method === 'DELETE' ) {
				$url = add_query_arg( $body, $url );
			} else {
				$args['body'] = wp_json_encode( $body );
			}
		}

		$response = wp_remote_request( $url, $args );

		if ( is_wp_error( $response ) ) {
			$this->log_error( $method, $endpoint, $response->get_error_message() );
			return $response;
		}

		$code = wp_remote_retrieve_response_code( $response );
		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );

		if ( $code < 200 || $code >= 300 ) {
			$msg = isset( $data['error'] ) ? $data['error'] : sprintf( 'HTTP %d', $code );
			$this->log_error( $method, $endpoint, $msg );
			return new WP_Error( 'api_error', $msg );
		}

		return $data;
	}

	private function get_current_user_for_api() {
		if ( ! class_exists( 'Volade_SDK' ) ) {
			return null;
		}
		$sdk = Volade_SDK::get_instance();
		if ( ! $sdk || ! method_exists( $sdk, 'get_current_user' ) ) {
			return null;
		}
		$user = $sdk->get_current_user();
		if ( ! $user ) {
			return null;
		}

		global $wpdb;
		$token_row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT token FROM {$wpdb->prefix}volade_tokens WHERE user_id = %d ORDER BY expires_at DESC LIMIT 1",
				$user['id']
			)
		);

		return array(
			'id'    => $user['id'],
			'token' => $token_row ? $token_row->token : '',
		);
	}

	private function log_error( $method, $endpoint, $message ) {
		if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
			error_log( sprintf( '[Volade API] %s %s: %s', $method, $endpoint, $message ) );
		}
	}

	public function is_available() {
		if ( ! $this->is_configured() ) {
			return false;
		}
		$cached = get_transient( 'volade_api_health' );
		if ( false !== $cached ) {
			return (bool) $cached;
		}
		$check = $this->get( '/health' );
		$ok    = ! is_wp_error( $check );
		set_transient( 'volade_api_health', $ok ? 1 : 0, 5 * MINUTE_IN_SECONDS );
		return $ok;
	}
}
