<?php
/**
 * Summary. Creates all Oxygen API calls.
 *
 * @package Oxygen
 * OxygenApi Class File
 *
 * @version 2.0.40
 * @since  1.0.0
 */

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

/**
 * Oxygen MyData Class
 */
class OxygenApi {

	/**
	 * Singleton Instance of OxygenApi
	 *
	 * @var OxygenApi
	 **/
	private static $instance = null;

	/**
	 * API KEY string
	 *
	 * @var string
	 */
	private static $api_key = '';

	/**
	 * Oxygen API URL
	 *
	 * @var string URL
	 */
	public static $api_url = '';

	/**
	 * API authentication token variable
	 *
	 * @var string
	 */
	public static $auth_token = '';

	/**
	 * API Status option string live|test
	 *
	 * @var string
	 */
	public static $oxygen_status = '';

	/**
	 * API request headers
	 *
	 * @var array
	 */
	public static $api_headers = '';


	/**
	 * Singleton init Function.
	 *
	 * @static
	 */
	public static function init() {
		if ( ! self::$instance ) {
			self::$instance = new self();

		}

		self::$api_key       = OxygenHelperFunctions::get_option( 'oxygen_api_key' );
		self::$oxygen_status = OxygenHelperFunctions::get_option( 'oxygen_status' );

		if ( 'live' === self::$oxygen_status ) {

			self::$api_url = 'https://api.oxygen.gr/v1';

		} else {

			self::$api_url = 'https://sandbox-api.oxygen.gr/v1';

		}

		self::$api_headers = array(
			'Authorization'    => 'Bearer ' . self::$api_key,
			'Accept'           => 'application/json',
			'X-Plugin-Version' => OXYGEN_PLUGIN_VERSION,
			'X-Plugin-Type'    => 'woocommerce',
		);

		return self::$instance;
	}

	/**
	 * OxygenApi Constructor.
	 */
	public function __construct() {
	}

	/**
	 *  Oxygen API ping and API key validation request.
	 *
	 *  @return array|WP_Error|false The response or WP_Error on failure.
	 */
	public static function check_connection() {

		$url = self::$api_url . '/numbering-sequences';

		$args = array(
			'body'    => array(),
			'headers' => self::$api_headers,
		);

		$request = wp_remote_get( $url, $args );

		if ( is_array( $request ) && isset( $request['response'] ) ) {

			return $request['response'];
		}

		return false;
	}

	/**
	 *  Oxygen API numbering sequences request.
	 *
	 *  @return array|WP_Error The response or WP_Error on failure.
	 */
	public static function get_sequences() {

		$url  = self::$api_url . '/numbering-sequences';
		$args = array(
			'headers' => self::$api_headers,
		);

		$result = wp_remote_get( $url, $args );
		if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 !== $result['response']['code'] ) {

			return $result['response'];
		}

