<?php

// Exit if accessed directly
if (!defined('ABSPATH')) exit;

class MXLNSTGutenberg
{

    public function registerBlocks()
    {

        // server side rendering
        add_action('init', [$this, 'serverSideRendering']);
    }

    /**
     * Blocks
     */

    // server side rendering
    public function serverSideRendering()
    {

        $asset_file = include('build/server-side-rendering/index.asset.php');

        wp_register_script(
            'mx_server_side_rendering_script',
            MXERP_PLUGIN_URL . 'includes/gutenberg/build/server-side-rendering/index.js',
            $asset_file['dependencies'],
            $asset_file['version'],
            true
        );

        register_block_type(
            __DIR__ . '/build/server-side-rendering',
            [
                'api_version'       => 2,
                'category'          => 'widgets',
                'editor_script' => 'mx_server_side_rendering_script',
                'render_callback'   => [$this, 'server_side_rendering_dynamic_render_callback'],
                'skip_inner_blocks' => true,
            ]
        );
    }

    public function server_side_rendering_dynamic_render_callback($block_attributes, $content)
    {

        ob_start();

        $url = 'https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5';

		if ($this->check_if_url_exists($url)) {

			$data = file_get_contents($url);

			$exchange_courses = json_decode($data, true);

			if (is_array($exchange_courses)) { ?>

				<div class="clearfix"></div>
				<div class="mx-exchange-rate-wrap">

					<div class="mx-exchange-rate-row mx-exchange-rate-row-header">
						<div class="mx-rate-name">Валюта</div>
						<div class="mx-rate-buy">Купівля</div>
						<div class="mx-rate-sale">Продаж</div>
					</div>

					<?php foreach ($exchange_courses as $exchange_cours) : ?>

						<div class="mx-exchange-rate-row">
							<div class="mx-rate-name"><?php echo $exchange_cours['ccy']; ?></div>
							<div class="mx-rate-buy"><?php echo round($exchange_cours['buy'], 2); ?></div>
							<div class="mx-rate-sale"><?php echo round($exchange_cours['sale'], 2); ?></div>
						</div>

					<?php endforeach; ?>

				</div>
				<div class="clearfix"></div>

		<?php }

		}

        return ob_get_clean();
    }

    public function check_if_url_exists($url)
	{

		$curl = curl_init($url);

		curl_setopt($curl, CURLOPT_NOBODY, true);

		$result = curl_exec($curl);

		return $result;
	}
}

$gutenbergClassInstance = new MXLNSTGutenberg();

$gutenbergClassInstance->registerBlocks();
