<?php

/**
 * Gutenberg (block editor) podrška za ubacivanje slike uplatnice i/ili IPS QR kôda.
 *
 * Oba bloka su "dynamic" blokovi — render se u potpunosti obavlja na PHP strani, pozivom
 * postojećih [uplatnica] / [ipsqr] shortcode-ova, tako da nema duplirane poslovne logike.
 */
class WooplatnicaBlocks
{
    public function __construct()
    {
        add_action('init', [$this, 'register_blocks']);
    }

    public function register_blocks()
    {
        if (!function_exists('register_block_type')) {
            return;
        }

        wp_register_script(
            'wooplatnica-blocks',
            plugins_url('../assets/js/wooplatnica-blocks.js', __FILE__),
            ['wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render', 'wp-i18n'],
            '1.3',
            true
        );

        register_block_type('wooplatnica/uplatnica', [
            'editor_script'   => 'wooplatnica-blocks',
            'render_callback' => [$this, 'render_uplatnica'],
            'attributes'      => [
                'order'  => ['type' => 'string', 'default' => ''],
                'width'  => ['type' => 'number', 'default' => 0],
                'height' => ['type' => 'number', 'default' => 0],
                'align'  => ['type' => 'string', 'default' => 'none'],
                'alt'    => ['type' => 'string', 'default' => ''],
                'title'  => ['type' => 'string', 'default' => ''],
                'class'  => ['type' => 'string', 'default' => ''],
            ],
        ]);

        register_block_type('wooplatnica/ips-qr', [
            'editor_script'   => 'wooplatnica-blocks',
            'render_callback' => [$this, 'render_ipsqr'],
            'attributes'      => [
                'order'  => ['type' => 'string', 'default' => ''],
                'size'   => ['type' => 'number', 'default' => 512],
                'width'  => ['type' => 'number', 'default' => 0],
                'height' => ['type' => 'number', 'default' => 0],
                'alt'    => ['type' => 'string', 'default' => ''],
                'title'  => ['type' => 'string', 'default' => ''],
                'class'  => ['type' => 'string', 'default' => ''],
            ],
        ]);
    }

    public function render_uplatnica($attributes)
    {
        return do_shortcode($this->build_shortcode('uplatnica', $attributes));
    }

    public function render_ipsqr($attributes)
    {
        return do_shortcode($this->build_shortcode('ipsqr', $attributes));
    }

    protected function build_shortcode($tag, $attributes)
    {
        $shortcode = '['.$tag;

        foreach ($attributes as $name => $value) {
            if ($value === '' || $value === null || $value === 0) {
                continue;
            }

            $shortcode .= ' '.$name.'="'.esc_attr($value).'"';
        }

        return $shortcode.']';
    }
}
