<?php
function dacdb_sponsors($atts)
{
    global $fDebug, $data_path, $options;

    $options = get_mmp_options();
    $account_id = $options['dacdb_district'];
    $club_id = $options['dacdb_club'];
    $cat = isset($atts['cat']) && isset($atts['cat']) > 0 ? $atts['cat'] : (isset($options['cat']) && $options['cat'] > 0 ? $options['cat'] : 0);

    $sponsors = '';

    if ($fDebug && dacdb_is_admin()) {
        $sponsors .= "=================================================================<BR>";
        $sponsors .= "function dacdb_sponsors called<br>";
        $sponsors .= "AccountID=" . $account_id . "<br>";
        $sponsors .= "ClubID=" . $club_id . "<br>";
        $sponsors .= "CategoryID=" . $cat . "<br>";
        $sponsors .= "URL=" . $data_path . 'wp_sponsor.cfm?AccountID=' . $account_id . '&ClubID=' . $club_id . '&CategoryID=' . $cat . '&N=9999&SortBy=random' . "<br>";
        $sponsors .= "=================================================================<BR>";
    }

    // Enqueue styles
    wp_enqueue_style('show-sponsors', MMPDB_PLUGIN_URL . 'css/show-sponsors.css', array('dacdb-bootstrap'), MMPDB_PLUGIN_VERSION, 'all');

    $xml = simplexml_load_file($data_path . 'wp_sponsor.cfm?AccountID=' . $account_id . '&ClubID=' . $club_id . '&CategoryID=' . $cat . '&N=9999&SortBy=random' . '&R=' . rand());
    if (!$xml) {
        return '<div>There are no sponsors to display at this time.</div>';
    }

    $sponsors .= '<section class="mmp-sponsors">';
    $sponsors .= '<div class="mmp-sponsors-row">';
    foreach ($xml->sponsor as $sponsor) {
        // Filter by category ID if specified
        if ($cat > 0 && (int)$sponsor->categoryid != $cat) {
            continue;
        }

        $sponsor_image = !empty($sponsor->image) && trim($sponsor->image) !== '' ? '<img src="' . $sponsor->imagepath . $sponsor->image . '" alt="' . htmlspecialchars($sponsor->sponsorname) . '">' : '';
        $sponsor_name = htmlspecialchars($sponsor->sponsorname);
        $sponsor_url = htmlspecialchars($sponsor->website);
        $sponsor_contact = $sponsor->contact ? '<p>Contact: ' . htmlspecialchars($sponsor->contact) . '</p>' : '';
        $sponsor_phone = $sponsor->phonenumber ? '<p>Phone: ' . htmlspecialchars($sponsor->phonenumber) . '</p>' : '';
        $sponsor_email = $sponsor->email ? '<p>Email: <a href="mailto:' . htmlspecialchars($sponsor->email) . '">' . htmlspecialchars($sponsor->email) . '</a></p>' : '';

        $sponsors .= '<div class="mmp-sponsor-item">';
        $sponsors .= '<a href="' . $sponsor_url . '" target="_blank" class="mmp-sponsor-link">';
        $sponsors .= $sponsor_image;
        $sponsors .= '<p class="mmp-sponsor-name">' . $sponsor_name . '</p>';
        $sponsors .= '</a>';
        $sponsors .= $sponsor_contact;
        $sponsors .= $sponsor_phone;
        $sponsors .= $sponsor_email;
        $sponsors .= '</div>';
    }
    $sponsors .= '</div>';
    $sponsors .= '</section>';

    return $sponsors;
}