<?php
/**
 * Event list rendering (shortcode output).
 *
 * Expects from the shortcode handler:
 *   $eventitShortcodeAttributes  (categories[], boxed, columns)
 *   $uriObject, $eventitPassPhrase, $currentLocale, $siteTheme
 *
 * Each event is normalised into an $ev array and handed to
 * compactevent.php / boxedevent.php. The admin live preview renders the same
 * templates with a fake $ev, so keep everything template-relevant in $ev.
 */
defined( 'ABSPATH' ) or die( 'I cannot do anything when called directly good sir' );

/* locale is not dynamic as of 1.0.0 */
$urlLocalePostfix = 'da';
$userIsManagerOnThisOrganizer = false;

$eventList    = eventit_events_getEvents( $currentLocale, $uriObject->getOrganizerKey(), false, $eventitPassPhrase );
$eventitStyle = eventit_events_get_style_options();

if ( ! is_object( $eventList ) ) {
    echo '<div class="eventit-error">' . esc_html__( 'No event data available.', 'eventit' ) . '</div>';
    return;
}

$isBoxed = ! empty( $eventitShortcodeAttributes['boxed'] );
$columns = intval( $eventitShortcodeAttributes['columns'] ?? 0 );
if ( ! in_array( $columns, array( 2, 3, 4 ), true ) ) {
    $columns = intval( $eventitStyle['boxed-columns'] );
}
$filterCategories = is_array( $eventitShortcodeAttributes['categories'] ?? null ) ? $eventitShortcodeAttributes['categories'] : array();
$filterEvents     = is_array( $eventitShortcodeAttributes['events'] ?? null ) ? $eventitShortcodeAttributes['events'] : array();
$usePalette = intval( $eventitStyle['color-theme'] ) === 1;

/* Category key => colour index (Eventit palette) */
$allEventCategoriesColor = eventit_events_getCategoryColorMap( $eventList );

$renderedEvents = 0;
?>
<div>
    <div id="eventdetaillist" class="<?php echo esc_attr( eventit_events_style_classes( $eventitStyle ) ); ?>">
