<?php
/**
 * DACdb Plus Widget Class
 *
 * @package   DACdbPlus
 * @author    Member Minder Pro, LLC <wordpress@memberminderpro.com>
 * @copyright 2025 Member Minder Pro, LLC
 * @license   Apache License 2.0
 * @link      https://memberminderpro.com
 */

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

/**
 * DACdb Plus Widget Class
 *
 * Provides widget functionality for displaying DACdb Plus content in sidebars.
 */
class dacdb_plus_widget extends WP_Widget {
    /**
     * Constructor
     */
    function __construct() {
        parent::__construct(
            // Base ID of your widget
            'dacdb_plus_widget',
            // Widget name will appear in UI
            __( 'DACdb Plus', 'dacdb_plus_widget' ),
            // Widget description
            array( 'description' => __( 'Allows you to display your DACdb Plus Wigets in your sidebars', 'dacdb_plus_widget' ) )
        );
    }

    /**
     * Creating widget front-end
     *
     * @param array $args     Widget arguments.
     * @param array $instance Saved values from database.
     */
    public function widget( $args, $instance ) {
        global $fDebug, $data_path, $file_path, $options, $catid;

        // Initialize variables to avoid linter errors
        $pagedata = '';
        $catid = '';
        
        $options = get_mmp_options();
        error_log( print_r( $options, true ) ); // Check the PHP error log to see the output

        $title = apply_filters( 'widget_title', $instance['title'] );

        $show = $instance['show'];
        $count = $instance['count'];
        $club_id = isset( $instance['club_id'] ) && $instance['club_id'] !== '' ? $instance['club_id'] : $options['dacdb_club'];

        setDataPath(); // ShortCode DACdb or iMembersDB paths

        if ( $data_path == '' ) {
            $pagedata .= "=================================================================<BR>";
            $pagedata .= "Missing System selction under Plugin Settings!<BR>";
            $pagedata .= "=================================================================<BR>";
            $pagedata .= "<BR>";
        }

        // $subscription = file_get_contents($data_path.'wp_subscription.cfm?AccountId='.$options['dacdb_district'].'&ClubID='.$options['dacdb_club']);
        $xml = simplexml_load_file( $data_path . 'wp_subscription2.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&R=' . rand() );
        //  if ( $subscription != '1' )  {
        if ( $xml->status != '1' ) {
            $pagedata .= "=================================================================<BR>";
            $pagedata .= "&nbsp; &nbsp;  Missing subscription record. System=" . $options['dacdb_system'] . ", AccountID=" . $options['dacdb_district'] . ", ClubID=" . $options['dacdb_club'] . "<BR>";
            $pagedata .= "&nbsp; &nbsp;  Please contact: support@memberminderpro.com<BR>";
            $pagedata .= "subscription=" . $xml->status . "<br>";
            if ( $fDebug && dacdb_is_admin() ) {
                $pagedata .= "&nbsp; &nbsp;  url=" . $data_path . 'wp_subscription2.cfm?AccountId=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . "<BR>";
            }
            $pagedata .= "=================================================================<BR>";
            $pagedata .= "<BR>";
        }

        if ( $fDebug && dacdb_is_admin() ) {
            $pagedata .= "=================================================================<BR>";
            $pagedata .= "Version=" . MMPDB_PLUGIN_VERSION . "<br>";
            $pagedata .= "Show=" . $show . "<br>";
            $pagedata .= "CatID=" . $catid . "<br>";
            $pagedata .= "System=" . $options['dacdb_system'] . "<BR>";
            $pagedata .= "data_path=" . $data_path . "<BR>";
            $pagedata .= "file_path=" . $file_path . "<BR>";
            $pagedata .= "subscription=" . $xml->status . "<BR>";
            $pagedata .= "=================================================================<BR>";
        }

        // Initialize show flags
        $show_stories = 0;
        $show_events = 0;
        $show_speakers = 0;
        $show_leaders = 0;
        $show_members = 0;
        $show_birthdays = 0;
        $show_club_meetings = 0;
        $show_newsletters = 0;
        $show_sponsors = 0;
        $show_meeting_info = 0;
        $show_d_events = 0;

        // before and after widget arguments are defined by themes
        echo $args['before_widget'];
        if ( ! empty( $title ) ) {
            echo $args['before_title'] . $title . $args['after_title'];
        }
        
        //            $subscription = file_get_contents($data_path.'wp_conf.cfm?AccountId='.$options['dacdb_district'].'&ClubID='.$options['dacdb_club']);
        //Handle Shortcode story show
        if ( $show == 'stories' ) {
            $show_stories = 1;
        } elseif ( $show == 2 ) {
            $show_events = 1;
        } elseif ( $show == 3 ) {
            $show_d_events = 1;
        } elseif ( $show == 7 ) {
            $show_speakers = 1;
        } elseif ( $show == 5 ) {
            $show_leaders = 1;
        } elseif ( $show == 4 ) {
            $show_birthdays = 1;
        } elseif ( $show == 1 ) {
            $show_meeting_info = 1;
        } elseif ( $show == 6 ) {
            $show_newsletters = 1;
        } elseif ( $show == 8 ) {
            $show_sponsors = 1;
        }
        
        // Handle Meeting Info
        if ( isset( $show_meeting_info ) && $show_meeting_info == 1 ) {
            if ( ! $club_id ) {
                $club_id = $options['dacdb_club'];
            }

            if ( $fDebug && function_exists( 'dacdb_is_admin' ) && dacdb_is_admin() ) {
                $meetings = "";
                $meetings .= "=======================<BR>";
                $meetings .= "function widget show_meeting_info<br>";
                $meetings .= "AccountID=" . $options['dacdb_district'] . "<br>";
                $meetings .= "ClubID=" . $options['dacdb_club'] . "<br>";
                $meetings .= "URL=" . $data_path . 'wp_club_meetings.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $club_id . '<br>';
                $meetings .= "=======================<BR>";
                echo $meetings;
            }
            
            $xml = simplexml_load_file( $data_path . 'wp_club_meetings.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $club_id . '&R=' . rand() );
            $meetings = array();
            $counter = 1;
            foreach ( $xml->meeting as $wcm ) {
                echo '<div class="side-meeting-info">';
                echo '<span class="side-meeting-info-dt">' . $wcm->meetingday . 's at ' . $wcm->meetingtime . '</span><br/>';
                echo '<strong>' . $wcm->meetingplace . '</strong><br>';
                echo $wcm->meetingaddress . '<br>';
                echo $wcm->meetingcity . ', ' . $wcm->meetingstatecode . ' ' . $wcm->meetingpostalcode . '<br/>';
                if ( $wcm->latlng != "" ) {
                    echo '<span style="float:right;"><a href="' . $wcm->latlng . '" target="new">Map It</a></span>';
                }
                echo '<br></div>';
                $counter = $counter + 1;
            }
            $meet_total = count( $xml->meeting );
            if ( $meet_total == 0 ) {
                echo 'There are no club meetings to display at this time.';
            }
        }

        // Handle Events
        if ( isset( $show_events ) && $show_events == 1 ) {
            if ( ! $club_id ) {
                $club_id = $options['dacdb_club'];
            } else {
                $byShowSpeaker = 1;
            }

            // Set category IDs and months
            $categoryids = '';
            $mo = '';
            if ( $club_id == 0 ) {
                $categoryids = isset( $options['district_events_types_page'] ) ? $options['district_events_types_page'] : '';
                $mo = isset( $options['district_events_months_side'] ) ? $options['district_events_months_side'] : '';
            } else {
                $categoryids = isset( $options['club_events_types_page'] ) ? $options['club_events_types_page'] : '';
                $mo = isset( $options['club_events_months_side'] ) ? $options['club_events_months_side'] : '';
            }
            
            $xml = simplexml_load_file( $data_path . 'wp_event.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&CatIDS=' . $categoryids . '&Mo=' . $mo . '&R=' . rand() );
            $events = array();
            $counter = 1;
            $showEvent = 1;

            $event_total = count( $xml->event );
            foreach ( $xml->event as $event ) {
                if ( isset( $options['club_events_show_speakers_side'] ) && $options['club_events_show_speakers_side'] == 0 && $event->speaker != '' ) {
                    $showEvent = 0;
                } else if ( isset( $options['club_events_show_speakers_side'] ) && $options['club_events_show_speakers_side'] == 0 && $event->speaker == '' ) {
                    $showEvent = 1;
                }

                if ( isset( $byShowSpeaker ) && $byShowSpeaker == 1 && $event->speaker == '' ) {
                    $showEvent = 1;
                }

                if ( $showEvent == 1 ) {
                    if ( $count >= $counter ) {
                        echo '<div class="side-club-event" style="line-height:1.5;">';
                        if ( isset( $options['events_global_date'] ) && $options['events_global_date'] == 1 ) {
                            if ( date( "Y-m-d", strtotime( $event->startdate ) ) == date( "Y-m-d", strtotime( $event->enddate ) ) ) {
                                echo date( "F jS Y", strtotime( $event->startdate ) ) . ' ' . date( "g:i a", strtotime( $event->startdate ) );
                            } else {
                                echo date( "M jS", strtotime( $event->startdate ) ) . ' - ' . date( "M jS Y", strtotime( $event->enddate ) ) . ' ' . date( "g:i a", strtotime( $event->startdate ) );
                            }
                            echo '<br>';
                        }

                        echo '<strong>' . $event->eventname . '</strong><br>';

                        if ( isset( $options['club_events_show_speakers_side_info'] ) && $options['club_events_show_speakers_side_info'] == 1 ) {
                            if ( $event->speaker != "" ) {
                                echo '<br><strong>Speaker: ' . $event->speaker . '</strong>';
                            }
                            if ( $event->topic != "" ) {
                                echo '<br>Topic: ' . $event->topic;
                            }
                        }

                        if ( isset( $options['events_global_date'] ) && $options['events_global_date'] == 0 ) {
                            echo '<br>';
                            if ( date( "Y-m-d", strtotime( $event->startdate ) ) == date( "Y-m-d", strtotime( $event->enddate ) ) ) {
                                echo date( "F jS Y", strtotime( $event->startdate ) ) . ' ' . date( "g:i a", strtotime( $event->startdate ) );
                            } else {
                                echo date( "M jS", strtotime( $event->startdate ) ) . ' - ' . date( "M jS Y", strtotime( $event->enddate ) ) . ' ' . date( "g:i a", strtotime( $event->startdate ) );
                            }
                        }

                        echo '<br>';
                        echo '<a class="iframe2 cboxElement" href="' . $data_path . 'R_Event.cfm?EventID=' . $event->eventid . '" style="float:right;">More info</a>';
                        echo '<br>';
                        if ( $count > $counter && $counter < $event_total ) {
                            echo '<hr>';
                        }
                        $counter = $counter + 1;
                        echo '</div>';
                    }
                }
            }
            if ( $event_total == 0 ) {
                echo 'There are no events at this time.';
            }
        }

        // Add placeholder for other content types
        if ( isset( $show_stories ) && $show_stories == 1 ) {
            echo 'Stories widget content will appear here.';
        }
        
        if ( isset( $show_d_events ) && $show_d_events == 1 ) {
            echo 'District Events widget content will appear here.';
        }
        
        if ( isset( $show_birthdays ) && $show_birthdays == 1 ) {
            echo 'Birthdays widget content will appear here.';
        }
        
        if ( isset( $show_leaders ) && $show_leaders == 1 ) {
            echo 'Leadership widget content will appear here.';
        }
        
        if ( isset( $show_newsletters ) && $show_newsletters == 1 ) {
            echo 'Newsletters widget content will appear here.';
        }
        
        if ( isset( $show_speakers ) && $show_speakers == 1 ) {
            echo 'Speakers widget content will appear here.';
        }
        
        if ( isset( $show_sponsors ) && $show_sponsors == 1 ) {
            echo 'Sponsors widget content will appear here.';
        }
        
        // Close widget
        echo $args['after_widget'];
    }

    /**
     * Widget Backend
     *
     * @param array $instance Previously saved values from database.
     */
    public function form( $instance ) {
        $options = get_mmp_options();
        if ( isset( $instance['title'] ) ) {
            $title = $instance['title'];
            $show = $instance['show'];
            $club_id = isset( $instance['club_id'] ) ? $instance['club_id'] : '';
            $count = isset( $instance['count'] ) ? $instance['count'] : '';
        } else {
            $title = __( '', 'dacdb_plus_widget' );
            $show = '';
            $club_id = '';
            $count = '';
        }
    ?>
        <p>
            <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>">
            <label for="<?php echo $this->get_field_id( 'club_id' ); ?>"><?php _e( '^Club ID:' ); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id( 'club_id' ); ?>" name="<?php echo $this->get_field_name( 'club_id' ); ?>" value="<?php echo esc_attr( $club_id ); ?>">
            <label for="<?php echo $this->get_field_id( 'show' ); ?>"><?php _e( 'Show:' ); ?></label>
            <select class="widefat" id="<?php echo $this->get_field_id( 'show' ); ?>" name="<?php echo $this->get_field_name( 'show' ); ?>">
                <option value="<?php echo $show; ?>">
                    <?php if ( $show == '1' ) {
                        echo 'Meeting Info';
                    } elseif ( $show == '2' ) {
                        echo 'Events';
                    } elseif ( $show == '3' ) {
                        echo 'District Events';
                    } elseif ( $show == '4' ) {
                        echo 'Birthdays';
                    } elseif ( $show == '5' ) {
                        echo 'Leadership';
                    } elseif ( $show == '6' ) {
                        echo 'Newsletters';
                    } elseif ( $show == '7' ) {
                        echo 'Speakers';
                    } elseif ( $show == '8' ) {
                        echo 'Sponsors';
                    } else {
                        echo 'Select One';
                    } ?></option>
                <?php if ( $options['dacdb_club'] == 0 ) { ?>
                    <option value="3">*District Events</option>
                    <option value="6">*Newsletters</option>
                    <option value="7">*Speakers</option>
                    <option value="8">Sponsors</option>
                <?php } else { ?>
                    <option value="1">^ Meeting Info</option>
                    <option value="5">^ Leadership</option>
                    <option value="4">Birthdays</option>
                    <option value="8">^ Sponsors</option>
                    <option value="2">*^ Events</option>
                    <option value="3">*District Events</option>
                    <option value="6">*Newsletters</option>
                    <option value="7">*Speakers</option>
                <?php } ?>
            </select>
            <label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( '*Number of items to display:' ); ?></label>
            <select class="widefat" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>">
                <option></option>
                <option value="1" <?php if ( $count == '1' ) {
                                        echo 'selected';
                                    } ?>>1</option>
                <option value="2" <?php if ( $count == '2' ) {
                                        echo 'selected';
                                    } ?>>2</option>
                <option value="3" <?php if ( $count == '3' ) {
                                        echo 'selected';
                                    } ?>>3</option>
                <option value="4" <?php if ( $count == '4' ) {
                                        echo 'selected';
                                    } ?>>4</option>
                <option value="5" <?php if ( $count == '5' ) {
                                        echo 'selected';
                                    } ?>>5</option>
                <option value="6" <?php if ( $count == '6' ) {
                                        echo 'selected';
                                    } ?>>6</option>
                <option value="7" <?php if ( $count == '7' ) {
                                        echo 'selected';
                                    } ?>>7</option>
                <option value="8" <?php if ( $count == '8' ) {
                                        echo 'selected';
                                    } ?>>8</option>
                <option value="9" <?php if ( $count == '9' ) {
                                        echo 'selected';
                                    } ?>>9</option>
                <option value="10" <?php if ( $count == '10' ) {
                                        echo 'selected';
                                    } ?>>10</option>
                <option value="11" <?php if ( $count == '11' ) {
                                        echo 'selected';
                                    } ?>>11</option>
                <option value="12" <?php if ( $count == '12' ) {
                                        echo 'selected';
                                    } ?>>12</option>
                <option value="13" <?php if ( $count == '13' ) {
                                        echo 'selected';
                                    } ?>>13</option>
                <option value="14" <?php if ( $count == '14' ) {
                                        echo 'selected';
                                    } ?>>14</option>
                <option value="15" <?php if ( $count == '15' ) {
                                        echo 'selected';
                                    } ?>>15</option>
                <option value="16" <?php if ( $count == '16' ) {
                                        echo 'selected';
                                    } ?>>16</option>
                <option value="17" <?php if ( $count == '17' ) {
                                        echo 'selected';
                                    } ?>>17</option>
                <option value="18" <?php if ( $count == '18' ) {
                                        echo 'selected';
                                    } ?>>18</option>
                <option value="19" <?php if ( $count == '19' ) {
                                        echo 'selected';
                                    } ?>>19</option>
                <option value="20" <?php if ( $count == '20' ) {
                                        echo 'selected';
                                    } ?>>20</option>
            </select>
        </p>
    <?php
    }
    
    /**
     * Updating widget replacing old instances with new
     *
     * @param array $new_instance New values for widget.
     * @param array $old_instance Previous values for widget.
     * @return array Updated safe values to be saved.
     */
    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
        $instance['show'] = ( ! empty( $new_instance['show'] ) ) ? strip_tags( $new_instance['show'] ) : '';
        $instance['count'] = ( ! empty( $new_instance['count'] ) ) ? strip_tags( $new_instance['count'] ) : '';
        $instance['club_id'] = ( ! empty( $new_instance['club_id'] ) ) ? strip_tags( $new_instance['club_id'] ) : '';
        return $instance;
    }
} 