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

    $newMemberForms = '';

    if ($fDebug) {
        $newMemberForms .= "==================================================================<br>";
        $newMemberForms .= "function dacdb_NewMemberFormList called<br>";
        $newMemberForms .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $newMemberForms .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $newMemberForms .= "URL=" . $data_path . 'wp_newMemberForm.cfm?AccountID=' . $options['dacdb_district'] . '<br>';
        $newMemberForms .= "==================================================================<br>";
    }

    // Fetch the JSON response
    $url = $data_path . 'wp_newMemberForm.cfm?AccountID=' . $options['dacdb_district'] . '&R=' . rand();
    $json = file_get_contents($url);

    // Decode the JSON response into an associative array
    $data = json_decode($json, true);

    if ($data === null || empty($data)) {
        $newMemberForms .= 'There are no club registration forms to display at this time.';
        return $newMemberForms;
    }

    $newMemberForms .= '<table width="100%" class="table" style="width: 100%; border:0;">';
    $newMemberForms .= '<tbody>';

    foreach ($data as $newMemberForm) {
        // Add https:// to CLUBURL if no protocol is present
        $clubUrl = !empty($newMemberForm['CLUBURL']) ? $newMemberForm['CLUBURL'] : '';
        if ($clubUrl && !preg_match("~^(?:f|ht)tps?://~i", $clubUrl)) {
            $clubUrl = 'https://' . $clubUrl;
        }

        $newMemberForms .= '<tr>';
        $newMemberForms .= '<td>' . (!empty($newMemberForm['CLUBURL']) ? '<a href="' . $clubUrl . '" target="_blank">' . $newMemberForm['CLUBNAME'] . '</a>' : $newMemberForm['CLUBNAME']) . '</td>';
        $newMemberForms .= '<td>' . (!empty($newMemberForm['CITY']) ?  $newMemberForm['CITY'] . ', ' . $newMemberForm['STATECODE']  : ''). '</td>' ;
        $newMemberForms .= '<td>' . (!empty($newMemberForm['APPID']) ? '<a href="https://www.emembersdb.com/NM/?ID=' . $newMemberForm['APPID'] . '" class="modal-link">' . $newMemberForm['APPNAME'] . '</a>' : $newMemberForm['APPNAME']) . '</td>';
        $newMemberForms .= '</tr>';
    }
    
    $newMemberForms .= '</tbody>';
    $newMemberForms .= '</table>';
    
    return $newMemberForms;
}
?>
