<?php
/**
 * Gutenberg Blocks
 *
 * @package Spin_Wheel
 */

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

/**
 * SWP_Blocks Class
 */
class SWP_Blocks {
    
    /**
     * Instance
     *
     * @var SWP_Blocks
     */
    private static $instance = null;
    
    /**
     * Get instance
     *
     * @return SWP_Blocks
     */
    public static function instance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        add_action('init', [$this, 'register_block']);
    }
    
    /**
     * Register Gutenberg block
     */
    public function register_block() {
        // Check if Gutenberg is available
        if (!function_exists('register_block_type')) {
            return;
        }
        
        // Register block
        register_block_type('spin-wheel/wheel', [
            'attributes'      => [
                'wheelId' => [
                    'type'    => 'number',
                    'default' => 0,
                ],
            ],
            'render_callback' => [$this, 'render_block'],
        ]);
    }
    
    /**
     * Render block
     *
     * @param array $attributes Block attributes
     * @return string Block output
     */
    public function render_block($attributes) {
        $wheel_id = isset($attributes['wheelId']) ? intval($attributes['wheelId']) : 0;
        
        if (!$wheel_id) {
            return '<p>' . esc_html__('Please select a wheel from the block settings.', 'spin-wheel') . '</p>';
        }
        
        return do_shortcode("[spin_wheel id=\"{$wheel_id}\"]");
    }
}
