<?php
/**
 * Single Committee Display functionality for Member Minder Pro plugin
 * 
 * This file contains the committee shortcode implementation for displaying a single committee.
 * It requires the following global variables to be set:
 * - $data_path: Path to data files
 * - $file_path: Path to file storage
 * - $options: Plugin options
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Display a single committee's members
 * 
 * @param array $atts Shortcode attributes
 * @return string HTML output
 */
function dacdb_committee($atts) {
    global $fDebug, $data_path, $file_path, $options;
    $options = get_mmp_options();

    // Initialize output
    $output = '';

    // Get committee ID from shortcode attributes
    $cid = isset($atts['cid']) ? strtolower($atts['cid']) : '';
    if (empty($cid)) {
        return '<div class="mmpro-error"><i class="fa fa-times-circle"></i>CommitteeID (cid=) is missing</div>';
    }

    // Debug output if enabled
    if ($fDebug) {
        $output .= sprintf(
            '<div class="mmpro-debug">
                <h5>function dacdb_committee</h5>
                <pre>AccountID: %s\nClubID: %s\nCommitteeID: %s</pre>
            </div>',
            esc_html($options['dacdb_district']),
            esc_html($options['dacdb_club']),
            esc_html($cid)
        );
    }

    // Ensure assets are registered and enqueued
    if (!wp_script_is('mmpro-committees-style', 'registered')) {
        wp_register_style(
            'mmpro-committees-style',
            plugins_url('css/show-committees.css', dirname(__FILE__)),
            array(),
            MMPDB_PLUGIN_VERSION
        );
    }
    wp_enqueue_style('mmpro-committees-style');
    wp_enqueue_style('jquery-colorbox-style');
    wp_enqueue_script('jquery-colorbox');

    // Get show_members setting
    $show_members = isset($atts['show_members']) ? $atts['show_members'] : 
                   (isset($options['committee_show_members']) ? $options['committee_show_members'] : '2');

    // Fetch committee data
    $url = $data_path . 'wp_ById.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&id=' . $cid . '&R=' . rand();
    $response = file_get_contents($url);

    if (!$response || strlen($response) == 0) {
        return '<div class="mmpro-error">There are no committee members to display at this time.</div>';
    }

    // Try to detect if response is JSON or XML
    $first_char = substr(trim($response), 0, 1);
    if ($first_char === '{' || $first_char === '[') {
        // Response is JSON
        $data = json_decode($response);
        if (!$data) {
            error_log('DACdb Plus: JSON decode error - ' . json_last_error_msg());
            error_log('DACdb Plus: Failed JSON content - ' . substr($response, 0, 1000));
            return '<div class="mmpro-error">Error processing committee data (JSON error: ' . json_last_error_msg() . ')</div>';
        }

        // Convert JSON to SimpleXML structure
        try {
            $xml = new SimpleXMLElement('<root/>');
            $xml->addChild('committeemembers');
            
            foreach ($data as $member) {
                $memberNode = $xml->committeemembers->addChild('member');
                foreach ($member as $key => $value) {
                    if (is_string($value) || is_numeric($value)) {
                        $memberNode->addChild($key, htmlspecialchars((string)$value));
                    }
                }
            }
        } catch (Exception $e) {
            error_log('DACdb Plus: XML creation error - ' . $e->getMessage());
            return '<div class="mmpro-error">Error processing committee data (XML creation error)</div>';
        }
    } else {
        // Response is XML
        libxml_use_internal_errors(true);
        $xml = simplexml_load_string($response);
        if (!$xml) {
            $errors = libxml_get_errors();
            libxml_clear_errors();
            error_log('DACdb Plus: XML parse error - ' . print_r($errors, true));
            return '<div class="mmpro-error">Error processing committee data (XML parse error)</div>';
        }
    }

    // Filter members based on show_members setting
    if ($show_members === '1') {
        try {
            $new_xml = new SimpleXMLElement('<committee></committee>');
            $filtered_count = 0;
            
            foreach ($xml->committeemembers as $member) {
                $raw_position = (string)$member->committeeposition;
                $position = strtolower(trim($raw_position));
                
                // Consider as leader if position is not empty and not "member"
                $is_leader = !empty($position) && $position !== 'member';
                
                if ($is_leader) {
                    $member_node = $new_xml->addChild('committeemembers');
                    foreach ($member as $key => $value) {
                        $member_node->addChild($key, htmlspecialchars((string)$value));
                    }
                    $filtered_count++;
                }
            }
            
            if ($filtered_count === 0) {
                return '<div class="mmpro-error">There are no committee leaders to display at this time.</div>';
            }
            
            $xml = $new_xml;
        } catch (Exception $e) {
            error_log('DACdb Plus: Leader filtering error - ' . $e->getMessage());
            return '<div class="mmpro-error">Error processing committee leaders data</div>';
        }
    }

    // Add committee header if enabled
    if ($options['committee_global_name'] == 1) {
        $output .= '<div class="committee-header"><h3>' . $xml->committeemembers[0]->committeename . ' Committee Members</h3></div>';
    }

    // Add description if enabled
    if ($options['committee_global_description'] == 1 && !empty($xml->committeemembers[0]->description)) {
        $output .= '<div class="committee-description">' . $xml->committeemembers[0]->description . '</div>';
    }

    // Set up display attributes - matching exactly what show-committees.php does
    $display_atts = array(
        'pics' => $options['committee_members_pics'] ?? 1,
        'show_committee_position' => $options['committee_members_committeeposition'] ?? 1,
        'show_district_number' => $options['committee_global_show_district_number'] ?? 0,
        'show_business_position' => $options['committee_members_busposition'] ?? 0,
        'show_classification' => $options['committee_members_classification'] ?? 0,
        'show_contact' => $options['committee_members_contact_link'] ?? 1,
        'org_data_entity' => $options['committee_org_data_entity'] ?? 0,
        'org_data_account' => $options['committee_org_data_account'] ?? 0
    );

    // Allow style override via shortcode, default to 5 (modern)
    $style = isset($atts['style']) && !empty($atts['style']) ? $atts['style'] : '5';

    // Display members using the shared display function
    $output .= dacdb_DisplayMembers($xml, $style, $display_atts);

    return $output;
}
