<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

$allowed_views = ['table', 'list', 'grid'];
$viewOption = isset($attributes['viewOptionValue']) ? sanitize_text_field((string)$attributes['viewOptionValue']) : 'table';

if (!in_array($viewOption, $allowed_views, true)) {
    $viewOption = 'table';
}

$eventData = [];
$metaDataLabel = isset($attributes['showMetaDataLabel']) && (bool)$attributes['showMetaDataLabel'];
$metaDataStatus = isset($attributes['showMetaDataStatus']) && (bool)$attributes['showMetaDataStatus'];
$showReservationInterface = !empty($attributes['showReservationInterface']);

$eventID = isset($attributes['eventId']) ? (int)$attributes['eventId'] : null;

// If reservation interface is enabled, handle differently
if ($showReservationInterface) {
    $isEditor = $events->is_block_editor_request();

    // Only show error in editor if no event ID is provided
    if (!$eventID) {
        if ($isEditor) {
            ?>
            <div <?php echo get_block_wrapper_attributes(['class' => 'ticketleo-reservation-error']); ?>>
                <div style="padding: 20px; border: 2px solid #d63638; text-align: center; background: #fef7f7;">
                    <p style="color: #d63638; margin: 0;"><strong><?php _e('Bitte geben Sie eine Event-ID ein', 'ticketleo-events'); ?></strong></p>
                </div>
            </div>
            <?php
        }
        return;
    }

    // Fetch event data to validate and extract slug
    $eventList = $events->fetchTicketleoEvent($eventID);

    // If API request failed or event not found, don't show anything
    if (!$eventList['success'] || empty($eventList['data'])) {
        // Show error only in editor
        if ($isEditor && !empty($eventList['message'])) {
            ?>
            <div <?php echo get_block_wrapper_attributes(['class' => 'ticketleo-reservation-error']); ?>>
                <div style="padding: 20px; border: 2px solid #d63638; text-align: center; background: #fef7f7;">
                    <p style="color: #d63638; margin: 0;">
                        <strong><?php echo esc_html($eventList['message']); ?></strong>
                    </p>
                </div>
            </div>
            <?php
        }
        return;
    }

    // Extract event slug from the first item's reservation link
    $eventSlug = '';
    if (!empty($eventList['data']) && is_array($eventList['data'])) {
        $firstEvent = reset($eventList['data']);

        if (isset($firstEvent->reservationLink)) {
            $link = explode('/', $firstEvent->reservationLink, 7);
            $linkParts = array_slice($link, 4, -1);

            if (count($linkParts) >= 2) {
                $eventSlug = $linkParts[1];
            }
        }
    }

    // If we can't get the slug, don't show the embed
    if (empty($eventSlug)) {
        if ($isEditor) {
            ?>
            <div <?php echo get_block_wrapper_attributes(['class' => 'ticketleo-reservation-error']); ?>>
                <div style="padding: 20px; border: 2px solid #d63638; text-align: center; background: #fef7f7;">
                    <p style="color: #d63638; margin: 0;">
                        <strong><?php _e('Event-Slug konnte nicht ermittelt werden', 'ticketleo-events'); ?></strong>
                    </p>
                </div>
            </div>
            <?php
        }
        return;
    }

    // Enqueue the Ticketleo embed script
    wp_enqueue_script('ticketleo-reservation-embed');
    ?>
    <div <?php echo get_block_wrapper_attributes(); ?>>
        <ticketleo-event event-id="<?php echo esc_attr($eventID); ?>" slug="<?php echo esc_attr($eventSlug); ?>"></ticketleo-event>
    </div>
    <?php
    return;
}

// Regular mode (non-reservation interface)
$eventList = $events->fetchTicketleoEvent($eventID);

if (!$eventList['success']) {
    // Show error message in the block editor if admin
    if ($events->is_block_editor_request() && !empty($eventList['message'])) {
        echo '<div class="error-message">' . esc_html($eventList['message']) . '</div>';
    }
    return null; // Do not output anything on the frontend if there's an error
}

$eventData['event'] = $eventList['data'];
?>
<?php if (!empty($eventData['event'])): ?>
    <div <?php echo get_block_wrapper_attributes(); ?>>
        <?php
        if ($metaDataLabel):
            $eventData['meta_data']['label'] = $metaDataLabel;
        endif;
        if ($metaDataStatus):
            $eventData['meta_data']['status'] = $metaDataStatus;
        endif;

        if ($eventList != null):
            switch($viewOption)
            {
                case 'list':
                    echo wp_kses_post($events->get_template('event/event-list', $eventData));
                    break;
                case 'grid':
                    echo wp_kses_post($events->get_template('event/event-grid', $eventData));
                    break;
                default:
                    echo wp_kses_post($events->get_template('event/event-table', $eventData));
            }
        else:
            return null;
        endif;
        ?>
    </div>
<?php endif; ?>