<?php
/**
 * DESCRIPTION: Server-side render class for the nemtly/event-calendar Gutenberg block.
 * Enqueues calendar assets and outputs the React mount container with data attributes.
 *
 * @since   PBOOKING_SINCE
 * @package NemtlyBooking\Blocks
 */

namespace NemtlyBooking\Blocks;

/**
 * Event Calendar Block class
 *
 * @since PBOOKING_SINCE
 */
class Event_Calendar extends Abstract_Block {

    /**
     * Block name
     *
     * @var string
     */
    protected $block_name = 'event-calendar';

    /**
     * Render the block on the frontend.
     *
     * @since PBOOKING_SINCE
     *
     * @param array     $attributes Block attributes.
     * @param string    $content    Inner block content (unused — dynamic block).
     * @param \WP_Block $block      Block instance.
     *
     * @return string HTML output.
     */
    public function render( $attributes, $content, $block ) {
        $this->enqueue_calendar_assets( $attributes );

        $default_view    = ! empty( $attributes['defaultView'] ) ? sanitize_text_field( $attributes['defaultView'] ) : '';
        $show_toolbar    = isset( $attributes['showToolbar'] ) ? (bool) $attributes['showToolbar'] : true;
        $show_filters    = isset( $attributes['showFilters'] ) ? (bool) $attributes['showFilters'] : true;
        $categories      = ! empty( $attributes['categories'] ) && is_array( $attributes['categories'] )
            ? implode( ',', array_map( 'absint', $attributes['categories'] ) )
            : '';
        $tags            = ! empty( $attributes['tags'] ) && is_array( $attributes['tags'] )
            ? implode( ',', array_map( 'absint', $attributes['tags'] ) )
            : '';
        $event_type      = ! empty( $attributes['eventType'] ) ? sanitize_text_field( $attributes['eventType'] ) : '';
        $available_views = ! empty( $attributes['availableViews'] ) && is_array( $attributes['availableViews'] )
            ? implode( ',', array_intersect( $attributes['availableViews'], [ 'month', 'week', 'day', 'list' ] ) )
            : '';

        $wrapper_attributes = get_block_wrapper_attributes(
            [
                'class'             => 'nb-event-calendar',
                'data-view'         => $default_view,
                'data-views'        => $available_views,
                'data-categories'   => $categories,
                'data-tags'         => $tags,
                'data-event-type'   => $event_type,
                'data-show-toolbar' => $show_toolbar ? 'true' : 'false',
                'data-show-filters' => $show_filters ? 'true' : 'false',
            ]
        );

        return sprintf(
            '<div %s><noscript><p>%s</p></noscript></div>',
            $wrapper_attributes,
            esc_html__( 'Please enable JavaScript to view the event calendar.', 'nemtly-booking' )
        );
    }