		return $result;
	}



	/**
	 *  Oxygen API taxes request.
	 *
	 *  @param int $page Page number of the request.
	 *  @return array|WP_Error The response or WP_Error on failure.
	 */
	public static function get_taxes( $page = 1 ) {

		$url  = self::$api_url . '/taxes';
		$args = array(
			'page'    => $page,
			'headers' => self::$api_headers,
		);

		$taxes = wp_remote_get( $url, $args );

		if ( is_array( $taxes ) && isset( $taxes['response']['code'] ) && 200 !== $taxes['response']['code'] ) {

			return $taxes['response'];
		}

		return $taxes;
	}

	/**
	 *  Oxygen API logos request.
	 *
	 *  @return array|false|WP_Error The response false or WP_Error on failure.
	 */
	public static function get_logos() {

		$url  = self::$api_url . '/logos';
		$args = array(
			'headers' => self::$api_headers,
		);

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

		if ( is_array( $response ) && isset( $response['response']['code'] ) && 200 !== $response['response']['code'] ) {

			return $response['response'];
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		return ( isset( $body['data'] ) ? $body['data'] : false );
	}

	/**
	 *  Oxygen API payment methods request.
	 *
	 *  @return array|WP_Error The response or WP_Error on failure.
	 */
	public static function get_payment_methods() {

		$url  = self::$api_url . '/payment-methods';
		$args = array(
			'headers' => self::$api_headers,
		);

		$result = wp_remote_get( $url, $args );

		if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 !== $result['response']['code'] ) {

			return $result['response'];
		}

		return $result;
	}


	public static function get_measurement_units(){

		$url  = self::$api_url . '/measurement-units';

		return self::extracted( $url );
	}

	/**
	 *  Oxygen API add notice request.
	 *
	 *  @param array $invoice_args API notice data.
	 *  @return array|WP_Error|false The response or WP_Error on failure.
	 */
	public static function add_notice( $invoice_args ) {

		$url  = self::$api_url . '/notices';
		$args = array(
			'body'    => $invoice_args,
			'headers' => self::$api_headers,
		);

		$result = wp_remote_post( $url, $args );

		if ( is_a( $result, 'WP_Error' ) ) {

			return $result;
		}

		if ( isset( $result['response']['code'] ) && is_array( $result ) && ! ( 200 === $result['response']['code'] || 201 === $result['response']['code'] ) ) {

			return $result['body'];
		}

		return $result;
	}

	/**
	 *  Oxygen API invoice PDF file request.
	 *
	 *  @param string $invoice_id API invoice ID.
	 *  @param string $print_type 80mm or a4 or 0 for empty.
	 *
	 *  @return string|WP_Error The response or WP_Error on failure.
	 */
	public static function get_invoice_pdf( $invoice_id, $print_type ) {

		$template = 'a4';
		if ( ! empty( $print_type ) && '0' !== $print_type ) {
			$template = $print_type;
		}

		$url = self::$api_url . '/invoices/' . $invoice_id . '/pdf?template=' . rawurlencode( $template );

		$args = array(
			'invoice_id' => $invoice_id,
			'headers'    => array(
				'Authorization' => 'Bearer ' . self::$api_key,
				'Accept'        => 'application/json',
			),
		);

		$result = wp_remote_get( $url, $args );

		if ( is_a( $result, 'WP_Error' ) ) {
			return $result;
		}

		if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 !== $result['response']['code'] ) {

			return $result['response'];
		}

		return $result;
	}


	/**
	 *  Oxygen API notice PDF file request.
	 *
	 *  @param string $notice_id API invoice ID.
	 *
	 *  @return string|WP_Error The response or WP_Error on failure.
	 */
	public static function get_notice_pdf( string $notice_id ) {

		$url = self::$api_url . '/notices/' . $notice_id . '/pdf';

		$args = array(
			'invoice_id' => $notice_id,
			'headers'    => array(
				'Authorization' => 'Bearer ' . self::$api_key,
				'Accept'        => 'application/json',
			),
		);

		$result = wp_remote_get( $url, $args );

		if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 !== $result['response']['code'] ) {

			return $result['response'];
		}

		return $result;
	}

	/**
	 *  Oxygen API add contact request.
	 *
	 *  @param array $contact_args API contact data.
	 *  @return array|WP_Error The response or WP_Error on failure.
	 */
	public static function add_contact( $contact_args ) {

		$log = array( '----------------- CONTACT ARGS ARE -----------------', $contact_args );
		OxygenHelperFunctions::debug( $log , 'debug' );

		$url  = self::$api_url . '/contacts';
		$args = array(
			'body'    => $contact_args,
			'headers' => self::$api_headers,
		);

		$result = wp_remote_post( $url, $args );

		if ( is_a( $result, 'WP_Error' ) ) {

			return $result;
		}

		if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 !== $result['response']['code'] ) {

			return $result['body'];
		}

		return $result;
	}

    /**
     *  Oxygen API update contact request.
     *
     *  @param array $contact_args API contact data.
     *  @return array|WP_Error The response or WP_Error on failure.
     */
    public static function update_contact( $contact_args ) {

        $log = array( '----------------- CONTACT ARGS FOR UPDATE ARE -----------------', $contact_args );
        OxygenHelperFunctions::debug( $log, 'debug' );

        $url  = self::$api_url . '/contacts/'.$contact_args['id'];
        $args = array(
            'method'  => 'PATCH',
            'body'    => $contact_args,
            'headers' => self::$api_headers,
        );

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


        if ( is_a( $result, 'WP_Error' ) ) {
            return $result;
        }

        if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 !== $result['response']['code'] ) {
            return $result['body'];
        }

        return $result;
    }

	/**
	 *  Oxygen API single contact request by vat number.
	 *
	 *  @param string $vatnum Oxygen API vat number string.
	 *  @return array The API response.
	 */
	public static function get_contact_by_vat( $vatnum ) {

		$url = self::$api_url . '/contacts?vat=' . $vatnum;

		return self::extracted( $url );
	}

	/**
	 *  Oxygen API single contact request by email.
	 *
	 *  @param string $email Oxygen API email string.
	 *  @return array|bool The API response.
	 */
	public static function get_contact_by_email( $email ) {

		if ( empty( $email ) ) {

			OxygenHelperFunctions::debug( array( '------- empty email in get_contact_by_email -------- ' . $email ));
			return false;
		}
		$url = self::$api_url . '/contacts?email=' . $email;

		return self::extracted( $url );
	}


    /**
	 *  Oxygen API add invoice request.
	 *
	 *  @param array $invoice_args API invoice data.
	 *  @return array|WP_Error The response or WP_Error on failure.
	 */
	public static function add_invoice( $invoice_args ) {

		$url  = self::$api_url . '/invoices';
		$args = array(
			'body'    => $invoice_args,
			'headers' => self::$api_headers,
		);

		$result = wp_remote_post( $url, $args );

		$log = array( '------------ result of add_invoice --------------', $args );
		OxygenHelperFunctions::debug( $log, 'debug' );

		if ( is_a( $result, 'WP_Error' ) ) {

			return $result;
		}

		if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 !== $result['response']['code'] ) {

			return $result['body'];
		}

		return $result;
	}

	/**
	 *  Oxygen API check vat.
	 *
	 *  @param string $vat_number is vat number.
	 *  @return array The API response.
	 */
	public static function do_vat_check( $vat_number ) {

		$log = array( '---------------- do greek vat check -------------', $vat_number );
		OxygenHelperFunctions::debug( $log , 'debug');

		$url  = self::$api_url . '/vat-check/?vat=' . $vat_number;
		$args = array(
			'headers' => self::$api_headers,
		);

		$result = wp_remote_get( $url, $args );

		if ( is_a( $result, 'WP_Error' ) ) {
			$log = array( '---------------- do vat check -------------', $result['message'] );
			OxygenHelperFunctions::debug( $log );
			return $result;
		}

		if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 !== $result['response']['code'] ) {

			return array(
				'code' => $result['response']['code'],
				json_decode( $result['body'], true ),
			);
		}

		return json_decode( $result['body'], true );
	}

	/**
	 *  Oxygen API check VIES.
	 *
	 *  @param string $vat_number is vat number.
	 *  @param string $country_code country code.
	 *  @return array The API response.
	 */
	public static function do_vies_check( $vat_number, $country_code ) {

		$log = array( '---------------- do vies check -------------', $vat_number, $country_code );
		OxygenHelperFunctions::debug( $log , 'debug');

		$url  = self::$api_url . '/vies/?vat=' . $vat_number . '&country_code=' . $country_code;
		$args = array(
			'headers' => self::$api_headers,
		);

		$result = wp_remote_get( $url, $args );

		if ( is_a( $result, 'WP_Error' ) ) {
			$log = array( '---------------- do vies check -------------', $result['message'] );
			OxygenHelperFunctions::debug( $log );
			return $result;
		}

		if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 !== $result['response']['code'] ) {

			return array(
				'code' => $result['response']['code'],
				json_decode( $result['body'], true ),
			);
		}

		return json_decode( $result['body'], true );
	}

	/**
	 * Extracted method
	 *
	 * @param string $url is url.
	 *
	 * @return array|mixed|WP_Error
	 */
	public static function extracted( string $url ) {
		$args = array(
			'headers' => self::$api_headers,
		);

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

		if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 !== $result['response']['code'] ) {
			return $result['response'];
		}

		$body = wp_remote_retrieve_body( $result );

		return json_decode( $body, true );
	}
}
