<?php 
function dacdb_committee($atts)
{
    // Global variables used within the function
    global $fDebug, $data_path, $options;
    $options = get_mmp_options(); // Retrieve the plugin options

    // Register and enqueue required styles
    if (!wp_style_is('show-committee', 'registered')) {
        wp_register_style(
            'show-committee',
            plugins_url('css/show-committee.css', dirname(__FILE__)),
            array(),
            MMPDB_PLUGIN_VERSION
        );
    }
    wp_enqueue_style('show-committee');

    $members = '';
    
    // Debug output for stylesheet
    if ($fDebug && dacdb_is_admin()) {
        $members .= "<div class=\"debug\">";
        $members .= "<h5>Stylesheet Debug</h5>";
        $members .= "<p>show-committee stylesheet registered: " . (wp_style_is('show-committee', 'registered') ? 'Yes' : 'No') . "</p>";
        $members .= "<p>show-committee stylesheet enqueued: " . (wp_style_is('show-committee', 'enqueued') ? 'Yes' : 'No') . "</p>";
        $members .= "</div>";
    }

    // Register and enqueue ColorBox if not already registered
    if (!wp_script_is('jquery-colorbox', 'registered')) {
        wp_register_script('jquery-colorbox', plugins_url('js/vendor/jquery.colorbox-min.js', dirname(__FILE__)), array('jquery'), '1.6.4', true);
        wp_register_style('jquery-colorbox-style', plugins_url('css/vendor/colorbox.css', dirname(__FILE__)), array(), '1.6.4');
    }
    wp_enqueue_script('jquery-colorbox');
    wp_enqueue_style('jquery-colorbox-style');

    // Retrieve attribute values from the $atts array
    $account_id = $options['dacdb_district'];
    $club_id = $options['dacdb_club'];

    // Fix for cid parameter handling - accept either string or numeric values
    $cid = "";
    if (isset($atts['cid'])) {
        // Convert to string first if it's numeric, and ensure it's cleaned of any HTML
        $cid = (string) $atts['cid'];
        // Remove any HTML that might be in the parameter
        $cid = strip_tags($cid);
    }

    $members = ""; // HTML markup for displaying the committee members

    // Check if Committee ID is missing
    if (empty($cid)) {
        return "<div class=\"error-msg\"><i class=\"fa fa-times-circle\"></i>CommitteeID (cid=) is missing</div>";
    }

    $members = ""; // HTML markup for displaying the committee members

    // Check if Committee ID is missing
    if (empty($cid)) {
        return "<div class=\"error-msg\"><i class=\"fa fa-times-circle\"></i>CommitteeID (cid=) is missing</div>";
    }

    // Set committee_show_members based on attributes and options
    $committee_show_members = isset($atts['show_members']) ? intval($atts['show_members']) : 
        (isset($options['committee_show_members']) ? intval($options['committee_show_members']) : 2);

    // Override committee_show_members if members attribute is set
    if (isset($atts['members'])) {
        $committee_show_members = intval($atts['members']);
    }

    // Ensure committee_show_members is at least 1 to show members
    if ($committee_show_members < 1) {
        $committee_show_members = 1;
    }

    // Set committee_global_name based on attributes and options
    $committee_global_name = isset($atts['name']) ? intval($atts['name']) : 
        (isset($options['committee_global_name']) ? intval($options['committee_global_name']) : 1);

    // Set committee_global_description based on attributes and options
    $committee_global_description = isset($atts['description']) ? intval($atts['description']) : 
        (isset($options['committee_global_description']) ? intval($options['committee_global_description']) : 1);

    // Get attribute values, falling back to options or defaults only if attribute doesn't exist or is empty
    $committee_show_account_id = isset($atts['accountid']) ? intval($atts['accountid']) :
        (isset($atts['district']) ? intval($atts['district']) :
            (isset($atts['grandlodge']) ? intval($atts['grandlodge']) :
                ($options['committee_org_data_account'] ?? 0)));
    $committee_show_entity_name = isset($atts['entityname']) ? intval($atts['entityname']) :
        (isset($atts['lodgename']) ? intval($atts['lodgename']) :
            (isset($atts['clubname']) ? intval($atts['clubname']) :
                (isset($atts['chaptername']) ? intval($atts['chaptername']) :
                    ($options['committee_org_data_entity'] ?? 1))));
    
    // Fix row/column handling to follow proper override hierarchy:
    // Parameters > Attributes > Options > Defaults
    $committee_members_per_row = 3; // Default value
    
    // First check options
    if (isset($options['committee_members_per_row'])) {
        $committee_members_per_row = intval($options['committee_members_per_row']);
    }
    
    // Then check attributes (these override options)
    if (isset($atts['row'])) {
        $committee_members_per_row = intval($atts['row']);
    } elseif (isset($atts['rows'])) {
        $committee_members_per_row = intval($atts['rows']);
    } elseif (isset($atts['cols'])) {
        $committee_members_per_row = intval($atts['cols']);
    }
    
    // Finally check parameters (these override everything)
    if (isset($_GET['row'])) {
        $committee_members_per_row = intval($_GET['row']);
    } elseif (isset($_GET['rows'])) {
        $committee_members_per_row = intval($_GET['rows']);
    } elseif (isset($_GET['cols'])) {
        $committee_members_per_row = intval($_GET['cols']);
    }
    
    // Ensure value is between 1 and 4
    if ($committee_members_per_row < 1 || $committee_members_per_row > 4) {
        $committee_members_per_row = 3; // Default to 3 if invalid value
    }

    // Boolean attributes that can be true/false strings or 1/0
    $committee_members_pics = isset($atts['pics']) ?
        (is_string($atts['pics']) ? strtolower($atts['pics']) === 'true' : intval($atts['pics'])) :
        ($options['committee_members_pics'] ?? 1);
    $committee_members_contact_link = isset($atts['contact']) ?
        (is_string($atts['contact']) ? strtolower($atts['contact']) === 'true' : intval($atts['contact'])) :
        ($options['committee_members_contact_link'] ?? 1);
    $committee_members_committeeposition = isset($atts['committeeposition']) ?
        (is_string($atts['committeeposition']) ? strtolower($atts['committeeposition']) === 'true' : intval($atts['committeeposition'])) :
        ($options['committee_members_committeeposition'] ?? 1);
    $committee_members_busposition = isset($atts['busposition']) ?
        (is_string($atts['busposition']) ? strtolower($atts['busposition']) === 'true' : intval($atts['busposition'])) :
        ($options['committee_members_busposition'] ?? 0);
    $committee_members_classification = isset($atts['classification']) ?
        (is_string($atts['classification']) ? strtolower($atts['classification']) === 'true' : intval($atts['classification'])) :
        ($options['committee_members_classification'] ?? 0);

    // Check for leaders/show_leaders attributes
    if (isset($atts['leaders']) || isset($atts['show_leaders'])) {
        $show_leaders = $atts['leaders'] ?? $atts['show_leaders'];
        if ($show_leaders === true || $show_leaders === '1' || $show_leaders === 1) {
            $committee_show_members = 1; // Show leaders only
        } elseif ($show_leaders === false || $show_leaders === '0' || $show_leaders === 0) {
            // If leaders are explicitly hidden, and we were showing all members,
            // switch to showing no members
            if ($committee_show_members === 2) {
                $committee_show_members = 0;
            }
        }
    }

    // Construct path to xml feed
    $xml_path = $data_path . 'wp_ById.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&id=' . $cid . '&R=' . rand();

    // Debug output for committee
    if ($fDebug && dacdb_is_admin()) {
        $members .= "<div class=\"debug\">";
        $members .= "<h5>function <em>dacdb_committee</em> called</h5>";
        $members .= "<table class=\"debug-table\">";
        $members .= "<tr><th>Variable</th><th>Option</th><th>Attribute</th><th>Default</th><th>Value</th></tr>";

        // Committee ID
        $members .= "<tr>";
        $members .= "<td><code>cid</code></td>";
        $members .= "<td>N/A</td>";
        $members .= "<td>" . ($atts['cid'] ?? 'N/A') . "</td>";
        $members .= "<td>N/A</td>";
        $members .= "<td>" . $cid . "</td>";
        $members .= "</tr>";

        // Committee Name
        $members .= "<tr>";
        $members .= "<td><code>committee_global_name</code></td>";
        $members .= "<td>" . ($options['committee_global_name'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['name'] ?? 'N/A') . "</td>";
        $members .= "<td>1</td>";
        $members .= "<td>" . $committee_global_name . "</td>";
        $members .= "</tr>";

        // Committee Description
        $members .= "<tr>";
        $members .= "<td><code>committee_global_description</code></td>";
        $members .= "<td>" . ($options['committee_global_description'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['description'] ?? 'N/A') . "</td>";
        $members .= "<td>1</td>";
        $members .= "<td>" . $committee_global_description . "</td>";
        $members .= "</tr>";

        // Show Account ID
        $members .= "<tr>";
        $members .= "<td><code>committee_show_account_id</code></td>";
        $members .= "<td>" . ($options['committee_org_data_account'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['accountid'] ?? $atts['district'] ?? $atts['grandlodge'] ?? 'N/A') . "</td>";
        $members .= "<td>0</td>";
        $members .= "<td>" . $committee_show_account_id . "</td>";
        $members .= "</tr>";

        // Show Entity Name
        $members .= "<tr>";
        $members .= "<td><code>committee_show_entity_name</code></td>";
        $members .= "<td>" . ($options['committee_org_data_entity'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['entityname'] ?? $atts['lodgename'] ?? $atts['clubname'] ?? $atts['chaptername'] ?? 'N/A') . "</td>";
        $members .= "<td>1</td>";
        $members .= "<td>" . $committee_show_entity_name . "</td>";
        $members .= "</tr>";

        // Members Per Row
        $members .= "<tr>";
        $members .= "<td><code>committee_members_per_row</code></td>";
        $members .= "<td>" . ($options['committee_members_per_row'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['cols'] ?? $atts['rows'] ?? $atts['row'] ?? 'N/A') . "</td>";
        $members .= "<td>3</td>";
        $members .= "<td>" . $committee_members_per_row . "</td>";
        $members .= "</tr>";

        // Show Members
        $members .= "<tr>";
        $members .= "<td><code>committee_show_members</code></td>";
        $members .= "<td>" . ($options['committee_show_members'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['show_members'] ?? $atts['members'] ?? 'N/A') . "</td>";
        $members .= "<td>2</td>";
        $members .= "<td>" . $committee_show_members . "</td>";
        $members .= "</tr>";

        $members .= "</table>";
        $members .= "</div>";

        // XML Path
        $members .= "<div class=\"debug-row\">";
        $members .= "<p><code>xml_path</code>: ";
        $members .= "<a href=\"" . $xml_path . "\" target=\"debug-window\">" . $xml_path . "</a></p>";
        $members .= "</div>";

        // Debug output for committee_members_per_row
        $members .= "<ul class=\"debug-row\"><li><code>committee_members_per_row</code> value: " . $committee_members_per_row . "</li>";
        $members .= "<li><code>committee_members_per_row</code> type: " . gettype($committee_members_per_row) . "</li></ul>";

    }

    // Load XML data from the specified URL
    libxml_use_internal_errors(true);
    $xml = simplexml_load_file($xml_path);
    
    if ($xml === false) {
        $errors = libxml_get_errors();
        libxml_clear_errors();
        $error_message = '';
        foreach ($errors as $error) {
            $error_message .= "XML Error {$error->code}: {$error->message}\n";
        }
        error_log('DACdb Plus: XML Error in dacdb_committee: ' . $error_message);
        return '<div class="error-msg"><i class="fa fa-times-circle"></i>Error loading committee data. Please check the error logs.</div>';
    }

    // Debug output for XML data
    if ($fDebug && dacdb_is_admin()) {
        $members .= "<div class=\"debug\">";
        $members .= "<h5>XML Data Debug</h5>";
        $members .= "<pre>";
        $members .= htmlspecialchars($xml->asXML());
        $members .= "</pre>";
        $members .= "</div>";
    }

    // Check if XML data is empty
    if (strlen($xml) == 0) {
        $members .= '<div class="error-msg"><i class="fa fa-times-circle"></i>There are no committee members to display at this time.</div>';
        return $members;
    }

    // Set the div and image widths based on the number of columns
    $setDivWidth = 160;
    $setImgWidth = 150;
    $div = '<div class="dac-col">';

    if ($committee_members_per_row === 1) {
        $div = '<div class="members dac-col-xs-12">';
        $setDivWidth = 155;
        $setImgWidth = 150;
    } else if ($committee_members_per_row === 2) {
        $div = '<div class="members dac-col-xs-12 dac-col-sm-6">';
        $setDivWidth = 140;
        $setImgWidth = 135;
    } else if ($committee_members_per_row === 3) {
        $div = '<div class="members dac-col-xs-12 dac-col-sm-6 dac-col-md-4">';
        $setDivWidth = 125;
        $setImgWidth = 120;
    } else if ($committee_members_per_row === 4) {
        $div = '<div class="members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3">';
        $setDivWidth = 110;
        $setImgWidth = 105;
    }

    if ($fDebug && dacdb_is_admin()) {
        $members .= "<div class=\"debug\">";
        $members .= "<h5>Row/Column Debug</h5>";
        $members .= "<p>committee_members_per_row value: " . $committee_members_per_row . "</p>";
        $members .= "<p>div class: " . $div . "</p>";
        $members .= "</div>";
    }

    $thumbnail_width = isset($options['thumbnail_width']) && $options['thumbnail_width'] > 0 ? $options['thumbnail_width'] : (isset($atts['imgwidth']) && isset($atts['imgwidth']) > 0 ? $atts['imgwidth'] : 150);
    $thumbnail_height = isset($options['thumbnail_height']) && $options['thumbnail_height'] > 0 ? $options['thumbnail_height'] : (isset($atts['imgheight']) && isset($atts['imgheight']) > 0 ? $atts['imgheight'] : 150);

    // Counter for tracking members
    $counter = 0;

    // Display committee name if enabled
    if ($committee_global_name == 1) {
        $members .= '<div class="dac-row">';
        $members .= '   <div class="dac-col-xs-12">';
        $members .= '       <h3>' . $xml->committeemembers->committeename . '</h3>';
        $members .= '   </div>';
        $members .= '</div>';
    }

    // Display committee description if enabled
    if ($committee_global_description == 1) {
        $members .= '<div class="dac-row">';
        $members .= '    <div class="dac-col-xs-12">';
        $members .= '        <article>';
        $members .= $xml->committeemembers->description;
        $members .= '        </article>';
        $members .= '    </div>';
        $members .= '</div>';
    }

    // Display committee members
    if ($committee_show_members > 0) {
        $members .= '<div class="dac-row">';

        foreach ($xml->committeemembers as $member) {
            // Skip non-leaders if we're only showing leaders
            if ($committee_show_members == 1 && strtolower($member->committeeposition ?? '') === 'member') {
                continue;
            }

            $members .= $div; // Add the Bootstrap classes div here
            $members .= '<table border="0" cellpadding="0" cellspacing="0">';
            $members .= '<tr>';

            if ($committee_members_pics == 1) {
                $members .= '<td style="border:0 !important;vertical-align: top; padding: 0 1rem 0 0; width:' . $setDivWidth . 'px;">';

                if ($member->image == '') {
                    $members .= '<div style="width:' . $setDivWidth . 'px;"><img src="' . MMPDB_PLUGIN_URL . 'img/avatar.svg"  style="aspect-ratio: 4 / 5; width: ' . $setImgWidth . 'px; object-fit: cover;" width="' . $setImgWidth . '"></div>';
                } else {
                    $members .= '<div style="width:' . $setDivWidth . 'px;"><img src="' . $member->image . '"  style="aspect-ratio: 4 / 5; width: ' . $setImgWidth . 'px; object-fit: cover;" width="' . $setImgWidth . '"></div>';
                }

                $members .= '</td>';
            }

            $members .= '    <td style="border:0 !important; text-align: left; vertical-align: top; padding:0;">';
            $members .= '       <strong>' . $member->membername . '</strong><BR>';

            $formattedUrl = formatDomainToUrl($member->cluburl);
            if (!empty($formattedUrl)) {
                $members .= '<a href="' . $formattedUrl . '" target="new">' . $member->clubname . '</a><br>';
            } else {
                $members .= '<span class="clubname">' . $member->clubname . '<br></span>';
            }

            if ($committee_show_account_id == 1) {
                if ($member->accountid != '') {
                    $members .= 'District ' . $member->accountid . '<br />';
                }
            }

            if ($committee_members_committeeposition == 1) {
                if ($member->committeeposition != '') {
                    $members .= $member->committeeposition . '<br />';
                }
            }

            if ($committee_members_busposition == 1) {
                if ($member->busposition != '') {
                    $members .= $member->busposition . '<br />';
                }
            }

            if ($committee_members_classification == 1) {
                if ($member->classification != '') {
                    $members .= $member->classification . '<br />';
                }
            }

            if ($committee_members_contact_link == 1) {
                $members .= '<a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $member->userid . '" name="dlc-inline-link-' . $counter . '" class="modal-link">Contact</a>';
            }

            $members .= '</td>';
            $members .= '</tr>';
            $members .= '</table>';
            $members .= '</div>'; // Close the Bootstrap classes div
            $counter = $counter + 1;
        }

        $members .= '</div>'; // Close the dac-row
    }

    return $members;
}