<?php
/**
 * Club Presidents functionality for Member Minder Pro plugin
 * 
 * This file contains the club presidents shortcode implementation.
 * 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
}

/**
 * Register club presidents scripts and styles
 */
function mmpro_register_club_presidents_assets() {
    // Register styles
    wp_register_style('mmpro-club-presidents-style', plugins_url('css/show-club-presidents.css', dirname(__FILE__)), array(), MMPDB_PLUGIN_VERSION);
    
    // Register ColorBox if not already registered
    if (!wp_script_is('jquery-colorbox', 'registered')) {
        $colorbox_cdn_js = 'https://cdn.jsdelivr.net/gh/jackmoore/colorbox@1.6.4/jquery.colorbox-min.js';
        $colorbox_cdn_css = 'https://cdn.jsdelivr.net/gh/jackmoore/colorbox@1.6.4/example1/colorbox.css';
        
        if (url_exists($colorbox_cdn_js) && url_exists($colorbox_cdn_css)) {
            wp_register_script('jquery-colorbox', $colorbox_cdn_js, array('jquery'), '1.6.4', true);
            wp_register_style('jquery-colorbox-style', $colorbox_cdn_css, array(), '1.6.4');
        } else {
            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');
        }
    }
}

// Register assets on init
add_action('init', 'mmpro_register_club_presidents_assets');

/**
 * Main club presidents shortcode function
 *
 * This function displays a grid of club presidents retrieved from DACdb.
 * It can be used with the shortcode [dacdb_plus show=club_presidents]
 *
 * Supported shortcode attributes:
 * - columns: Number of presidents to display per row (1-4) - recommended standard attribute
 * - per_row: Alternative name for 'columns' attribute
 * - presidents_per_row: Legacy attribute for number of presidents per row
 * - club_presidents_per_row: Legacy attribute matching the option name
 *
 * Example usage:
 * [dacdb_plus show=club_presidents columns=1] - Display presidents in a single column
 * [dacdb_plus show=club_presidents columns=2] - Display presidents in two columns
 *
 * If no attributes are specified, the function uses the global plugin setting for 'club_presidents_per_row'.
 *
 * @param array $atts Shortcode attributes
 * @return string HTML output
 */
