<?php
//SECTION - Utility Functions

//ANCHOR - Format Club URL
/**
 * Formats a domain name URL with the https:// protocol.
 *
 * @param string $url The URL to format.
 * @return string The formatted URL with the https:// protocol.
 */
function formatDomainToUrl($url)
{
    // Trim whitespace and ensure the URL has a protocol for filter_var validation
    $url = trim($url);
    if (!preg_match('~^(?:f|ht)tps?://~i', $url)) {
        // Temporarily prepend 'https://' for validation purposes
        $validatedUrl = 'https://' . $url;
    } else {
        $validatedUrl = $url;
    }

    // Validate the URL format
    if (!filter_var($validatedUrl, FILTER_VALIDATE_URL)) {
        // If the URL does not pass validation, return an empty string or a specific invalid URL indication
        return '';
    }

    // If the original URL didn't have a protocol, prepend 'https://'
    if (!preg_match('~^(?:f|ht)tps?://~i', $url)) {
        $url = 'https://' . $url;
    }

    return $url;
}

//ANCHOR - Round Down
/**
 * Rounds a number down to a specified precision level.
 *
 * @param float $number The number that needs to be rounded down.
 * @param int $precision (Optional) The number of decimal places to which the number should be rounded down. Default is 2.
 * @return float The rounded down number.
 */
function round_down($number, $precision = 2)
{
    $fig = (int) str_pad('1', $precision, '0');
    return (floor($number * $fig) / $fig);
}

//ANCHOR - Strip HTML
/**
 * Strips HTML tags from a string.
 *
 * @param string $tag The HTML tag or tags to be stripped. Multiple tags can be provided as a comma-separated string.
 * @param string $string The input string from which the HTML tags should be removed.
 * @return string The modified string with the specified HTML tags removed.
 */
function strip_html($tag, $string)
{
    $string = preg_replace('/<' . $tag . '[^>]*>/i', '', $string);
    $string = preg_replace('/<\/' . $tag . '>/i', '', $string);
    return $string;
}

//ANCHOR - File Size Convert
/**
 * Converts a file size in bytes to a more human-readable format.
 *
 * @param float $bytes The file size in bytes to be converted.
 * @return string The converted file size with the appropriate unit.
 */
function FileSizeConvert($bytes)
{
    $bytes = floatval($bytes);
    $arBytes = array(
        0 => array(
            "UNIT" => "TB",
            "VALUE" => pow(1024, 4)
        ),
        1 => array(
            "UNIT" => "GB",
            "VALUE" => pow(1024, 3)
        ),
        2 => array(
            "UNIT" => "MB",
            "VALUE" => pow(1024, 2)
        ),
        3 => array(
            "UNIT" => "KB",
            "VALUE" => 1024
        ),
        4 => array(
            "UNIT" => "B",
            "VALUE" => 1
        ),
    );
    foreach ($arBytes as $arItem) {
        if ($bytes >= $arItem["VALUE"]) {
            $result = $bytes / $arItem["VALUE"];
            $result = str_replace(".", ".", strval(round($result, 0))) . " " . $arItem["UNIT"];
            break;
        }
    }
    return $result;
}

