<?php
defined( 'ABSPATH' ) or die( 'I cannot do anything when called directly good sir' );

/**
 * custom option and settings
 *
 */

function eventit_events_sanitize( $args ) {
    $sanitized_input = array();
    if( isset( $args['eventit_events_field_organizerkey'] ) )
        $sanitized_input['eventit_events_field_organizerkey'] = sanitize_text_field( $args['eventit_events_field_organizerkey'] );

    if( isset( $args['eventit_events_field_passphrase'] ) )
            $sanitized_input['eventit_events_field_passphrase'] = sanitize_text_field( $args['eventit_events_field_passphrase'] );

    return $sanitized_input; 
}

// API section callback
function eventit_events_section_api_cb( $args ) { }

// Shortcode section
function eventit_events_section_shortcode_cb( $args ) { }
 
/* Callback for input fields */
function eventit_events_field_input_cb( $args ) {
    $options = get_option( 'eventit_events_options' );
    ?>
    <input type="text"
           id="<?php echo esc_attr( $args['label_for'] ); ?>"
           data-custom="<?php echo esc_attr( $args['eventit_custom_data'] ); ?>"
           name="eventit_events_options[<?php echo esc_attr( $args['label_for'] ); ?>]"
           value="<?php echo isset( $options[ $args['label_for'] ] ) ? esc_attr( $options[ $args['label_for'] ] ) : ''; ?>"
    />
    <p class="description"><?php echo esc_html( $args['eventit_description'] ); ?></p>
    <?php
}

/* Fetch organizer details - used for validating api credentials */
function eventit_events_getOrganizerDetails( $a_localekey, $a_organizerkey, $a_passphrase ) {

    $base = 'https://app.event.it/organizerservices/api/v1/organizerdetails';

    $query = array(
        'characterset' => 'UTF-8',
        'format'       => 'json',
        'localekey'    => $a_localekey,
        'organizerkey' => $a_organizerkey,
    );
    $url  = add_query_arg( $query, $base );

    $args = array(
        'headers' => array(
            'Authorization' => 'Basic ' . base64_encode( $a_organizerkey . ':' . $a_passphrase ),
            'Accept'        => 'application/json',
        ),
        'timeout'   => 20,
        'sslverify' => true,
    );

    $response = wp_remote_get( $url, $args );
    if ( is_wp_error( $response ) ) {
        return false;
    }

    $code = intval( wp_remote_retrieve_response_code( $response ) );
    if ( $code < 200 || $code >= 300 ) {
        return false;
    }

    $body = wp_remote_retrieve_body( $response );
    if ( $body === '' || $body === null ) {
        return false;
    }

    // If the server unexpectedly returns XML, you can keep a minimal fallback.
    $trimmed = ltrim( $body );
    if ( $trimmed !== '' && isset( $trimmed[0] ) && $trimmed[0] === '<' ) {
        // Optional: try to parse XML then convert to an array (kept for compatibility)
        if ( function_exists( 'simplexml_load_string' ) ) {
            libxml_use_internal_errors( true );
            $xml = simplexml_load_string( $body );
            if ( $xml !== false ) {
                $arr = json_decode( json_encode( $xml ), true );
                return !empty( $arr ) ? $arr : false;
            }
        }
        return false;
    }

    // Decode JSON
    $data = json_decode( $body, true );
    if ( $data === null && function_exists( 'json_last_error' ) && json_last_error() !== JSON_ERROR_NONE ) {
        return false;
    }

    // Basic sanity checks: treat empty payloads as invalid
    if ( empty( $data ) ) {
        return false;
    }

    // Wrong credentials give a 401 (caught above); a valid response carries
    // the organizer details under the "organizer-details" key.
    $details = $data['organizer-details'] ?? null;
    if ( ! is_array( $details ) || ( $details['organizer-name'] ?? '' ) === '' ) {
        return false;
    }

    // Success: return the organizer details (truthy, with top-level organizer-name/-email)
    return $details;
}



/* List events for organizer */
function eventit_events_list_events ( $atts ) {
    //check for attributes 
    $eventitShortcodeAttributes = shortcode_atts( [
        'events'     => false,   // comma separated event keys - wins over categories
        'categories' => false,   // comma separated category keys
        'boxed'      => false,   // "1" = box layout
        'columns'    => 0,       // 2/3/4 columns in box layout (0 = use global setting)
    ], $atts, 'eventit-events' );

    if ( $eventitShortcodeAttributes['events'] ) {
        // Parse event keys into an array. Deleted events are no longer in the feed
        // and finished ones are filtered out during rendering, so a pinned selection
        // quietly shrinks instead of showing something that is over.
        $eventitShortcodeAttributes['events'] = array_values( array_filter( array_map( 'trim', str_getcsv( (string) $eventitShortcodeAttributes['events'], ',' ) ), 'strlen' ) );
    } else {
        $eventitShortcodeAttributes['events'] = array();
    }

    if ( $eventitShortcodeAttributes['categories'] ) {
        // Parse categories into an array. Whitespace will be stripped.
        $eventitShortcodeAttributes['categories'] = array_values( array_filter( array_map( 'trim', str_getcsv( (string) $eventitShortcodeAttributes['categories'], ',' ) ), 'strlen' ) );
    } else {
        $eventitShortcodeAttributes['categories'] = array();
    }
    $eventitShortcodeAttributes['boxed']   = filter_var( $eventitShortcodeAttributes['boxed'], FILTER_VALIDATE_BOOLEAN );
    $eventitShortcodeAttributes['columns'] = intval( $eventitShortcodeAttributes['columns'] );

    //Load options
    $eventitOptions = get_option( 'eventit_events_options' );

    //$uriObject = new URIHandler( $_SERVER[ "REQUEST_URI" ] );
    $currentLocale = 'da';

    //fetch API values
    $uriObject = new URIHandler( '/'.  esc_attr($eventitOptions['eventit_events_field_organizerkey'] ?? '') .'/' );
    $eventitPassPhrase = esc_attr($eventitOptions['eventit_events_field_passphrase'] ?? '');

    // Default values (assuming NO valid organizer)
    $validOrganizerFound = false;
    $siteTheme = THEME_EVENTIT;
    
    ob_start();
    include( plugin_dir_path( __FILE__).'includes/rendering/events.php' );
    return ob_get_clean();

}