function mmpro_club_presidents($atts)
{
    global $fDebug, $data_path, $options;

    // Handle direct attribute access for both string and numeric types
    // When the shortcode is called as [dacdb_plus show="club_presidents" columns="1"]
    // The attributes might be passed as strings, so we need to check both ways
    $columns = null;
    $per_row = null;
    $presidents_per_row = null;
    $club_presidents_per_row = null;
    
    // Extract attributes from the array, handling both string and numeric indices
    if (is_array($atts)) {
        // Check for string indices (traditional attributes)
        if (isset($atts['columns'])) {
            $columns = $atts['columns'];
        }
        if (isset($atts['rows'])) {
            $columns = $atts['rows'];
        }
        if (isset($atts['cols'])) {
            $columns = $atts['cols'];
        }
        if (isset($atts['per_row'])) {
            $per_row = $atts['per_row'];
        }
        if (isset($atts['presidents_per_row'])) {
            $presidents_per_row = $atts['presidents_per_row'];
        }
        if (isset($atts['club_presidents_per_row'])) {
            $club_presidents_per_row = $atts['club_presidents_per_row'];
        }
    }
    
    // Ensure assets are registered (in case init hook hasn't run)
    if (!wp_script_is('mmpro-club-presidents-style', 'registered')) {
        mmpro_register_club_presidents_assets();
    }

    // Enqueue required styles and scripts
    wp_enqueue_style('mmpro-club-presidents-style');
    wp_enqueue_style('jquery-colorbox-style');
    wp_enqueue_script('jquery-colorbox');

    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];
    $leaders = '';

    // Determine number of presidents per row, checking attributes with priority
    // First check the standard attribute names, then legacy ones, then fall back to plugin option
    $presidentsPerRow = null;
    if (!empty($columns)) {
        $presidentsPerRow = (int)$columns;
    } elseif (!empty($rows)) {
        $presidentsPerRow = (int)$rows;
    } elseif (!empty($cols)) {
        $presidentsPerRow = (int)$cols;
    } elseif (!empty($per_row)) {
        $presidentsPerRow = (int)$per_row;
    } elseif (!empty($presidents_per_row)) {
        $presidentsPerRow = (int)$presidents_per_row;
    } elseif (!empty($club_presidents_per_row)) {
        $presidentsPerRow = (int)$club_presidents_per_row;
    } else {
        $presidentsPerRow = isset($options['club_presidents_per_row']) ? (int)$options['club_presidents_per_row'] : 1;
    }
    
    // Ensure value is between 1 and 4
    $presidentsPerRow = max(1, min(4, $presidentsPerRow));

    if ($fDebug && dacdb_is_admin()) {
        $leaders .= "=================================================================<BR>";
        $leaders .= "function dacdb_club_presidents called<br>";
        $leaders .= "AccountID=" . $account_id . "<br>";
        $leaders .= "leaders_contact_link=" . $options['leaders_contact_link'] . "<br>";
        $leaders .= "data_path=" . $data_path . "<br>";
        $leaders .= "ClubID=" . $club_id . "<br>";
        $leaders .= "Presidents per row=" . $presidentsPerRow . "<br>";
        if (is_array($atts)) {
            $leaders .= "Passed attributes: " . print_r($atts, true) . "<br>";
        }
        $leaders .= "URL=" . $data_path . 'wp_ccp.cfm?AccountID=' . $account_id . '&ClubID=' . $club_id . '&RoleKey=P&SortBy=C<br>';
        $leaders .= "=================================================================<BR>";
    }

    try {
        $xml = simplexml_load_file($data_path . 'wp_ccp.cfm?AccountID=' . $account_id . '&RoleKey=P&SortBy=C' . '&R=' . rand());
        if (strlen($xml) == 0) {
            $leaders .= 'There are no club presidents to display at this time.';
            return $leaders;
        }
    } catch (Exception $e) {
        return 'Error: ' . $e->getMessage();
    }
    $counter = 1;
    $cnt = 0;
    $lastCounter = count($xml->ccp);
    foreach ($xml->ccp as $ccp) {
        $grid_counter = isset($grid_counter) ? $grid_counter + 1 : 1;

        if ($presidentsPerRow == 1) {
            $grid_counter = 1; // force single row
        }

        if ($grid_counter == 1) {
            $leaders .= '<div class="dac-row">';
        }

        $presidentClasses = [
            1 => 'members dac-col-xs-12',
            2 => 'members dac-col-xs-12 dac-col-sm-6',
            3 => 'members dac-col-xs-12 dac-col-sm-12 dac-col-md-4',
            4 => 'members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3'
        ];

        $leaders .= '<div class="' . ($presidentClasses[$presidentsPerRow] ?? 'members') . '">';

        // Adjust div and image widths based on number of presidents per row
        $setDivWidth = ($presidentsPerRow == 4) ? 120 : 150;
        $setImgWidth = ($presidentsPerRow == 4) ? 110 : 140;

        if (
            $ccp->image == ''
        ) {
            $leaders .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . MMPDB_PLUGIN_URL . 'img/avatar.svg" style="aspect-ratio: 4 / 5; width: ' . $setImgWidth  . 'px; object-fit: cover;" width="' . $setImgWidth  . '"></td>';
        } else {
            $leaders .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . $ccp->imgpath . '' . $ccp->image . '" style="aspect-ratio: 4 / 5; width: ' . $setImgWidth  . 'px; object-fit: cover;" width="' . $setImgWidth  . '"></td>';
        }
        $leaders .= '<td style="border:0 !important;max-width:1px;width:1px;padding:0;">&nbsp;</td>';
        $leaders .= '<td style="border:0 !important;vertical-align: top;padding:0;">';
        $leaders .= '<strong>' . $ccp->membername . '</strong><br>' . $ccp->clubname . '<br>';
        if ($options['leaders_contact_link'] == 1) {
            $leaders .= '       <a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $ccp->userid . '" name="dlc-inline-link-' . $cnt . '" class="modal-link">Contact</a>';
        }
        $leaders .= '</td>';


        $leaders .= '</tr></table></div>';
        $cnt++;
        if ($grid_counter == $presidentsPerRow) {
            $leaders .= '</div>';
            $grid_counter = 0;
        }
    }
    if ($grid_counter > 0) {
        $leaders .= '</div><!-- end  -->';
    }
    return $leaders;
}

/**
 * Legacy function for backward compatibility
 */
function dacdb_club_presidents($atts) {
    // Add debug output to see what attributes are coming in
    if (defined('WP_DEBUG') && WP_DEBUG) {
        error_log('dacdb_club_presidents received attributes: ' . print_r($atts, true));
    }
    
    return mmpro_club_presidents($atts);
}