// ANCHOR - Add Google Analytics
function add_googleanalytics()
{
    global $options;

    if (isset($options['ua_tracking_id']) && !empty($options['ua_tracking_id'])) {

        echo "<!-- DACdbPlus Google Analytics Tracking Integration -->\n";
        $tracking_id = trim($options['ua_tracking_id']);

        // Ensure the tracking ID is not empty or null before proceeding
        if (empty($tracking_id)) {
            // Optionally log an error or display an admin notice if the tracking ID is missing
            echo "<!-- GA Tracking ID missing -->\n"; // Debugging message
            return;
        } else {
            // Remove any leading or trailing whitespace from the tracking ID
            $tracking_id = trim($tracking_id);
        }

        // Determine the type of tracking code to use based on the format of the tracking ID
        if (preg_match('/^UA-\d{4,10}-\d{1,4}$/', $tracking_id)) {
            // Universal Analytics (UA) tracking code
            echo "<script>
                    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

                    ga('create', '" . esc_js($tracking_id) . "', 'auto');
                    ga('send', 'pageview');
                </script>\n";
        } elseif (preg_match('/^G-\w+/', $tracking_id)) {
            // Google Analytics 4 (GA4) tracking code 
?>

            <!-- Google tag (gtag.js) -->
            <script async src="https://www.googletagmanager.com/gtag/js?id=<?= esc_attr($tracking_id); ?>"></script>
            <script>
                window.dataLayer = window.dataLayer || [];

                function gtag() {
                    dataLayer.push(arguments);
                }
                gtag('js', new Date());
                gtag('config', '<?= esc_attr($tracking_id); ?>');
            </script>

<?php
        } elseif (preg_match('/^GTM-\w+/', $tracking_id)) {
            // Google Tag Manager (GTM) code
            echo "<!-- Google Tag Manager -->
                <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
                new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
                j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
                'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
                })(window,document,'script','dataLayer','" . esc_js($tracking_id) . "');</script>
                <!-- End Google Tag Manager -->\n";
        } else {
            echo "<!-- Unsupported or unknown ID format -->\n"; // Debugging message
            // Log an error or display a notice for unsupported or unknown ID format
        }
    }
}

add_action('wp_head', 'add_googleanalytics', 1);

// ANCHOR - Fetch the Plugin Options from WPDB
function get_mmp_options()
{
    // Attempt to fetch "mmp" options first
    $options = get_option('mmp_plus_options');

    // If "mmp" options are not found, attempt to migrate from "dacdb_plus_options"
    if ($options === false) {
        $old_options = get_option('dacdb_plus_options');
        if ($old_options !== false) {
            // "dacdb_plus_options" found, migrate to "mmp_plus_options"
            update_option('mmp_plus_options', $old_options);
            // delete_option('dacdb_plus_options'); // For now, do not delete "dacdb_plus_options" to preserve it as a backup

            $options = $old_options;
        } else {
            // Initialize with defaults if neither option set is found
            $options = array(
                // Define your default options array here
                // e.g., 'club' => 0, 'district' => '', 'system' => 'DACdb',
            );
        }
    }

    return $options;
}

function formatDateToISO($dateString) {
    $date = new DateTime($dateString);
    return $date->format(DateTime::ATOM); // Outputs ISO 8601 date
}
function normalize_boolean($value) {
    $true_values = ['1', 'true', 'yes'];
    $false_values = ['0', 'false', 'no'];

    if (in_array(strtolower($value), $true_values, true)) {
        return 1;
    }

    if (in_array(strtolower($value), $false_values, true)) {
        return 0;
    }

    // Default to false if not explicitly true
    return 0;
}

//ANCHOR - Check URL Exists
/**
 * Checks if a URL exists by making a HEAD request.
 *
 * @param string $url The URL to check.
 * @return bool True if the URL exists and returns a 200 status code, false otherwise.
 */
function url_exists($url) {
    $headers = @get_headers($url);
    return $headers && strpos($headers[0], '200') !== false;
}

/**
 * Check if the current user has admin capabilities
 * 
 * @return bool True if the user has admin capabilities, false otherwise
 */
function dacdb_is_admin() {
    return current_user_can('manage_options') || current_user_can('edit_posts') || current_user_can('edit_pages');
}

/**
 * Check if we're in a page builder environment
 *
 * @return boolean True if we're in a page builder environment
 */
function dacdb_is_page_builder() {
    return (
        defined('BRICKS_VERSION') || // Bricks Builder
        defined('ELEMENTOR_VERSION') || // Elementor
        defined('WPB_VC_VERSION') // WPBakery
    );
}

//ANCHOR - Get File Icon
/**
 * Get the appropriate icon for a file based on its extension
 * 
 * @param string $extension The file extension
 * @return string HTML for the icon with appropriate classes
 */