    /**
     * Enqueue the calendar JS/CSS bundle and localize global config.
     *
     * Guarded by wp_script_is() so repeated calls (e.g. multiple blocks on one page)
     * don't re-enqueue.
     *
     * @since PBOOKING_SINCE
     *
     * @param array $attributes Block attributes — used to populate the nemtlyCalendar JS config.
     *
     * @return void
     */
    private function enqueue_calendar_assets( $attributes ) {
        if ( wp_script_is( 'nemtly-event-calendar', 'enqueued' ) ) {
            return;
        }

        $plugin_url  = plugin_dir_url( dirname( __DIR__ ) );
        $plugin_path = plugin_dir_path( dirname( __DIR__ ) );

        wp_enqueue_style(
            'nemtly-event-calendar-styles',
            $plugin_url . 'assets/css/event-calendar.css',
            [],
            NEMTLY_BOOKING_VERSION
        );

        $asset_path = $plugin_path . 'assets/js/event-calendar.asset.php';
        $asset      = file_exists( $asset_path ) ? require $asset_path : [
            'dependencies' => [ 'wp-element', 'wp-api-fetch', 'wp-i18n' ],
            'version'      => NEMTLY_BOOKING_VERSION,
        ];

        wp_enqueue_script(
            'nemtly-event-calendar',
            $plugin_url . 'assets/js/event-calendar.js',
            $asset['dependencies'],
            $asset['version'],
            true
        );

        $available_views = ! empty( $attributes['availableViews'] ) && is_array( $attributes['availableViews'] )
            ? $attributes['availableViews']
            : [ 'month', 'week', 'day', 'list' ];

        wp_localize_script(
            'nemtly-event-calendar',
            'nemtlyCalendar',
            [
                'restUrl'          => rest_url( 'nemtly-booking/v1' ),
                'restNonce'        => wp_create_nonce( 'wp_rest' ),
                'defaultView'      => ! empty( $attributes['defaultView'] ) ? $attributes['defaultView'] : 'month',
                'availableViews'   => $available_views,
                'firstDayOfWeek'   => isset( $attributes['firstDayOfWeek'] ) ? (int) $attributes['firstDayOfWeek'] : 0,
                'eventsPerCell'    => isset( $attributes['eventsPerCell'] ) ? (int) $attributes['eventsPerCell'] : 3,
                'timeFormat'       => ! empty( $attributes['timeFormat'] ) ? $attributes['timeFormat'] : 'site_default',
                'showEventTime'    => isset( $attributes['showEventTime'] ) ? (bool) $attributes['showEventTime'] : true,
                'showBookingBtn'   => isset( $attributes['showBookingBtn'] ) ? (bool) $attributes['showBookingBtn'] : true,
                'showPastEvents'   => isset( $attributes['showPastEvents'] ) ? (bool) $attributes['showPastEvents'] : false,
                'colorBy'          => ! empty( $attributes['colorBy'] ) ? $attributes['colorBy'] : 'category',
                'categoryColors'   => ! empty( $attributes['categoryColors'] ) ? $attributes['categoryColors'] : [],
                'calendarHeight'   => ! empty( $attributes['calendarHeight'] ) ? $attributes['calendarHeight'] : 'auto',
                'calendarHeightPx' => isset( $attributes['calendarHeightPx'] ) ? (int) $attributes['calendarHeightPx'] : 600,
                'siteTimezone'     => wp_timezone_string(),
                'strings'          => [
                    'loading'       => __( 'Loading events...', 'nemtly-booking' ),
                    'noEvents'      => __( 'No events this period.', 'nemtly-booking' ),
                    'error'         => __( 'Could not load events. Please try again.', 'nemtly-booking' ),
                    'retry'         => __( 'Retry', 'nemtly-booking' ),
                    'today'         => __( 'Today', 'nemtly-booking' ),
                    'month'         => __( 'Month', 'nemtly-booking' ),
                    'week'          => __( 'Week', 'nemtly-booking' ),
                    'day'           => __( 'Day', 'nemtly-booking' ),
                    'list'          => __( 'List', 'nemtly-booking' ),
                    'viewDetails'   => __( 'View Details', 'nemtly-booking' ),
                    'bookNow'       => __( 'Book Now', 'nemtly-booking' ),
                    'allCategories' => __( 'All Categories', 'nemtly-booking' ),
                    'allTags'       => __( 'All Tags', 'nemtly-booking' ),
                    /* translators: %d: number of additional events not shown in the cell */
                    'moreEvents'    => __( '+%d more', 'nemtly-booking' ),
                    'noJs'          => __( 'Please enable JavaScript to view the event calendar.', 'nemtly-booking' ),
                ],
            ]
        );

        wp_add_inline_script(
            'nemtly-event-calendar',
            sprintf(
                'wp.apiFetch.use( wp.apiFetch.createNonceMiddleware( %s ) );',
                wp_json_encode( wp_create_nonce( 'wp_rest' ) )
            ),
            'before'
        );

        wp_set_script_translations( 'nemtly-event-calendar', 'nemtly-booking' );
    }
}
