<?php
/**
 * Event Date Block
 *
 * @package NemtlyBooking\Blocks
 */

namespace NemtlyBooking\Blocks;

use NemtlyBooking\Core\Event_Creator;
use NemtlyBooking\Core\Status;

/**
 * Event Date Block class
 */
class Event_Date extends Abstract_Block {

    /**
     * Block Name
     *
     * @var string
     */
    protected $block_name = 'event-date';

    /**
     * Render the block
     *
     * @param array    $attributes Block attributes.
     * @param string   $content    Block content.
     * @param \WP_Block $block      Block instance.
     * @return string
     */
    public function render( $attributes, $content, $block ) {
        $post_id = isset( $block->context['postId'] ) ? $block->context['postId'] : 0;

        // Verify post type
        if ( empty( $post_id ) || get_post_type( $post_id ) !== 'nemtly_event' ) {
            return '';
        }

        // Slot-based events (one-on-one, group) don't have a single event date.
        $event_type = get_post_meta( $post_id, Event_Creator::META_EVENT_TYPE, true );

        if ( in_array( $event_type, [ Status::EVENT_TYPE_ONE_ON_ONE, Status::EVENT_TYPE_GROUP ], true ) ) {
            return '';
        }

        $event_date     = get_post_meta( $post_id, 'nemtly_event_date', true );
        $event_time     = get_post_meta( $post_id, 'nemtly_event_time', true );
        $event_timezone = get_post_meta( $post_id, 'nemtly_event_timezone', true );

        if ( empty( $event_date ) ) {
            return '';
        }

        // Use event's timezone for display, fall back to site timezone
        try {
            $tz = new \DateTimeZone( $event_timezone ? $event_timezone : wp_timezone_string() );
        } catch ( \Exception $e ) {
            $tz = wp_timezone();
        }

        // Format Date
        $format         = isset( $attributes['format'] ) ? $attributes['format'] : get_option( 'date_format' );
        $date_obj       = new \DateTime( $event_date . ' ' . ( $event_time ? $event_time : '00:00' ), $tz );
        $formatted_date = wp_date( $format, $date_obj->getTimestamp(), $tz );

        // Include time if requested
        $show_time      = isset( $attributes['showTime'] ) ? $attributes['showTime'] : true;
        $formatted_time = '';
        if ( $show_time && ! empty( $event_time ) ) {
            $time_format    = get_option( 'time_format' );
            $formatted_time = wp_date( $time_format, $date_obj->getTimestamp(), $tz );
        }

        /**
         * Filter the CSS classes applied to the Event Date block wrapper.
         *
         * @since PBOOKING_SINCE
         *
         * @param string[] $classes    Wrapper CSS classes.
         * @param array    $attributes Block attributes.
         * @param int      $post_id    Event post ID.
         */
        $classes = apply_filters( 'nemtly_booking_block_event_date_classes', [ 'nemtly-event-date' ], $attributes, $post_id );

        $wrapper_attributes = get_block_wrapper_attributes(
            [
                'class' => implode( ' ', $classes ),
            ]
        );

        $icon = '';
        if ( isset( $attributes['showIcon'] ) && $attributes['showIcon'] ) {
            $icon = '<svg width="20" height="20" class="nb-mr-2" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" clip-rule="evenodd" /></svg>';
        }

        /**
         * Filter the resolved render data for the Event Date block.
         *
         * @since PBOOKING_SINCE
         *
         * @param array $data       {
         *     @type string $datetime       Machine-readable datetime attribute value.
         *     @type string $formatted_date Human-readable formatted date.
         *     @type string $formatted_time Human-readable formatted time (empty if not shown).
         *     @type string $icon           Icon markup (empty if not shown).
         * }
         * @param array $attributes Block attributes.
         * @param int   $post_id    Event post ID.
         */
        $data = apply_filters(
            'nemtly_booking_block_event_date_data',
            [
                'datetime'       => $event_date . ( $event_time ? 'T' . $event_time : '' ),
                'formatted_date' => $formatted_date,
                'formatted_time' => $formatted_time,
                'icon'           => $icon,
            ],
            $attributes,
            $post_id
        );

        $output = sprintf(
            '<div %1$s>%2$s<time datetime="%3$s">%4$s</time>',
            $wrapper_attributes,
            $data['icon'],
            esc_attr( $data['datetime'] ),
            esc_html( $data['formatted_date'] )
        );

        if ( $data['formatted_time'] ) {
            $output .= sprintf(
                '<span class="nemtly-event-time-separator"> | </span><time class="nemtly-event-time">%s</time>',
                esc_html( $data['formatted_time'] )
            );
        }

        $output .= '</div>';

        /**
         * Filter the final rendered HTML of the Event Date block.
         *
         * @since PBOOKING_SINCE
         *
         * @param string $output     Rendered block HTML.
         * @param array  $data       Render data used to build the output.
         * @param array  $attributes Block attributes.
         * @param int    $post_id    Event post ID.
         */
        return apply_filters( 'nemtly_booking_block_event_date_html', $output, $data, $attributes, $post_id );
    }
}