function dacdb_get_file_icon($extension) {
    // Convert extension to lowercase for consistency
    $extension = strtolower($extension);
    
    // Special case for folders - use Font Awesome
    if ($extension === 'folder') {
        return '<i class="fas fa-folder dacdb-file-icon"></i>';
    }
    
    // Map file extensions to their corresponding icons in the JSDelivr file-icon library
    $icon_map = array(
        // Microsoft Office
        'doc' => 'Microsoft-Word',
        'docx' => 'Microsoft-Word',
        'xls' => 'Microsoft-Excel',
        'xlsx' => 'Microsoft-Excel',
        'ppt' => 'Microsoft-PowerPoint',
        'pptx' => 'Microsoft-PowerPoint',
        'pub' => 'Microsoft-Publisher',
        'vsd' => 'Microsoft-Visio',
        'vsdx' => 'Microsoft-Visio',
        'mpp' => 'Microsoft-Project',
        'accdb' => 'Microsoft-Access',
        
        // PDF and Documents
        'pdf' => 'Adobe-Acrobat',
        'docbook' => 'DocBook',
        'asciidoc' => 'AsciiDoc',
        
        // Images
        'jpg' => 'Image',
        'jpeg' => 'Image',
        'png' => 'Image',
        'gif' => 'Image',
        'tiff' => 'Image',
        'bmp' => 'Image',
        
        // Archives
        'zip' => 'ZIP',
        'rar' => 'RAR',
        '7z' => '7Z',
        
        // Text files
        'txt' => 'Text',
        'csv' => 'CSV',
        'md' => 'Markdown',
        
        // Other common formats
        'url' => 'URL',
        'lnk' => 'Shortcut'
    );
    
    // Get the icon name from the map, or use 'Default' if not found
    $icon_name = isset($icon_map[$extension]) ? $icon_map[$extension] : 'Default';
    
    // Add the appropriate CSS class for color styling
    $icon_class = 'dacdb-icon-' . strtolower($extension);
    
    // Return the icon HTML using JSDelivr file-icon library
    return sprintf(
        '<img src="https://cdn.jsdelivr.net/gh/file-icons/icons@master/svg/%s.svg" alt="%s icon" class="dacdb-file-icon %s" onerror="this.onerror=null; this.src=\'https://cdn.jsdelivr.net/gh/file-icons/icons@master/svg/Default.svg\';">',
        esc_attr($icon_name),
        esc_attr($extension),
        esc_attr($icon_class)
    );
}

/**
 * Enqueues the file-icons CSS file
 */
function dacdb_enqueue_file_icons_css() {
    wp_enqueue_style(
        'dacdb-file-icons',
        plugin_dir_url(dirname(__FILE__)) . 'css/file-icons.css',
        array(),
        '1.0.0'
    );
}

/**
 * Robust XML loading function with fallback to wp_remote_get
 * 
 * @param string $url The URL to load XML from
 * @param string $context Context for error logging (e.g., 'committee', 'subscription')
 * @return SimpleXMLElement|false XML object on success, false on failure
 */
function dacdb_load_xml($url, $context = 'unknown') {
    // Enable error handling for XML
    $old_setting = libxml_use_internal_errors(true);
    libxml_clear_errors();
    
    $xml = @simplexml_load_file($url);
    
    // Check for XML errors
    $xml_errors = libxml_get_errors();
    libxml_use_internal_errors($old_setting);
    
    if ($xml === false || !empty($xml_errors)) {
        // Log the error if WP_DEBUG is enabled
        if (defined('WP_DEBUG') && WP_DEBUG === true) {
            error_log("DACdb Plus: Failed to load {$context} XML from: {$url}");
            foreach ($xml_errors as $error) {
                error_log("DACdb Plus: XML Error in {$context}: XML Error {$error->code}: {$error->message}");
            }
        }
        
        // Try alternative method using wp_remote_get
        $response = wp_remote_get($url, array(
            'timeout' => 10,
            'sslverify' => false, // Temporarily disable SSL verification for debugging
            'user-agent' => 'WordPress/DACdb Plus Plugin'
        ));
        
        if (is_wp_error($response)) {
            if (defined('WP_DEBUG') && WP_DEBUG === true) {
                error_log("DACdb Plus: wp_remote_get error in {$context}: " . $response->get_error_message());
            }
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $xml = simplexml_load_string($body);
        
        if ($xml === false) {
            if (defined('WP_DEBUG') && WP_DEBUG === true) {
                error_log("DACdb Plus: Failed to parse {$context} XML response: " . substr($body, 0, 200));
            }
            return false;
        }
    }
    
    return $xml;
}

//!SECTION - Utility Functions