<?php
/* PAGES RENDERING FOR ADMIN SECTION */
defined( 'ABSPATH' ) or die( 'I cannot do anything when called directly good sir' );

 /**
 * SETUP PAGE
 *
 */
function eventit_events_options_page_html() {
    // check user capabilities
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }
    //Load the options
    $eventitOptions = get_option( 'eventit_events_options' );

    //Check if we already have working organizer setup
    $organizerDetails = eventit_events_getOrganizerDetails( 'da', $eventitOptions['eventit_events_field_organizerkey'] ?? '', $eventitOptions['eventit_events_field_passphrase'] ?? '' );

     // check if the user has submitted the settings
     if ( isset( $_GET['settings-updated'] ) ) {

        //Set wordpress confirmation update / error message. If we get $organizerDetails, the update will be successful.
        if ($organizerDetails) {
            $updateMessage = 'oplysningerne er korrekte og er nu gemt!';
            $updateType = 'updated';
        } else {
            $updateMessage = 'Oplysningerne er ikke korrekte. Kontroller API oplysningerne og prøv igen';
            $updateType = 'error';
            //New or updated settings are not valid. Clear organizer settings to prevent shortcode generation.
            delete_option( 'eventit_events_organizer_name' );
            delete_option( 'eventit_events_organizer_email' );
        }

        // add settings saved message with the class of "updated"
        add_settings_error( 'eventit_events_messages', 'eventit_events_message', __(  $updateMessage, 'eventit_events' ), $updateType );

        //New API values set, let's check if these are valid

        //Check if both values are set
        if ( ( $eventitOptions['eventit_events_field_organizerkey'] ?? '' ) != '' && ( $eventitOptions['eventit_events_field_passphrase'] ?? '' ) != '' ) {

            //If we get an organizer name back, then information is valid and we should save that info
            if ( $organizerDetails ) {

                $organizerName = (string) ( $organizerDetails['organizer-name'] ?? '' );
                $organizerEmail = (string) ( $organizerDetails['organizer-email'] ?? '' );

                if ( get_option('eventit_events_organizer_name') ) {
                    update_option( 'eventit_events_organizer_name', $organizerName );
                    update_option( 'eventit_events_organizer_email', $organizerEmail );
                } else {
                    add_option( 'eventit_events_organizer_name', $organizerName, '', 'yes' );
                    add_option( 'eventit_events_organizer_email', $organizerEmail, '', 'yes' );
                }
            }
        }
     }

     // show error/update messages
     settings_errors( 'eventit_events_messages' );

     //Connection status for the status notice below. Name/email comes from the live server response when available.
     $eventitHasCredentials = ( $eventitOptions['eventit_events_field_organizerkey'] ?? '' ) !== '' && ( $eventitOptions['eventit_events_field_passphrase'] ?? '' ) !== '';
     $eventitOrganizerName = $organizerDetails['organizer-name'] ?? get_option( 'eventit_events_organizer_name' );
     $eventitOrganizerEmail = $organizerDetails['organizer-email'] ?? get_option( 'eventit_events_organizer_email' );
     ?>

     <div class="wrap eventit-admin">
        <img class="eventit-admin-logo" src="<?php echo esc_url( EVENTIT_EVENTS_PLUGIN_URL . '/assets/img/event-IT-logo-black.png' ); ?>" alt="Event.it" />
        <h1>Opsætning</h1>

        <?php if ( $organizerDetails ) { ?>
        <div class="notice notice-success inline">
            <p>
                <b>&#10004; Forbundet til Event.it</b> &mdash; logget ind som <b><?php echo esc_html( $eventitOrganizerName ); ?></b><?php if ( $eventitOrganizerEmail ) { ?> (<?php echo esc_html( $eventitOrganizerEmail ); ?>)<?php } ?><br />
                Serveren har bekræftet dine API-oplysninger.
            </p>
        </div>
        <?php } elseif ( $eventitHasCredentials ) { ?>
        <div class="notice notice-error inline">
            <p><b>&#10008; Ikke forbundet</b> &mdash; dine API-oplysninger kunne ikke bekræftes hos Event.it. Kontroller din organizer key og passphrase og prøv igen.</p>
        </div>
        <?php } else { ?>
        <div class="notice notice-info inline">
            <p><b>Ikke forbundet</b> &mdash; indtast dine API-oplysninger nedenfor for at komme i gang.</p>
        </div>
        <?php } ?>

        <div class="eventit-admin-grid">
            <div class="eventit-card">
                <h2>API-oplysninger</h2>
                <p class="description"><?php esc_html_e( 'Indsæt din organizer key og passphrase. Du kan finde oplysningerne under API-menuen i Eventits administration.', 'eventit' ); ?></p>
                <form action="options.php" method="post">
                <?php
                // output security fields for the registered setting "eventit"
                settings_fields( 'eventit_events' );

                // output setting sections and their fields
                do_settings_sections( 'eventit_events' );

                // output save settings button
                submit_button( 'Gem indstillinger' );
                ?>
                </form>
            </div>

            <?php if ( get_option('eventit_events_organizer_name') ) { ?>
            <div class="eventit-card eventit-ready-panel">
                <img src="<?php echo esc_url( EVENTIT_EVENTS_PLUGIN_URL . '/assets/img/admin-check.png' ); ?>" alt="" />
                <h3>Du er klar til at vise dine events på hjemmesiden</h3>
                <h4>Events vises for: <b><?php echo esc_html( get_option('eventit_events_organizer_name') ); ?></b></h4>
                <p>Næste skridt er at bygge din shortcode, så du selv bestemmer hvilke events der vises og hvordan.</p>
                <p><a class="button button-primary" href="<?php echo esc_url( admin_url( 'admin.php?page=eventit-events-shortcode' ) ); ?>">Lav din shortcode</a></p>
            </div>
            <?php } ?>
        </div>
     </div>
 <?php
}

