<?php
/* ****************************************************
   Requests information from the organizer services API
**************************************************** */

function eventit_events_getEvents( $a_localekey, $a_organizerkey, $a_includeDepartmentEvents, $a_passphrase ) {
    // WP/legacy friendly: build query values as strings
    $departmentEvents = $a_includeDepartmentEvents ? 'true' : 'false';

    // Build URL
    $base  = 'https://app.event.it/organizerservices/api/v1/eventlist';
    $query = array(
        'characterset'            => 'UTF-8',
        'format'                  => 'json',
        'include-test-events'     => 'true',
        'include-for-departments' => $departmentEvents,
        'filter-visible'          => 'yes',
        'localekey'               => $a_localekey,
        'organizerkey'            => $a_organizerkey,
    );
    $url = add_query_arg( $query, $base );

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

    // Do request
    $response = wp_remote_get( $url, $args );
    if ( is_wp_error( $response ) ) {
        error_log( 'eventit_events_getEvents: ' . $response->get_error_message() );
        return null;
    }

    $code = intval( wp_remote_retrieve_response_code( $response ) );
    if ( $code < 200 || $code >= 300 ) {
        error_log( 'eventit_events_getEvents HTTP ' . $code );
        return null;
    }

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

    // Build Eventlist object from JSON
    $eventListObj = new Eventlist();

    if ( method_exists( $eventListObj, 'loadFromJson' ) ) {
        // Let the class map JSON → internal structures
        $eventListObj->loadFromJson( $body );
        return $eventListObj;
    }
    return null;
}
