<?php
/**
 * DACdb Plus Newsletter Display Function
 *
 * Handles the display and organization of newsletters/bulletins from DACdb,
 * including folder navigation and file listings with various display options.
 *
 * @package    DACdbPlus
 * @subpackage Display
 * @author     Member Minder Pro, LLC <support@memberminderpro.com>
 * @copyright  2023 Member Minder Pro, LLC
 * @license    GPL-2.0+ 
 * @link       https://www.memberminderpro.com/
 *
 * @wordpress-plugin
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Displays newsletters or bulletins based on shortcode attributes
 *
 * @since 1.0.0
 *
 * @param array $atts {
 *     Shortcode attributes.
 *     
 *     @type string  $date     Whether to show dates (1 for yes, 0 for no)
 *     @type string  $icon     Whether to show file icons (1 for yes, 0 for no)
 *     @type string  $size     Whether to show file sizes (1 for yes, 0 for no)
 * }
 * @return string HTML output of newsletter listing
 */
function dacdb_newsletter($atts)
{
    global $fDebug, $data_path, $file_path, $options, $wp;

    $documents = '';

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

    if ($fDebug) {
        $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"><img class="icon" alt="directory icon" src="' . plugins_url('img/folder.png', __FILE__) . '" width="32">' . trim($name) . '</a>' . $current_url;
            } else {
                if ($icon == 1) {
                    $documents .= '<a href="' . $document->path . '" aria-label="Download ' . $extension . ': ' . trim($name) . '" target="dacdb-newsletter"><img class="icon" alt="' . $extension . ' icon" src="' . plugins_url('img/16px/' . $extension . '.png', __FILE__) . '">' . trim($name) . '</a>';
                } else {
                    $documents .= '<a href="' . $document->path . '" aria-label="Download ' . $extension . ': ' . trim($name) . '" target="dacdb-newsletter">' . trim($name) . '</a>';
                }
            }
            if ($size == 1) {
                $documents .= FileSizeConvert($document->size) . $document->datelastmodified;
            }
            if ($date == 1) {
                $documents .= $document->datelastmodified;
            }
            $documents .= '</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>';
        }
        try {
            if ($folder) {
                $nfxml = @simplexml_load_file($data_path . 'newsletter_folders.php?AccountID=' . $account_id . '&ClubID=' . $club_id . '&Folder=' . $folder . '&Sort=' . $options['newsletters_order_folders_page'] . '&R=' . rand());
            } else {
                $nfxml = @simplexml_load_file($data_path . 'newsletter_folders.php?AccountID=' . $account_id . '&ClubID=' . $club_id . '&Folder=&Sort=' . $options['newsletters_order_folders_page'] . '&R=' . rand());
            }
        } catch (Exception $e) {
            $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';
                    }

                    if ($folder) {
                        $getURL = $file_path;
                        echo $getURL . "<br>";
                        $documents .= '<div><strong><a href="' . $getURL . '" target="__blank">' . $document->name . '</a></strong> - ' . $document->size . '<span class="pull-right" style="float:right;">' . $document->modded . '</span></div>';
                        $documents .= '<hr>';
                    } else {
                        if ($extension == 'pdf') {
                        }
                    }
                    $counter = $counter + 1;
                }
            }
        }
    }
    $documents .= '</section>';
    return $documents;
}