/**
 * SHORTCODE PAGE - helpers
 *
 */

/**
 * Example events used by the live preview. Same shape as the $ev array the
 * shortcode builds in includes/rendering/events.php.
 */
function eventit_events_preview_events( $eventitStyle ) {
    $usePalette = intval( $eventitStyle['color-theme'] ) === 1;

    $available = array(
        'title'        => 'Onsdagsevent - Håndbold',
        'description'  => 'En kort beskrivelse af eventet, som vises under titlen. Den kan være lidt længere end én linje.',
        'location'     => 'Musikhuset, Aarhus',
        'weekday'      => 'Onsdag',
        'day'          => '3',
        'month'        => 'juni',
        'month_short'  => 'jun',
        'time'         => '19:30',
        'categories'   => array(
            array( 'name' => 'Sport', 'color' => $usePalette ? 1 : 0 ),
            array( 'name' => 'Familie', 'color' => $usePalette ? 3 : 0 ),
        ),
        'accent'       => $usePalette ? array( 1, 3, 3 ) : array( 0, 0, 0 ),
        'info_url'     => '#',
        'info_label'   => 'Mere info',
        'buy_url'      => '#',
        'buy_label'    => 'Køb billetter',
        'buy_disabled' => false,
        'buy_state'    => 'available',
        'classes'      => 'eventstart1780000000 event-signup-open category-sport category-familie',
    );

    /* Sold out with an open waiting list. The label is the organizer's own text from
       Event.it ("sold-out-but-waitlist-open-label"), shown here so the colours and the
       longer wording can be checked before it goes live. */
    $waitlist = array_merge( $available, array(
        'title'        => 'Julekoncert',
        'description'  => 'Eventet er udsolgt, men gæster kan stadig skrive sig på ventelisten.',
        'weekday'      => 'Lørdag',
        'day'          => '24',
        'month'        => 'december',
        'month_short'  => 'dec',
        'time'         => '16:00',
        'categories'   => array( array( 'name' => 'Musik', 'color' => $usePalette ? 6 : 0 ) ),
        'accent'       => $usePalette ? array( 6, 6, 6 ) : array( 0, 0, 0 ),
        'buy_label'    => 'Udsolgt - tilmeld dig ventelisten',
        'buy_state'    => 'waitlist',
        'classes'      => 'eventstart1798700000 event-signup-open category-musik',
    ) );

    /* Sold out, no waiting list */
    $soldOut = array_merge( $available, array(
        'title'        => 'Foredrag: Kom godt i gang',
        'description'  => 'Alle pladser er optaget.',
        'location'     => 'Hovedbiblioteket',
        'weekday'      => 'Mandag',
        'day'          => '12',
        'month'        => 'januar',
        'month_short'  => 'jan',
        'time'         => '18:00',
        'categories'   => array( array( 'name' => 'Foredrag', 'color' => $usePalette ? 4 : 0 ) ),
        'accent'       => $usePalette ? array( 4, 4, 4 ) : array( 0, 0, 0 ),
        'buy_label'    => 'Udsolgt',
        'buy_disabled' => true,
        'buy_state'    => 'soldout',
        'classes'      => 'eventstart1799900000 event-signup-closed category-foredrag',
    ) );

    return array( $available, $waitlist, $soldOut );
}

/**
 * The preview markup - byte for byte the structure the shortcode outputs
 * (see includes/rendering/events.php), so nothing can drift between the two.
 */
