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

    $events = '';

    $account_id = $options['dacdb_district'];
    $club_id = $options['dacdb_club'];

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

    // Get category IDs in order of precedence:
    // 1. Query string parameter
    // 2. Shortcode attribute
    // 3. Plugin settings (district_events_types_side for district, club_events_types_side for club)
    // 4. Empty string (show all events)
    $categoryids = '';
    if (!empty($_GET['catids'])) {
        $categoryids = $_GET['catids'];
    } elseif (!empty($atts['catids'])) {
        $categoryids = $atts['catids'];
    } elseif ($type === 'district' && !empty($options['district_events_types_side'])) {
        $categoryids = $options['district_events_types_side'];
    } elseif ($type === 'club' && !empty($options['club_events_types_side'])) {
        $categoryids = $options['club_events_types_side'];
    }

    // Sanitize category IDs to only allow numbers and commas
    $categoryids = preg_replace('/[^0-9,]/', '', $categoryids);

    // Validate and sanitize $wk
    $wk = $_GET['wk'] ?? $atts['wk'] ?? 0;
    $wk = is_numeric($wk) && $wk >= 0 ? intval($wk) : 0;
    
    // Validate and sanitize $mo
    $mo = $_GET['mo'] ?? $atts['mo'] ?? 0;
    $mo = is_numeric($mo) && $mo >= 0 ? intval($mo) : 0;

    // Validate and sanitize $showTZ
    $showTZ = isset($atts['showtz']) ? $atts['showtz'] : 0;
    $showTZ = $showTZ == '1' || $showTZ == 'true' || $showTZ == true ? 1 : 0;

    // Validate and sanitize $showGMT
    $showGMT = isset($atts['showgmt']) ? $atts['showgmt'] : 0;
    $showGMT = $showGMT == '1' || $showGMT == 'true' || $showGMT == true ? 1 : 0;

    $xml_params = [
        'AccountID' => $account_id,
        'ClubID' => $club_id,
        'R' => rand(),
    ];

    // Check URL parameters first (highest precedence)
    if (isset($_GET['wk']) && $_GET['wk'] > 0) {
        $xml_params['wk'] = $_GET['wk'];
    } elseif (isset($_GET['Mo'])) {
        $xml_params['Mo'] = $_GET['Mo'];
    }
    // Then check shortcode attributes (second precedence)
    elseif ($wk > 0) {
        $xml_params['wk'] = $wk;
    } elseif (isset($atts['Mo'])) {
        $xml_params['Mo'] = $atts['Mo'];
    }
    // Finally fall back to option settings (lowest precedence)
    elseif (isset($options['district_events_months']) && $options['district_events_months'] > 0) {
        $xml_params['Mo'] = $options['district_events_months'];
    }

    // Only add CatIDs parameter if categoryids is not empty - it must be last
    if (!empty($categoryids)) {
        $xml_params['CatIDs'] = $categoryids;
    }

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

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

    if ($fDebug && dacdb_is_admin()) {
        $debug_vars = [
            'type' => $type,
            'categoryids' => $categoryids,
            'wk' => $wk,
            'showTZ' => $showTZ,
            'showGMT' => $showGMT,
            'mo' => $mo,
            'xml_params' => $xml_params,
            'request_url' => $request_url,
            'xml' => $xml,
        ];

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

    $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>';
        // Event "More info" links
        $events .= '<a class="modal-link" href="' . $data_path . 'R_Event.cfm?EventID=' . $event->eventid . '" style="float:right;">More info</a>';
        $events .= '<br></div>';
        $events .= '<hr class="dacdb_plus_event_hr">';
        $counter = $counter + 1;
    }

    return $events;
}