<?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'];

    // Merge original shortcode attributes if available
    if (isset($GLOBALS['dacdb_plus_current_shortcode_id']) && 
        isset($GLOBALS['dacdb_plus_original_atts_' . $GLOBALS['dacdb_plus_current_shortcode_id']]) && 
        is_array($GLOBALS['dacdb_plus_original_atts_' . $GLOBALS['dacdb_plus_current_shortcode_id']])) {
        $atts = array_merge($atts, $GLOBALS['dacdb_plus_original_atts_' . $GLOBALS['dacdb_plus_current_shortcode_id']]);
    }

    // Parse shortcode attributes with defaults
    $atts = shortcode_atts(array(
        'type' => ($club_id == 0 ? 'district' : 'club'),
        'catids' => '',
        'wk' => 0,
        'mo' => 0,
        'showtz' => 0,
        'showgmt' => 0,
        'count' => 0, // New: limit number of events shown
    ), $atts, 'dacdb_events');
    
    // Handle uppercase variations that users might use
    if (isset($atts['Mo']) && !isset($atts['mo'])) {
        $atts['mo'] = $atts['Mo'];
    }
    if (isset($atts['showTZ']) && !isset($atts['showtz'])) {
        $atts['showtz'] = $atts['showTZ'];
    }
    if (isset($atts['showGMT']) && !isset($atts['showgmt'])) {
        $atts['showgmt'] = $atts['showGMT'];
    }

    // Apply precedence order: URL params > shortcode attributes > plugin settings > defaults
    
    // Type precedence
    $type = $_GET['type'] ?? $atts['type'] ?? ($club_id == 0 ? 'district' : 'club');
    $type = in_array($type, ['district', 'club']) ? trim($type) : ($club_id == 0 ? 'district' : 'club');

    // Category IDs precedence
    $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);

    // Weeks precedence
    $wk = 0;
    if (isset($_GET['wk']) && is_numeric($_GET['wk']) && $_GET['wk'] >= 0) {
        $wk = intval($_GET['wk']);
    } elseif (isset($atts['wk']) && is_numeric($atts['wk']) && $atts['wk'] >= 0) {
        $wk = intval($atts['wk']);
    } elseif ($type === 'district' && isset($options['district_events_weeks']) && is_numeric($options['district_events_weeks']) && $options['district_events_weeks'] > 0) {
        $wk = intval($options['district_events_weeks']);
    } elseif ($type === 'club' && isset($options['club_events_weeks']) && is_numeric($options['club_events_weeks']) && $options['club_events_weeks'] > 0) {
        $wk = intval($options['club_events_weeks']);
    } elseif (isset($options['events_weeks']) && is_numeric($options['events_weeks']) && $options['events_weeks'] > 0) {
        $wk = intval($options['events_weeks']);
    }

    // Months precedence  
    $mo = 0;
    if (isset($_GET['mo']) && is_numeric($_GET['mo']) && $_GET['mo'] >= 0) {
        $mo = intval($_GET['mo']);
    } elseif (isset($_GET['Mo']) && is_numeric($_GET['Mo']) && $_GET['Mo'] >= 0) {
        $mo = intval($_GET['Mo']);
    } elseif (isset($atts['mo']) && is_numeric($atts['mo']) && $atts['mo'] >= 0) {
        $mo = intval($atts['mo']);
    } elseif ($type === 'district' && isset($options['district_events_months']) && is_numeric($options['district_events_months']) && $options['district_events_months'] > 0) {
        $mo = intval($options['district_events_months']);
    } elseif ($type === 'club' && isset($options['club_events_months']) && is_numeric($options['club_events_months']) && $options['club_events_months'] > 0) {
        $mo = intval($options['club_events_months']);
    } elseif (isset($options['events_months']) && is_numeric($options['events_months']) && $options['events_months'] > 0) {
        $mo = intval($options['events_months']);
    }

    // ShowTZ precedence
    $showTZ = 0;
    if (isset($_GET['showtz'])) {
        $showTZ = ($_GET['showtz'] == '1' || $_GET['showtz'] == 'true') ? 1 : 0;
    } elseif (isset($atts['showtz'])) {
        $showTZ = ($atts['showtz'] == '1' || $atts['showtz'] == 'true' || $atts['showtz'] == true) ? 1 : 0;
    } elseif ($type === 'district' && isset($options['district_events_show_timezone']) && $options['district_events_show_timezone'] == 1) {
        $showTZ = 1;
    } elseif ($type === 'club' && isset($options['club_events_show_timezone']) && $options['club_events_show_timezone'] == 1) {
        $showTZ = 1;
    } elseif (isset($options['events_show_timezone']) && $options['events_show_timezone'] == 1) {
        $showTZ = 1;
    }

    // ShowGMT precedence
    $showGMT = 0;
    if (isset($_GET['showgmt'])) {
        $showGMT = ($_GET['showgmt'] == '1' || $_GET['showgmt'] == 'true') ? 1 : 0;
    } elseif (isset($atts['showgmt'])) {
        $showGMT = ($atts['showgmt'] == '1' || $atts['showgmt'] == 'true' || $atts['showgmt'] == true) ? 1 : 0;
    } elseif ($type === 'district' && isset($options['district_events_show_gmt']) && $options['district_events_show_gmt'] == 1) {
        $showGMT = 1;
    } elseif ($type === 'club' && isset($options['club_events_show_gmt']) && $options['club_events_show_gmt'] == 1) {
        $showGMT = 1;
    } elseif (isset($options['events_show_gmt']) && $options['events_show_gmt'] == 1) {
        $showGMT = 1;
    }

    // Count precedence
    $count = 0;
    if (isset($_GET['count']) && is_numeric($_GET['count']) && $_GET['count'] > 0) {
        $count = intval($_GET['count']);
    } elseif (isset($atts['count']) && is_numeric($atts['count']) && $atts['count'] > 0) {
        $count = intval($atts['count']);
    } elseif ($type === 'district' && isset($options['district_events_default_count']) && is_numeric($options['district_events_default_count']) && $options['district_events_default_count'] > 0) {
        $count = intval($options['district_events_default_count']);
    } elseif ($type === 'club' && isset($options['club_events_default_count']) && is_numeric($options['club_events_default_count']) && $options['club_events_default_count'] > 0) {
        $count = intval($options['club_events_default_count']);
    } elseif (isset($options['events_default_count']) && is_numeric($options['events_default_count']) && $options['events_default_count'] > 0) {
        $count = intval($options['events_default_count']);
    }

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

    // Determine time period for events
    // Priority: URL params > shortcode attributes > plugin settings
    if ($wk > 0) {
        // If wk (weeks) is specified, use it
        $xml_params['wk'] = $wk;
    } elseif ($mo > 0) {
        // If mo (months) is specified, use it
        $xml_params['Mo'] = $mo;
    } elseif (isset($options['district_events_months']) && $options['district_events_months'] > 0) {
        // Fall back to plugin settings
        $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 = dacdb_load_xml($request_url, 'events');

    if ($xml === false || 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,
            'count' => $count,
            '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) {
        // If count is specified and we've reached the limit, break out of loop
        if ($count > 0 && $counter > $count) {
            break;
        }

        $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++;
    }

    return $events;
}