function eventit_events_render_preview_markup( $eventitStyle, $layout = 'list', $columns = 0 ) {
    $events = eventit_events_preview_events( $eventitStyle );
    $boxed  = ( $layout === 'boxed' );

    /* $columns lets the preview show 2, 3 or 4 columns without changing the saved
       setting - the same thing columns="" on the shortcode does. */
    $columns = intval( $columns );
    if ( ! in_array( $columns, array( 2, 3, 4 ), true ) ) {
        $columns = intval( $eventitStyle['boxed-columns'] );
    }

    ob_start();
    ?>
<div>
    <div id="eventdetaillist" class="<?php echo esc_attr( eventit_events_style_classes( $eventitStyle ) ); ?>">
<?php if ( $boxed ) { ?>
        <div class="eventit-box-grid eventit-cols-<?php echo esc_attr( $columns ); ?>">
<?php foreach ( $events as $ev ) { include EVENTIT_EVENTS_PLUGIN_DIR . '/includes/rendering/boxedevent.php'; } ?>
        </div>
<?php } else { ?>
<?php foreach ( $events as $ev ) { include EVENTIT_EVENTS_PLUGIN_DIR . '/includes/rendering/compactevent.php'; } ?>
<?php } ?>
    </div>
    <div class="site-vertical-spacer"></div>
</div>
    <?php
    return ob_get_clean();
}

/**
 * A complete HTML document for the preview iframe.
 *
 * The preview is rendered in an iframe that loads exactly the same stylesheets as
 * the frontend (Bootstrap + flex.css + Font Awesome + the generated settings CSS).
 * That is what makes it match the live site 1:1 - wp-admin's own styling cannot
 * leak in, and no part of the grid has to be reimplemented for the admin screen.
 */
function eventit_events_render_preview_document( $eventitStyle, $layout = 'list', $columns = 0 ) {
    $cssUrl = EVENTIT_EVENTS_PLUGIN_URL . '/css/';

    ob_start();
    ?>
<!doctype html>
<html lang="da">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="<?php echo esc_url( $cssUrl . 'bootstrap.min.css' ); ?>" />
<link rel="stylesheet" href="<?php echo esc_url( $cssUrl . 'flex.css?ver=' . EVENTIT_EVENTS_VERSION ); ?>" />
<link rel="stylesheet" href="<?php echo esc_url( $cssUrl . 'fontawesome.min.css' ); ?>" />
<style><?php echo eventit_events_style_css( $eventitStyle ); ?></style>
<style>
/* Stand-in for the theme: on the live site the font and page background come from
   your WordPress theme, everything else below is the plugin's own styling. */
html, body { margin: 0; padding: 0; background: transparent; }
body { padding: 4px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.5; }
.site-vertical-spacer { height: 8px; }
a { cursor: default; }
</style>
</head>
<body><?php echo eventit_events_render_preview_markup( $eventitStyle, $layout, $columns ); ?>
<script>
/* This is a preview, not a live page. A srcdoc iframe inherits the parent's base
   URL, so an unguarded click would load wp-admin inside the frame - swallow all
   link clicks here. Hover effects keep working, which pointer-events would not. */
document.addEventListener('click', function (event) {
    var link = event.target && event.target.closest ? event.target.closest('a') : null;
    if (link) {
        event.preventDefault();
    }
}, true);
</script>
</body>
</html>
    <?php
    return ob_get_clean();
}

/* Form field renderers for the appearance form */
function eventit_events_field_color( $key, $eventitStyle, $hint = '' ) {
    $schema = eventit_events_style_schema();
    $field  = $schema[ $key ];
    $auto   = $field['type'] === 'hex-auto';
    ?>
    <div class="eventit-option-row" data-option="<?php echo esc_attr( $key ); ?>">
        <span class="eventit-option-label"><?php echo esc_html( $field['label'] ); ?><?php if ( $hint !== '' ) { ?><small><?php echo esc_html( $hint ); ?></small><?php } elseif ( $auto ) { ?><small>Tom = automatisk</small><?php } ?></span>
        <input type="text" class="eventit-color-field" id="eventit-opt-<?php echo esc_attr( $key ); ?>" name="eventit_events_shortcode_options[<?php echo esc_attr( $key ); ?>]" value="<?php echo esc_attr( $eventitStyle[ $key ] ); ?>"<?php if ( ! $auto ) { ?> data-default-color="<?php echo esc_attr( $field['default'] ); ?>"<?php } ?> />
    </div>
    <?php
}

function eventit_events_field_select( $key, $eventitStyle, $hint = '' ) {
    $schema = eventit_events_style_schema();
    $field  = $schema[ $key ];
    ?>
    <div class="eventit-option-row" data-option="<?php echo esc_attr( $key ); ?>">
        <label class="eventit-option-label" for="eventit-opt-<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $field['label'] ); ?><?php if ( $hint !== '' ) { ?><small><?php echo esc_html( $hint ); ?></small><?php } ?></label>
        <select id="eventit-opt-<?php echo esc_attr( $key ); ?>" name="eventit_events_shortcode_options[<?php echo esc_attr( $key ); ?>]">
            <?php foreach ( $field['options'] as $value => $label ) { ?>
            <option value="<?php echo esc_attr( $value ); ?>" <?php selected( strval( $eventitStyle[ $key ] ), strval( $value ) ); ?>><?php echo esc_html( $label ); ?></option>
            <?php } ?>
        </select>
    </div>
    <?php
}

