<?php 
function dacdb_events($atts)
{
    global $fDebug, $data_path, $file_path, $options;
    $events = '';

    // Ensure $atts is an array
    $atts = is_array($atts) ? $atts : array();

    $account_id = $options['dacdb_district'];
    $club_id = isset($options['dacdb_club']) ? $options['dacdb_club'] : '0';

    // Validate and sanitize $wk
    $wk = $_GET['wk'] ?? $atts['wk'] ?? 0;
    $wk = in_array($wk, [0, 1]) ? intval($wk) : 0;

    // Validate and sanitize $mo
    $mo = $_GET['Mo'] ?? $atts['Mo'] ?? $options['district_events_months'] ?? '';
    $mo = trim($mo);

    // Validate and sanitize timezone display options
    $showTZ = $_GET['showTZ'] ?? $atts['showTZ'] ?? 0;
    $showTZ = in_array($showTZ, [0, 1]) ? intval($showTZ) : 0;

    $showGMT = $_GET['showgmt'] ?? $atts['showgmt'] ?? 0;
    $showGMT = in_array($showGMT, [0, 1]) ? intval($showGMT) : 0;

    // Get all available event category IDs for fallback
    $eventID_json = $data_path . "wp_eventcategory.cfm?D=" . $options['dacdb_district'];
    $valid_categories = array();
    
    $json_data = @file_get_contents($eventID_json);
    if ($json_data !== false) {
        $categories = json_decode($json_data, true);
        if (is_array($categories)) {
            $valid_categories = array_column($categories, 'EVENTCATEGORYID');
        }
    }

    // Determine type (district or club)
    $type = $_GET['type'] ?? $atts['type'] ?? ($club_id == 0 ? 'district' : 'club');
    $type = in_array($type, ['district', 'club']) ? trim($type) : 'district';

    // Priority chain for event category IDs
    if (isset($_GET['catids'])) {
        $eids = $_GET['catids'];
    } elseif (isset($_GET['catid'])) {
        $eids = $_GET['catid'];
    } elseif (isset($atts['catids'])) {
        $eids = $atts['catids'];
    } elseif (isset($atts['catid'])) {
        $eids = $atts['catid'];
    } elseif ($type === 'club' && !empty($options['club_events_types_page'])) {
        $eids = $options['club_events_types_page'];
    } elseif ($type === 'district' && !empty($options['district_events_types_page'])) {
        $eids = $options['district_events_types_page'];
    } else {
        $eids = implode(',', $valid_categories);
    }

    // Sanitize the category IDs
    $eids = preg_replace('/[^0-9,]/', '', $eids);

    // Build XML parameters with explicit CatIDs
    $xml_params = array(
        'AccountID' => $account_id,
        'ClubID' => $club_id,
        'CatIDs' => $eids,
        'R' => rand()
    );

    // Debug the parameters before building URL
    if ($fDebug) {
        error_log('XML Parameters: ' . print_r($xml_params, true));
    }

    $request_url = $data_path . 'wp_event.cfm?' . http_build_query($xml_params);

    // Debug the final URL
    if ($fDebug) {
        error_log('Request URL: ' . $request_url);
    }

    // Load XML data with proper error handling
    if ($wk > 0) {
        $xml = @simplexml_load_file("$request_url&wk=$wk");
    } else {
        $xml = !empty($mo) ? @simplexml_load_file("$request_url&Mo=$mo") : @simplexml_load_file($request_url);
    }

    if ($fDebug) {
        $debug_vars = array(
            'type' => $type,
            'URL catids' => isset($_GET['catids']) ? $_GET['catids'] : 'Not set',
            'URL catid' => isset($_GET['catid']) ? $_GET['catid'] : 'Not set',
            'Shortcode catids' => isset($atts['catids']) ? $atts['catids'] : 'Not set',
            'Shortcode catid' => isset($atts['catid']) ? $atts['catid'] : 'Not set',
            'Options district_events_types_page' => isset($options['district_events_types_page']) ? $options['district_events_types_page'] : 'Not set',
            'Options club_events_types_page' => isset($options['club_events_types_page']) ? $options['club_events_types_page'] : 'Not set',
            'All available categories' => is_array($valid_categories) ? implode(',', $valid_categories) : 'No categories found',
            'Final eids used' => $eids,
            'XML Parameters' => $xml_params,
            'XML Response' => $xml ? 'Valid XML' : 'No XML data',
            'Request URL' => $request_url,
            'Week Parameter' => $wk,
            'Month Parameter' => $mo,
            'Show Timezone' => $showTZ,
            'Show GMT' => $showGMT
        );

        dacdb_debug('dacdb_events', $atts, $options, $debug_vars, $xml);
    }

    if (empty($xml)) {
        $events .= 'There are no events at this time.';
        return $events;
    }

    $counter = 1;
    foreach ($xml->event as $event) {
        $events .= '<div class="dacdb_plus_event">';

        if ($options['events_global_date'] == 1) {
            $startDateTime = date("Y-m-d H:i", strtotime($event->startdate));
            $events .= '<time datetime="' . $startDateTime . '">';
            $events .= date("F jS Y, g:i a", strtotime($event->startdate));
            $events .= '</time>';

            if ($showTZ)
                $events .= ' ' . $event->tz;
            if ($showGMT)
                $events .= ' ' . $event->gmtoffset;
            $events .= '<br>';
        }

        $events .= '<strong>' . $event->eventname . '</strong>';

        if ($event->description != '') {
            $events .= '<br>' . $event->description;
        }

        if ($options['club_events_show_speakers_info'] == 1) {
            if ($event->speaker != '') {
                $events .= '<br><strong>Speaker: ' . $event->speaker . '</strong>';
            }
            if ($event->topic != '') {
                $events .= '<br>Topic: ' . $event->topic;
            }
        }

        if ($options['events_global_date'] == 0) {
            $startDateTime = date("Y-m-d H:i", strtotime($event->startdate));
            $events .= '<br><time datetime="' . $startDateTime . '">';
            $events .= date("F jS Y \a\\t g:i a", strtotime($event->startdate));
            $events .= '</time>';

            if ($showTZ)
                $events .= ' ' . $event->tz;
            if ($showGMT)
                $events .= ' ' . $event->gmtoffset;
        }

        $events .= '<br>';
        $events .= '<a class="iframe cboxElement" sandbox="allow-top-navigation" href="' . $data_path . 'R_Event.cfm?EventID=' . $event->eventid . '">More info</a>';
        $events .= '<br></div>';
        $events .= '<hr class="dacdb_plus_event_hr">';
        $counter = $counter + 1;
    }

    return $events;
}