<?php if ( $isBoxed ) { ?>
        <div class="eventit-box-grid eventit-cols-<?php echo esc_attr( $columns ); ?>">
<?php } ?>
<?php
for ( $i = 0; $i < $eventList->getNumberOfEvents(); $i++ ) {
    $event    = $eventList->getEvent( $i );
    $stateKey = $event->getStateKey();

    $renderThisEvent = ( $stateKey === 'PublishedMode' ) || ( $stateKey === 'TestMode' && $userIsManagerOnThisOrganizer );
    if ( ! $renderThisEvent ) {
        continue;
    }

    /* Categories on this event */
    $eventCategoryList = $event->eventit_events_getCategoryList();
    if ( ! is_array( $eventCategoryList ) ) {
        $eventCategoryList = array();
    }

    /* Shortcode event filter. An explicit list of events wins over the category
       filter. A page pinned to specific events should not keep showing them once
       they are over, so finished events are dropped here as well - deleted ones
       already fall out because their key is no longer in the feed. Events that are
       merely listed (no events="") stay governed by the visibility window the
       organizer set in Event.it. */
    if ( ! empty( $filterEvents ) ) {
        if ( ! in_array( (string) $event->getEventKey(), $filterEvents, true ) ) {
            continue;
        }
        if ( eventit_events_hasFinished( $event ) ) {
            continue;
        }
    } elseif ( ! empty( $filterCategories ) ) {
        $match = false;
        foreach ( $eventCategoryList as $category ) {
            if ( in_array( (string) ( $category['external-key'] ?? '' ), $filterCategories, true ) ) {
                $match = true;
                break;
            }
        }
        if ( ! $match ) {
            continue;
        }
    }

    /* ---- Register button: state and label come straight from the API ---- */
    $ticketState           = eventit_events_resolveTicketState( $event, $currentLocale, $siteTheme );
    $availableTicketsClass = $ticketState['disabled'] ? 'event-signup-closed' : 'event-signup-open';

    /* ---- Categories + colour indices ---- */
    $categories   = array();
    $categoryKeys = array();
    foreach ( $eventCategoryList as $category ) {
        $key  = (string) ( $category['external-key'] ?? '' );
        $name = trim( (string) ( $category['display-name'] ?? '' ) );
        if ( $key !== '' ) {
            $categoryKeys[] = $key;
        }
        if ( $name === '' ) {
            continue;
        }
        $categories[] = array(
            'name'  => $name,
            /* Index 0 means "no colour of its own" and resolves to the theme's own
               colour in flex.css, rather than repeating a hard-coded shade here. */
            'color' => ( $usePalette && isset( $allEventCategoriesColor[ $key ] ) ) ? $allEventCategoriesColor[ $key ] : 0,
        );
    }

    /* Accent indices for the date block (up to three categories colour the three cells) */
    if ( $usePalette ) {
        $accent = array();
        foreach ( $categoryKeys as $key ) {
            if ( isset( $allEventCategoriesColor[ $key ] ) ) {
                $accent[] = $allEventCategoriesColor[ $key ];
            }
        }
        if ( empty( $accent ) ) {
            /* No category at all: index 0 means "no colour of its own" and resolves to
               var(--eventit-accent) / var(--eventit-accent-soft) in flex.css. On this
               theme those always hold the palette's own colours - the main colour
               setting is hidden and ignored here, because the categories own the
               colour - so this renders identically to the old hard-coded index 1,
               without repeating that number. */
            $accent = array( 0 );
        }
        $accent = array( $accent[0], $accent[1] ?? $accent[0], $accent[2] ?? ( $accent[1] ?? $accent[0] ) );
    } else {
        $accent = array( 0, 0, 0 );
    }

    /* ---- Filter / state classes on the card ---- */
    $cardClasses = array( 'eventstart' . strtotime( (string) $event->getEventStart() ), $availableTicketsClass );
    foreach ( $categoryKeys as $key ) {
        $cardClasses[] = 'category-' . sanitize_html_class( $key );
    }

    $dateParts = eventit_events_getDateParts( $event->getEventStart(), $currentLocale );
    $location  = trim( (string) $event->getLocationName() );
    if ( $location === '-' ) {
        $location = '';
    }

    $infoLabel = trim( (string) $event->getLabelButtonMore() );
    if ( $infoLabel === '' ) {
        $infoLabel = eventit_events_localize( 'button_more_info', $currentLocale );
    }

    $eventBaseUrl = EVENTIT_EVENTS_URL . rawurlencode( (string) $event->getOrganizerKey() ) . '/event/' . rawurlencode( (string) $event->getEventKey() );

    $ev = array(
        'title'        => (string) $event->getEventName(),
        'description'  => (string) $event->getEventShortDescription(),
        'location'     => $location,
        'weekday'      => $dateParts['weekday'],
        'day'          => $dateParts['day'],
        'month'        => $dateParts['month'],
        'month_short'  => $dateParts['month_short'],
        'time'         => $dateParts['time'],
        'categories'   => $categories,
        'accent'       => $accent,
        'info_url'     => $eventBaseUrl . '/l/' . $urlLocalePostfix,
        'info_label'   => $infoLabel,
        'buy_url'      => $eventBaseUrl . '/register/l/' . $urlLocalePostfix,
        'buy_label'    => (string) $ticketState['label'],
        'buy_disabled' => (bool) $ticketState['disabled'],
        'buy_state'    => $ticketState['state'],
        'classes'      => implode( ' ', $cardClasses ),
    );

    $renderedEvents++;
    include __DIR__ . ( $isBoxed ? '/boxedevent.php' : '/compactevent.php' );
}
?>
<?php if ( $isBoxed ) { ?>
        </div>
<?php } ?>
<?php if ( $renderedEvents == 0 ) { ?>
        <div class="row no-gutters panel-theme content-panel no-loaded-events">
            <div class="col-xs-12">
                <div class="site-organizer-frontpage-text"><h3><?php echo esc_html( eventit_events_localize( 'no_events_header', $currentLocale ) ); ?></h3><?php echo esc_html( eventit_events_localize( 'no_events_text', $currentLocale ) ); ?></div>
            </div>
        </div>
<?php } ?>
    </div>
    <div class="site-vertical-spacer"></div>
</div>