function eventit_events_field_range( $key, $eventitStyle, $unit = 'px', $hint = '' ) {
    $schema = eventit_events_style_schema();
    $field  = $schema[ $key ];
    ?>
    <div class="eventit-option-row" data-option="<?php echo esc_attr( $key ); ?>">
        <label class="eventit-option-label" for="eventit-opt-<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $field['label'] ); ?><?php if ( $hint !== '' ) { ?><small><?php echo esc_html( $hint ); ?></small><?php } ?></label>
        <span class="eventit-range-wrap">
            <input type="range" id="eventit-opt-<?php echo esc_attr( $key ); ?>" name="eventit_events_shortcode_options[<?php echo esc_attr( $key ); ?>]" min="<?php echo esc_attr( $field['min'] ); ?>" max="<?php echo esc_attr( $field['max'] ); ?>" step="1" value="<?php echo esc_attr( $eventitStyle[ $key ] ); ?>" />
            <output for="eventit-opt-<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $eventitStyle[ $key ] ); ?></output><?php echo esc_html( $unit ); ?>
        </span>
    </div>
    <?php
}

/**
 * SHORTCODE PAGE
 *
 */
function eventit_events_styling_page_html() {
    // check user capabilities
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $eventitSaveNotice = '';
    $validateErrors    = array();

    /* Handle submission */
    if ( ! empty( $_POST ) && isset( $_POST['eventit_events_shortcode_nonce'] ) ) {
        if ( ! wp_verify_nonce( $_POST['eventit_events_shortcode_nonce'], 'eventit_events_shortcode_form_action' ) ) {
            wp_die( 'Something went wrong with this submission.<br>Error: nonce did not verify.' );
        }

        if ( isset( $_POST['eventit_events_reset'] ) ) {
            /* Reset to defaults */
            update_option( 'eventit_events_shortcode_options', eventit_events_style_defaults() );
            $eventitSaveNotice = 'Indstillingerne er nulstillet til standard.';
        } else {
            $raw   = isset( $_POST['eventit_events_shortcode_options'] ) && is_array( $_POST['eventit_events_shortcode_options'] ) ? $_POST['eventit_events_shortcode_options'] : array();
            $clean = eventit_events_sanitize_style_options( $raw, false );

            if ( empty( $clean['errors'] ) ) {
                update_option( 'eventit_events_shortcode_options', $clean['options'] );
                $eventitSaveNotice = 'Indstillingerne er gemt.';
            } else {
                $validateErrors = $clean['errors'];
            }
        }
    }

    /* Current (saved + defaults) appearance options */
    $eventitStyle = eventit_events_get_style_options();

    ?>

    <div class="wrap eventit-admin">
        <img class="eventit-admin-logo" src="<?php echo esc_url( EVENTIT_EVENTS_PLUGIN_URL . '/assets/img/event-IT-logo-black.png' ); ?>" alt="Event.it" />
        <h1>Styling</h1>

        <?php if ( ! empty( $validateErrors ) ) { ?>
        <div class="notice notice-error inline">
            <p><b>Indstillingerne blev ikke gemt:</b></p>
            <ul>
                <?php foreach ( $validateErrors as $validateError ) { ?>
                <li><?php echo esc_html( $validateError ); ?></li>
                <?php } ?>
            </ul>
        </div>
        <?php } elseif ( $eventitSaveNotice !== '' ) { ?>
        <div class="notice notice-success inline">
            <p><?php echo esc_html( $eventitSaveNotice ); ?></p>
        </div>
        <?php } ?>

        <!-- LIVE PREVIEW -->
        <div class="eventit-card eventit-preview-card">
            <div class="eventit-preview-head">
                <div>
                    <h2>Forhåndsvisning</h2>
                    <p class="description">Vises med de samme stylesheets som på dit website, så det matcher 1:1. Skrifttype og sidebaggrund kommer fra dit tema. Ændringer nedenfor vises med det samme &ndash; husk at gemme.</p>
                </div>
                <div class="eventit-preview-tools">
                    <div class="eventit-preview-widths eventit-preview-layouts">
                        <button type="button" class="button eventit-preview-layout is-active" data-layout="list" data-columns="0">Fuld bredde</button>
                        <?php foreach ( array( 2, 3, 4 ) as $previewCols ) {
                            $isDefault = ( intval( $eventitStyle['boxed-columns'] ) === $previewCols );
                            ?>
                        <button type="button" class="button eventit-preview-layout<?php echo $isDefault ? ' is-default' : ''; ?>" data-layout="boxed" data-columns="<?php echo esc_attr( $previewCols ); ?>"<?php echo $isDefault ? ' title="Din standard for shortcodes uden columns-attribut"' : ''; ?>>Box <?php echo esc_html( $previewCols ); ?> kol.</button>
                        <?php } ?>
                    </div>
                    <div class="eventit-preview-widths">
                        <button type="button" class="button eventit-preview-width is-active" data-width="1280">Desktop</button>
                        <button type="button" class="button eventit-preview-width" data-width="820">Tablet</button>
                        <button type="button" class="button eventit-preview-width" data-width="390">Mobil</button>
                    </div>
                    <span class="eventit-preview-scale" id="eventit-preview-scale"></span>
                    <label class="eventit-preview-bg-toggle"><input type="checkbox" id="eventit-preview-dark" /> Mørk baggrund</label>
                </div>
            </div>
            <div class="eventit-preview">
                <!-- The frame renders at a real device width and is scaled down to fit,
                     so the responsive breakpoints behave exactly as on the live site. -->
                <div class="eventit-preview-stage" id="eventit-preview-stage">
                    <iframe id="eventit-preview-frame" class="eventit-preview-frame" title="Forhåndsvisning af events"
                            srcdoc="<?php echo esc_attr( eventit_events_render_preview_document( $eventitStyle, 'list', 0 ) ); ?>"></iframe>
                </div>
            </div>
        </div>

        <div class="eventit-styling-form">

            <!-- APPEARANCE FORM -->
            <div class="eventit-card">
                <h2>Udseende for alle shortcodes</h2>
                <p class="description">Udseendet gælder alle steder, hvor dine events vises. Klik på en sektion for at folde den ud.</p>

                <form id="eventit-style-form" action="<?php echo esc_url( admin_url( 'admin.php?page=eventit-events-styling' ) ); ?>" method="post">
                <?php wp_nonce_field( 'eventit_events_shortcode_form_action', 'eventit_events_shortcode_nonce' ); ?>

                <details class="eventit-section" open>
                    <summary>Farvetema</summary>
                    <div class="eventit-section-body">
                        <?php eventit_events_field_select( 'color-theme', $eventitStyle ); ?>
                        <?php eventit_events_field_color( 'accent-color', $eventitStyle, 'Bruges på datoblok, stribe og kategori-tags. Tom = temaets egen farve' ); ?>
                        <p class="description eventit-theme-hint" data-theme="1">Hver kategori får sin egen farve, som du har sat den i Event.it. Derfor er der ingen hovedfarve at vælge her. Vil du selv bestemme farverne, kan du sætte datoblok- og tag-farverne nedenfor &ndash; de gælder så alle events uanset kategori.</p>
                        <p class="description eventit-theme-hint" data-theme="0">Alle events får samme farve &ndash; den du vælger som hovedfarve. Lader du hovedfarven stå tom, bruges neutrale grå toner. Den lyse variant til datoblokken beregnes automatisk.</p>
                        <p class="description eventit-theme-hint" data-theme="3">Mørke kort med lys tekst. Vælg en lys hovedfarve, så den står tydeligt.</p>
                    </div>
                </details>

                <details class="eventit-section">
                    <summary>Kort</summary>
                    <div class="eventit-section-body">
                        <?php eventit_events_field_color( 'card-background', $eventitStyle ); ?>
                        <?php eventit_events_field_color( 'card-border-color', $eventitStyle ); ?>
                        <?php eventit_events_field_select( 'card-border-width', $eventitStyle ); ?>
                        <?php eventit_events_field_select( 'card-shadow', $eventitStyle ); ?>
                        <?php eventit_events_field_select( 'card-hover', $eventitStyle ); ?>
                        <?php eventit_events_field_range( 'card-radius', $eventitStyle ); ?>
                        <?php eventit_events_field_select( 'card-spacing', $eventitStyle ); ?>
                        <?php eventit_events_field_select( 'card-padding', $eventitStyle ); ?>
                    </div>
                </details>

                <details class="eventit-section">
                    <summary>Datoblok</summary>
                    <div class="eventit-section-body">
                        <?php eventit_events_field_select( 'date-style', $eventitStyle ); ?>
                        <?php eventit_events_field_color( 'date-background', $eventitStyle, 'Tom = følger temaet/kategorien' ); ?>
                        <?php eventit_events_field_color( 'date-text-color', $eventitStyle, 'Tom = følger temaet/kategorien' ); ?>
                    </div>
                </details>

                <details class="eventit-section">
                    <summary>Kategori-tags</summary>
                    <div class="eventit-section-body">
                        <?php eventit_events_field_select( 'tag-show', $eventitStyle ); ?>
                        <?php eventit_events_field_select( 'tag-shape', $eventitStyle ); ?>
                        <?php eventit_events_field_color( 'tag-color', $eventitStyle, 'Tom = følger temaet/kategorien' ); ?>
                    </div>
                </details>

                <details class="eventit-section">
                    <summary>Tekst</summary>
                    <div class="eventit-section-body">
                        <?php eventit_events_field_select( 'title-size', $eventitStyle ); ?>
                        <?php eventit_events_field_select( 'title-weight', $eventitStyle ); ?>
                        <?php eventit_events_field_color( 'title-color', $eventitStyle ); ?>
                        <?php eventit_events_field_color( 'text-color', $eventitStyle ); ?>
                        <?php eventit_events_field_select( 'desc-lines', $eventitStyle, 'Maks. 2 linjer giver ens højde i box-visning' ); ?>
                        <?php eventit_events_field_select( 'button-uppercase', $eventitStyle ); ?>
                    </div>
                </details>

                <details class="eventit-section">
                    <summary>Knapper</summary>
                    <div class="eventit-section-body">
                        <?php eventit_events_field_select( 'button-style', $eventitStyle, 'Ved outline/link bruges baggrundsfarven som kant- og tekstfarve' ); ?>
                        <?php eventit_events_field_select( 'button-size', $eventitStyle ); ?>
                        <?php eventit_events_field_range( 'button-radius', $eventitStyle ); ?>
                        <?php eventit_events_field_select( 'button-hover', $eventitStyle ); ?>
                        <?php eventit_events_field_color( 'button-info-background', $eventitStyle ); ?>
                        <?php eventit_events_field_color( 'button-info-font-color', $eventitStyle ); ?>
                        <?php eventit_events_field_color( 'button-buy-background', $eventitStyle ); ?>
                        <?php eventit_events_field_color( 'button-buy-font-color', $eventitStyle ); ?>
                        <?php eventit_events_field_color( 'button-waitlist-background', $eventitStyle, 'Tom = samme som køb-knappen' ); ?>
                        <?php eventit_events_field_color( 'button-waitlist-font-color', $eventitStyle, 'Tom = samme som køb-knappen' ); ?>
                        <p class="description">Er et event udsolgt med åben venteliste, viser knappen arrangørens venteliste-tekst fra Event.it og er stadig klikbar.</p>
                    </div>
                </details>

                <details class="eventit-section">
                    <summary>Box-visning</summary>
                    <div class="eventit-section-body">
                        <?php eventit_events_field_select( 'boxed-columns', $eventitStyle, 'Standard for shortcodes uden columns-attribut' ); ?>
                        <p class="description">På tablet vises højst 2 kolonner og på mobil 1 kolonne. Slå "Maks. 2 linjer" til under Tekst for ens højde på boksene.</p>
                    </div>
                </details>

                <details class="eventit-section">
                    <summary>Avanceret</summary>
                    <div class="eventit-section-body">
                        <label for="eventit-opt-custom-css"><b>Egen CSS</b></label>
                        <p class="description">Indlæses efter pluginets stylesheet. Alle events ligger i <code>#eventdetaillist</code>; hvert kort har klassen <code>.eventit-compact-wrap</code> (liste) eller <code>.eventit-box-wrapper</code> (box). Du kan også overstyre variabler, fx <code>#eventdetaillist { --eventit-radius: 20px; }</code>.</p>
                        <textarea id="eventit-opt-custom-css" name="eventit_events_shortcode_options[custom-css]" rows="8" class="large-text code" spellcheck="false"><?php echo esc_textarea( $eventitStyle['custom-css'] ); ?></textarea>
                    </div>
                </details>

                <div class="eventit-form-actions">
                    <?php submit_button( 'Gem indstillinger', 'primary', 'submit', false ); ?>
                    <button type="submit" name="eventit_events_reset" value="1" class="button button-link-delete eventit-reset-button">Nulstil til standard</button>
                </div>
                </form>
            </div>

        </div>
    </div>
<?php
}

