<?php

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

class AIEO_Opening_Hours_Block {

    private static $registered = false;

    public static function register() {
        if (self::$registered) { return; }
        self::$registered = true;
        add_action('init', array(__CLASS__, 'register_block'));
        add_shortcode('aieo_opening_hours', array(__CLASS__, 'shortcode'));
    }

    public static function register_block() {
        register_block_type('aieo/opening-hours', array(
            'api_version'     => 3,
            'title'           => __('AIEO Opening Hours', 'ai-eshop-optimizer'),
            'description'     => __("A store location's opening hours. Auto-resolves on a store page, or set a location slug.", 'ai-eshop-optimizer'),
            'category'        => 'widgets',
            'icon'            => 'clock',
            'keywords'        => array('hours', 'opening', 'schedule', 'store'),
            'supports'        => array('align' => array('wide')),
            'attributes'      => array(
                'locationSlug' => array('type' => 'string', 'default' => ''),
                'heading'      => array('type' => 'string', 'default' => ''),
            ),
            'uses_context'    => array('postId'),
            'render_callback' => array(__CLASS__, 'render'),
        ));
    }

    public static function shortcode($atts) {
        $atts = shortcode_atts(array('location' => '', 'heading' => ''), $atts, 'aieo_opening_hours');
        return self::render(array('locationSlug' => (string) $atts['location'], 'heading' => (string) $atts['heading']));
    }

    public static function render($attrs, $content = '', $block = null) {
        if (!class_exists('AIEO_Google_Reviews_Helpers')) { return ''; }
        $attrs = wp_parse_args(is_array($attrs) ? $attrs : array(), array('locationSlug' => '', 'heading' => ''));
        $loc   = AIEO_Google_Reviews_Helpers::resolve_single($attrs['locationSlug'], $block);
        if (!$loc) { return ''; }
        $hours = AIEO_Google_Reviews_Helpers::render_hours_html($loc);
        if ('' === $hours) { return ''; }

        AIEO_Google_Reviews_Helpers::enqueue_locations_assets();
        $wrap = function_exists('get_block_wrapper_attributes')
            ? get_block_wrapper_attributes(array('class' => 'aieo-loc-hours-block'))
            : 'class="aieo-loc-hours-block"';
        $out = '<div ' . $wrap . '>';
        if ('' !== (string) $attrs['heading']) { $out .= '<h3>' . esc_html($attrs['heading']) . '</h3>'; }
        $out .= $hours . '</div>';
        return $out;
    }
}
