<?php

namespace WPT\MLSL\Blocks\LocationAddress;

use WPT\MLSL\Blocks\Styles;
/**
 * Block.
 */
class Block {
    protected $container;

    /**
     * Constructor.
     */
    public function __construct( $container ) {
        $this->container = $container;
    }

    /**
     * Init block
     */
    public function init() {
        register_block_type( $this->container['plugin_dir'] . '/blocks/location-address/', [
            'render_callback' => [$this, 'render_callback'],
        ] );
    }

    public function render_callback( $attributes, $content ) {
        $module_class = $attributes['module_class'];
        $show_no_location_error = 'off';
        $no_location_found_error = '';
        global $post;
        $post_id = $post->ID;
        $location = $post;
        if ( $attributes['use_current_post'] ) {
            if ( isset( $_GET['context'] ) and $_GET['context'] == 'edit' and isset( $_GET['post_id'] ) ) {
                $post_id = $_GET['post_id'];
                if ( $post_id != $post->ID ) {
                    $location = get_post( $post_id );
                }
            }
        } else {
            if ( $attributes['location_post'] ) {
                $post_id = $attributes['location_post'];
                $location = get_post( $post_id );
            }
        }
        $location_data = $this->container['locations']->get( $location );
        $address_array = $this->container['locations']->get_address_array( $location_data );
        if ( empty( $address_array ) ) {
            $address_array = [
                '909 Dummy Street',
                'Dummy State',
                '99999',
                'Dummy Country'
            ];
        }
        if ( !empty( $address_array ) ) {
            $address_array = array_map( function ( $item ) {
                return sprintf( '<span class="location-part">%s</span>', $item );
            }, $address_array );
        }
        $separator = ( $attributes['layout'] == 'single' ? '<span class="mlsl-address-separator">, </span>' : '<br class="mlsl-address-separator"/>' );
        $css = '';
        ob_start();
        require $this->container['plugin_dir'] . '/resources/views/location-address.php';
        $html = ob_get_clean();
        if ( isset( $_GET['context'] ) and $_GET['context'] == 'edit' ) {
            $html .= "<style>{$css}</style>";
        } else {
            wp_register_style( 'location-address-inline-css', false );
            wp_enqueue_style( 'location-address-inline-css' );
            wp_add_inline_style( 'location-address-inline-css', $css );
        }
        return "<div class='{$module_class}'>{$html}</div>";
    }

}