/**
 * SHORTCODE BUILDER PAGE ("Lav shortcode")
 *
 * Picks specific events and/or categories and assembles the shortcode. Nothing is
 * stored: the page only produces a shortcode string, so a selection lives on the
 * page where it is pasted. Event keys that later disappear (deleted or finished
 * events) simply stop matching and drop out of the list by themselves.
 */
function eventit_events_shortcode_builder_page_html() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $eventitStyle    = eventit_events_get_style_options();
    $eventitOptions  = get_option( 'eventit_events_options' );
    $organizerKey    = $eventitOptions['eventit_events_field_organizerkey'] ?? '';
    $organizerPhrase = $eventitOptions['eventit_events_field_passphrase'] ?? '';

    $organizerDetails = eventit_events_getOrganizerDetails( 'da', $organizerKey, $organizerPhrase );

    $shortcodeCategories = array();
    $pickableEvents      = array();
    $pastEventCount      = 0;

    if ( $organizerDetails ) {
        $eventList = eventit_events_getEvents( 'da', $organizerKey, false, $organizerPhrase );

        if ( is_object( $eventList ) ) {
            $shortcodeCategories = eventit_events_getCategoryList( $eventList );
            $now                 = time();

            for ( $i = 0; $i < $eventList->getNumberOfEvents(); $i++ ) {
                $event = $eventList->getEvent( $i );
                if ( $event->getStateKey() !== 'PublishedMode' ) {
                    continue;
                }

                $startStamp = strtotime( (string) $event->getEventStart() );
                $isPast     = ( $startStamp && $startStamp < $now );
                if ( $isPast ) {
                    $pastEventCount++;
                }

                $categoryNames = array();
                $categoryList  = $event->eventit_events_getCategoryList();
                if ( is_array( $categoryList ) ) {
                    foreach ( $categoryList as $category ) {
                        $name = trim( (string) ( $category['display-name'] ?? '' ) );
                        if ( $name !== '' ) {
                            $categoryNames[] = $name;
                        }
                    }
                }

                $dateParts = eventit_events_getDateParts( $event->getEventStart(), 'da' );

                $pickableEvents[] = array(
                    'key'        => (string) $event->getEventKey(),
                    'name'       => (string) $event->getEventName(),
                    'day'        => $dateParts['day'],
                    'month'      => $dateParts['month_short'],
                    'year'       => $dateParts['year'],
                    'weekday'    => $dateParts['weekday'],
                    'time'       => $dateParts['time'],
                    'location'   => ( $event->getLocationName() === '-' ? '' : trim( (string) $event->getLocationName() ) ),
                    'categories' => $categoryNames,
                    'past'       => $isPast,
                    'stamp'      => $startStamp ? $startStamp : 0,
                );
            }

            /* Soonest first, so the relevant ones are at the top */
            usort( $pickableEvents, function ( $a, $b ) {
                return $a['stamp'] <=> $b['stamp'];
            } );
        }
    }

    $upcomingCount = count( $pickableEvents ) - $pastEventCount;
    ?>

    <div class="wrap eventit-admin">
        <img class="eventit-admin-logo" src="<?php echo esc_url( EVENTIT_EVENTS_PLUGIN_URL . '/assets/img/event-IT-logo-black.png' ); ?>" alt="Event.it" />
        <h1>Lav shortcode</h1>

        <?php if ( ! $organizerDetails ) { ?>
        <div class="notice notice-warning inline">
            <p>Du er ikke forbundet til Event.it, så dine events kan ikke hentes. <a href="<?php echo esc_url( admin_url( 'admin.php?page=eventit_events' ) ); ?>">Gå til Opsætning</a> og indtast dine API-oplysninger.</p>
        </div>
        <?php } ?>

        <div class="eventit-builder-layout">

            <!-- CHOICES -->
            <div class="eventit-builder-main">

                <div class="eventit-card">
                    <div class="eventit-card-head">
                        <div>
                            <h2>Vælg events</h2>
                            <p class="description">Vælg ikke noget, og shortcoden viser <b>alle</b> dine events automatisk. Vælg bestemte events, hvis siden kun skal vise et fast udvalg.</p>
                        </div>
                        <span class="eventit-pick-counter" id="eventit-pick-counter">Alle events</span>
                    </div>

                    <?php if ( ! empty( $pickableEvents ) ) { ?>
                    <div class="eventit-picker-toolbar">
                        <input type="search" id="eventit-event-search" class="eventit-search" placeholder="Søg i dine events&hellip;" autocomplete="off" />
                        <div class="eventit-picker-actions">
                            <button type="button" class="button-link eventit-pick-none">Ryd valg</button>
                            <?php if ( $pastEventCount > 0 ) { ?>
                            <label class="eventit-show-past"><input type="checkbox" id="eventit-show-past" /> Vis afholdte (<?php echo esc_html( $pastEventCount ); ?>)</label>
                            <?php } ?>
                        </div>
                    </div>

                    <div class="eventit-event-list" id="eventit-event-list">
                        <?php foreach ( $pickableEvents as $pickEvent ) { ?>
                        <label class="eventit-event-row<?php echo $pickEvent['past'] ? ' is-past' : ''; ?>"
                               data-search="<?php echo esc_attr( eventit_events_strtolower( $pickEvent['name'] . ' ' . $pickEvent['location'] . ' ' . implode( ' ', $pickEvent['categories'] ) ) ); ?>"
                               data-past="<?php echo $pickEvent['past'] ? '1' : '0'; ?>">
                            <input type="checkbox" class="eventit-event-checkbox" value="<?php echo esc_attr( $pickEvent['key'] ); ?>" />
                            <span class="eventit-event-date">
                                <span class="eventit-event-day"><?php echo esc_html( $pickEvent['day'] ); ?></span>
                                <span class="eventit-event-month"><?php echo esc_html( $pickEvent['month'] ); ?></span>
                            </span>
                            <span class="eventit-event-main">
                                <span class="eventit-event-name"><?php echo esc_html( $pickEvent['name'] ); ?></span>
                                <span class="eventit-event-meta">
                                    <?php echo esc_html( ucfirst( $pickEvent['weekday'] ) . ' ' . $pickEvent['day'] . '. ' . $pickEvent['month'] . ' ' . $pickEvent['year'] ); ?>
                                    <?php if ( $pickEvent['time'] !== '' ) { ?>&middot; <?php echo esc_html( $pickEvent['time'] ); ?><?php } ?>
                                    <?php if ( $pickEvent['location'] !== '' ) { ?>&middot; <?php echo esc_html( $pickEvent['location'] ); ?><?php } ?>
                                </span>
                            </span>
                            <span class="eventit-event-tags">
                                <?php foreach ( $pickEvent['categories'] as $categoryName ) { ?>
                                <span class="eventit-event-tag"><?php echo esc_html( $categoryName ); ?></span>
                                <?php } ?>
                                <?php if ( $pickEvent['past'] ) { ?><span class="eventit-event-tag is-past-tag">Afholdt</span><?php } ?>
                            </span>
                        </label>
                        <?php } ?>
                        <p class="eventit-no-hits" id="eventit-no-hits">Ingen events matcher din søgning.</p>
                    </div>
                    <p class="description">Viser <?php echo esc_html( $upcomingCount ); ?> kommende event<?php echo $upcomingCount === 1 ? '' : 's'; ?>. Bliver et valgt event slettet eller afholdt, forsvinder det stille fra siden &ndash; resten vises videre.</p>

                    <?php } elseif ( $organizerDetails ) { ?>
                    <p class="description"><i>Ingen offentliggjorte events fundet på din konto endnu.</i></p>
                    <?php } ?>
                </div>

                <div class="eventit-card">
                    <h2>Eller filtrér på kategori</h2>
                    <p class="description">Bruges når siden skal følge med automatisk: nye events i de valgte kategorier dukker op af sig selv. <b>Vælger du bestemte events ovenfor, bruges de i stedet for kategorierne.</b></p>

                    <?php if ( ! empty( $shortcodeCategories ) ) { ?>
                    <div class="eventit-category-list">
                        <?php foreach ( $shortcodeCategories as $categoryKey => $categoryName ) { ?>
                        <label class="eventit-category-option">
                            <input type="checkbox" class="eventit-category-checkbox" value="<?php echo esc_attr( $categoryKey ); ?>" />
                            <?php echo esc_html( trim( (string) $categoryName ) !== '' ? $categoryName : $categoryKey ); ?>
                        </label>
                        <?php } ?>
                    </div>
                    <?php } else { ?>
                    <p class="description"><i>Ingen kategorier fundet endnu.</i></p>
                    <?php } ?>
                </div>

                <div class="eventit-card">
                    <h2>Layout</h2>
                    <p class="description">Farver og udseende styres samlet under <a href="<?php echo esc_url( admin_url( 'admin.php?page=eventit-events-styling' ) ); ?>">Styling</a>. Her vælger du kun, hvordan netop denne shortcode sætter dine events op.</p>

                    <div class="eventit-option-row">
                        <label class="eventit-option-label" for="eventit-choose-view-type">Visningstype</label>
                        <select id="eventit-choose-view-type">
                            <option value="0" selected>Fuld bredde</option>
                            <option value="1">Box visning</option>
                        </select>
                    </div>

                    <div class="eventit-option-row" id="eventit-builder-columns" style="display:none;">
                        <label class="eventit-option-label" for="eventit-choose-columns">Kolonner</label>
                        <select id="eventit-choose-columns">
                            <option value="" selected>Brug standard (<?php echo esc_html( $eventitStyle['boxed-columns'] ); ?>)</option>
                            <option value="2">2 kolonner</option>
                            <option value="3">3 kolonner</option>
                            <option value="4">4 kolonner</option>
                        </select>
                    </div>

                    <p class="description">Dine events bør altid indsættes i en fuld bredde-række på din side.</p>
                </div>
            </div>

            <!-- RESULT -->
            <div class="eventit-builder-side">
                <div class="eventit-card eventit-result-card">
                    <h2>Din shortcode</h2>
                    <p class="description">Kopier og indsæt på den side, hvor dine events skal vises.</p>

                    <div class="eventit-shortcode-output">
                        <code id="eventit-show-shortcode">[eventit-events]</code>
                    </div>
                    <button type="button" class="button button-primary eventit-copy-shortcode">Kopier shortcode</button>
                    <span class="eventit-copy-feedback">Kopieret!</span>

                    <ul class="eventit-result-summary" id="eventit-result-summary"></ul>
                </div>
            </div>

        </div>
    </div>
<?php
}
