<?php
function dacdb_newsletter($atts)
{
    // Enqueue the newsletter stylesheet
    wp_enqueue_style('show-newsletters');

    global $fDebug, $data_path, $file_path, $options, $wp;
    $options = get_mmp_options(); // Retrieve the plugin options

    $documents = '';

    // Get account and club IDs from options
    $account_id = $options['dacdb_district'];
    $club_id = $options['dacdb_club'];
    $current_url = add_query_arg($wp->query_string, '', home_url($wp->request));

    $folder = isset($_GET["folder"]) ? $_GET["folder"] : '';

    // Create completely new variables for size and date display
    $should_show_size = is_toggle_enabled($options, 'newsletters_show_size');
    $should_show_date = is_toggle_enabled($options, 'newsletters_show_date');

    // Override with shortcode attributes if explicitly provided
    if (isset($atts['size'])) {
        $should_show_size = ($atts['size'] == '1' || $atts['size'] == 1);
    }
    if (isset($atts['date'])) {
        $should_show_date = ($atts['date'] == '1' || $atts['date'] == 1);
    }

    $icon = isset($atts['icon']) ? $atts['icon'] : '0';
    $location = ($options['dacdb_club'] == 0) ? 'newsletters' : 'bulletins';
    $url = $data_path . 'wp_newsletters.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&type=' . $location . '&Weeks=' . $options['newsletters_weeks_page'];
    $xml = dacdb_load_xml($url . '&R=' . rand(), 'newsletters');

    if ($fDebug && dacdb_is_admin()) {
        $documents .= '
            <h5>function <em><strong>dacdb_newsletter</strong></em> called:</h5>
            <h4 class="drawer">Shortcode Settings</h4>
            <pre class="panel">
                <dl>
                    <dt>$options[\'newsletters_weeks_page\']</dt><dd>' . $options['newsletters_weeks_page'] . '</dd>
                    <dt>$options[\'newsletters_show_folders_page\']</dt><dd>' . $options['newsletters_show_folders_page'] . '</dd>
                    <dt>$options[\'newsletters_order_folders_page\']</dt><dd>' . $options['newsletters_order_folders_page'] . '</dd>
                    <dt>$options[\'newsletters_weeks_widget\']</dt><dd>' . $options['newsletters_weeks_widget'] . '</dd>
                </dl>
            </pre>';
        // Show shortcode attributes if there are any
        if (count($atts) > 1) {
            $documents .= '<h4 class="drawer">Shortcode Attributes</h4>
                                    <pre class="panel">
                                        <dl>';
            foreach ($atts as $key => $value) {
                $documents .= '    <dt>$_[\'' . $key . '\']</dt><dd>' . $value . '</dd>';
            }
            $documents .= '</dl>
                        </pre>'; // Close the drawer
        }
        // show URL parameters if there are any (Except Debug)
        if (count($_GET) > 1 || (count($_GET) == 1 && !array_key_exists("debug", $_GET))) {
            $documents .= '<h4 class="drawer">URL Parameters</h4>
                                    <pre class="panel">
                                        <dl>';
            foreach ($_GET as $key => $value) {
                if ($key == "debug") {
                    continue; // Skip the rest of the loop for this iteration
                }
                $documents .= '    <dt>$_[\'' . $key . '\']</dt><dd>' . $value . '</dd>';
            }
            $documents .= '</dl>
                    </pre>'; // Close the drawer
        }
        $documents .= '
                <h4 class="drawer">Named Variables</h4>
                <pre class="panel">
                    <dl>
                        <dt>$folder</dt><dd>' . (isset($folder) && $folder !== '' ? $folder : 'Not set') . '</dd>
                        <dt>$date</dt><dd>' . (isset($date) ? $date : 'Not set') . '</dd>
                        <dt>$icon</dt><dd>' . (isset($icon) ? $icon : 'Not set') . '</dd>
                        <dt>$location</dt><dd>' . (isset($location) ? $location : 'Not set') . '</dd>
                        <dt>$size</dt><dd>' . (isset($size) ? $size : 'Not set') . '</dd>
                    </dl>
                </pre>
                <h4 class="drawer">URLs</h4>
                <pre class="panel">
                    <dl>
                        <dt>$file_path</dt><dd>' . $file_path . '</dd>
                        <dt>$url</dt><dd><a href="' . $url . '" target="debug-tab">' . $url . '</a></dd>
                    </dl>
                </pre>';

        // Debugging output for $xml->newsletter
        $documents .= '
            <h4 class="drawer">XML Output</h4>
                <div class="panel">';
        foreach ($xml->newsletter as $document) {
            $dom = new DOMDocument();
            $dom->preserveWhiteSpace = false; // Don't preserve whitespaces
            $dom->formatOutput = true; // Format output with indentation and line breaks
            $dom->loadXML($document->asXML()); // Load the XML string from SimpleXMLElement
            $formattedXml = $dom->saveXML(); // Save the formatted XML to a string
            $documents .= '<pre>' . htmlspecialchars($formattedXml) . '</pre>';
        }
        $documents .= '
                </div>
            </div>'; // Close the drawer and panel
    }

    if (strlen($xml) == 0) {
        $documents .= 'There are no newsletters to display at this time.';
        return $documents;
    }

    $documents .= '
        <section class="dacdb newsletters">
            <ul>';

    $counter = 1;

    if (empty($_GET["folder"])) { //
        foreach ($xml->newsletter as $document) {
            $name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $document->name);
            $extension = substr(strrchr($document->name, '.'), 1);
            $documents .= '<li>';
            if ($document->type == 'Dir') {
                $documents .= '<a href="' . $current_url . '?folder=' . $folder . '&folder2=' . $document->name . '" target="dacdb-newsletter">'. dacdb_get_file_icon($extension) . trim($name) . '</a>' . $current_url;
            } else {
                if ($icon == 1) {
                    $documents .= '<a href="' . $document->path . '" aria-label="Download ' . $extension . ': ' . trim($name) . '" target="dacdb-newsletter">'. dacdb_get_file_icon($extension) . trim($name) . '</a> ';
                } else {
                    $documents .= '<a href="' . $document->path . '" aria-label="Download ' . $extension . ': ' . trim($name) . '" target="dacdb-newsletter">' . trim($name) . '</a> ';
                }
            }

            // Adding hardcoded debug trace to isolate the issue
            if ($document->type != 'Dir') {
                // Direct option checks for size display - doesn't use intermediate variables
                if (isset($options['newsletters_show_size']) && ($options['newsletters_show_size'] === '1' || $options['newsletters_show_size'] === 1)) {
                    $documents .= '<span class="newsletter__meta newsletter__meta--size">Size: ' . FileSizeConvert($document->size) . '</span>';
                }

                // Direct option checks for date display - doesn't use intermediate variables
                if (isset($options['newsletters_show_date']) && ($options['newsletters_show_date'] === '1' || $options['newsletters_show_date'] === 1)) {
                    $documents .= '<span class="newsletter__meta newsletter__meta--date">Last Modified: ' . $document->datelastmodified . '</span>';
                }
            }

            $documents .= '<br><br></li>';
            $counter = $counter + 1;
        }
    }

    // get folders here
    if ($options['newsletters_show_folders_page'] == 1) {
        $page_title = esc_html(get_the_title());
        if ($folder) {
            $level = 1;
        } else {
            $level = 0;
        }
        $current_url = add_query_arg($wp->query_string, '', home_url($wp->request));
        if ($folder) {
            $documents .= '<div class="breadcrumbs" style="text-align:right;">';
            $documents .= '<a href="' . $current_url . '">' . $page_title . '</a> > ' . $folder;
            $documents .= '</div><br>';
        }
        if ($folder) {
            $folder_url = $data_path . 'newsletter_folders.php?AccountID=' . $account_id . '&ClubID=' . $club_id . '&Folder=' . $folder . '&Sort=' . $options['newsletters_order_folders_page'] . '&R=' . rand();
        } else {
            $folder_url = $data_path . 'newsletter_folders.php?AccountID=' . $account_id . '&ClubID=' . $club_id . '&Folder=&Sort=' . $options['newsletters_order_folders_page'] . '&R=' . rand();
        }
        $nfxml = dacdb_load_xml($folder_url, 'newsletter_folders');
        
        if ($nfxml === false) {
            $nfxml = '';
        }
        if ($nfxml != NULL) {
            foreach ($nfxml->document as $document) {
                $name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $document->name);
                if ($document->type == 0) {

                    if (!$folder) {
                        if (is_front_page()) {
                            $documents .= '<div><strong><a href="' . $current_url . '?folder=' . $document->name . '">' . $document->name . '</a></strong><span class="pull-right" style="float:right;">-</span></div>';
                        } else {
                            $documents .= '<div><strong><a href="' . $current_url . '&folder=' . $document->name . '">' . $document->name . '</a></strong><span class="pull-right" style="float:right;">-</span></div>';
                        }
                        $documents .= '<hr>';
                    }
                } else {
                    $extension = substr(strrchr($document->name, '.'), 1);
                    if ($extension == '') {
                        $extension = '__blank';
                    }

                    // Build the URL for the document
                    if ($folder && $folder2 == '') {
                        $getURL = $file_path . $options['dacdb_district'] . '/Downloads/' . $options['dacdb_club'] . '/' . $folder . '/' . $document->name;
                    } elseif ($folder && $folder2) {
                        $getURL = $file_path . $options['dacdb_district'] . '/Downloads/' . $options['dacdb_club'] . '/' . $folder . '/' . $folder2 . '/' . $document->name;
                    } else {
                        $getURL = $file_path . $options['dacdb_district'] . '/Downloads/' . $options['dacdb_club'] . '/' . trim($document->name);
                    }

                    $documents .= '<a href="' . $getURL . '" target="__blank" class="' . $extension . ' icon">'. dacdb_get_file_icon($extension) . trim($name) . '</a> ';
                    $counter = $counter + 1;
                }
            }
        }
    }
    $documents .= '</section>';
    return $documents;

}