<?php
//SECTION - Utility Functions

// Version check first
if (version_compare(get_bloginfo('version'), '5.0', '<')) {
    return;
}

//SECTION - Directory Management
function is_correct_dacdb_directory() {
    $plugin_file = realpath(dirname(__DIR__) . '/dacdbplus.php');
    $current_dir = basename(dirname($plugin_file));
    return $current_dir === 'dacdbplus';
}

//SECTION - Error Handling
/**
 * Display an error message indicating that the DACdb plugin account number is missing.
 */
if (!function_exists('dacdb_missing_district')) {
    function dacdb_missing_district()
    {
        global $pagenow;

        // Store the error message in a variable
        $error_message = __('A valid district, grand lodge, or account number is required.', 'dacdbplus');

        // Define the URL of your specific settings page.
        $settings_url = admin_url('options-general.php?page=mmp-settings');
        // Define the URL for your external customer support page.
        $support_url = 'https://www.dacdbsupport.com';

        // Check if the current page is the settings page
        if ($pagenow == 'options-general.php' && isset($_GET['page']) && $_GET['page'] == 'mmp-settings') {
            ?>
            <div class="updated settings-error error is-dismissible" style="padding: 10px;">
                <h2 style="margin: 0px;">DACdb Plus: <?php echo $error_message; ?></h2>
            </div>
            <?php
        } else {
            ?>
            <div class="updated settings-error error is-dismissible" style="display: flex; justify-content: space-between; align-items: center;">
                <h2 style="margin: 0;"><?php echo '<a href="' . esc_url($settings_url) . '" title="Click to access DACdb Plus plugin settings">DACdb Plus</a>: ' . $error_message . ''; ?></h2>
                <!-- Container for buttons to ensure they stay together -->
                <div>
                    <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary" style="margin: 10px;">
                        <?php _e('Go to Settings', 'dacdbplus'); ?>
                    </a>
                    <a href="<?php echo esc_url($support_url); ?>" class="button button-secondary" style="margin: 10px 0;">
                        <?php _e('Get Support', 'dacdbplus'); ?>
                    </a>
                </div>
            </div>
            <?php
        }
    }
}

if (!function_exists('dacdb_missing_club')) {
    function dacdb_missing_club()
    {
        global $pagenow;

        // Store the error message in a variable
        $error_message = __('A valid club, lodge, or entity number is required. ', 'dacdbplus');

        // Define the URL of your specific settings page.
        $settings_url = admin_url('options-general.php?page=mmp-settings');
        // Define the URL for your external customer support page.
        $support_url = 'https://www.dacdbsupport.com';

        // Check if the current page is the settings page
        if ($pagenow == 'options-general.php' && isset($_GET['page']) && $_GET['page'] == 'mmp-settings') {
            ?>
            <div class="updated settings-error error is-dismissible" style="padding: 10px;">
                <h2 style="margin: 0px;">DACdb Plus: <?php echo $error_message; ?></h2>
            </div>
            <?php
        } else {
            ?>
            <div class="updated settings-error error is-dismissible" style="display: flex; justify-content: space-between; align-items: center;">
                <h2 style="margin: 0;"><?php echo '<a href="' . esc_url($settings_url) . '" title="Click to access DACdb Plus plugin settings">DACdb Plus</a>: ' . $error_message . ''; ?></h2>
                <!-- Container for buttons to ensure they stay together -->
                <div>
                    <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary" style="margin: 10px;">
                        <?php _e('Go to Settings', 'dacdbplus'); ?>
                    </a>
                    <a href="<?php echo esc_url($support_url); ?>" class="button button-secondary" style="margin: 10px 0;">
                        <?php _e('Get Support', 'dacdbplus'); ?>
                    </a>
                </div>
            </div>
            <?php
        }
    }
}

if (!function_exists('dacdb_missing_system')) {
    function dacdb_missing_system()
    {
        global $pagenow;

        // Store the error message in a variable
        $error_message = __('System selection is missing or invalid.', 'dacdbplus');

        // Define the URL of your specific settings page.
        $settings_url = admin_url('options-general.php?page=mmp-settings');
        // Define the URL for your external customer support page.
        $support_url = 'https://www.dacdbsupport.com';

        // Check if the current page is the settings page
        if ($pagenow == 'options-general.php' && isset($_GET['page']) && $_GET['page'] == 'mmp-settings') {
            ?>
            <div class="updated settings-error error is-dismissible" style="padding: 10px;">
                <h2 style="margin: 0px;">DACdb Plus: <?php echo $error_message; ?></h2>
            </div>
            <?php
        } else {
            ?>
            <div class="updated settings-error error is-dismissible" style="display: flex; justify-content: space-between; align-items: center;">
                <h2 style="margin: 0;"><?php echo '<a href="' . esc_url($settings_url) . '" title="Click to access DACdb Plus plugin settings">DACdb Plus</a>: ' . $error_message . ''; ?></h2>
                <!-- Container for buttons to ensure they stay together -->
                <div>
                    <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary" style="margin: 10px;">
                        <?php _e('Go to Settings', 'dacdbplus'); ?>
                    </a>
                    <a href="<?php echo esc_url($support_url); ?>" class="button button-secondary" style="margin: 10px 0;">
                        <?php _e('Get Support', 'dacdbplus'); ?>
                    </a>
                </div>
            </div>
            <?php
        }
    }
}

if (!function_exists('dacdb_missing_subscription')) {
    function dacdb_missing_subscription()
    {
        global $pagenow;

        // Store the error message in a variable
        $error_message = __('A valid DACdb plugin subscription is required, please check your settings or contact customer support.', 'dacdbplus');

        // Define the URL of your specific settings page.
        $settings_url = admin_url('options-general.php?page=mmp-settings');
        // Define the URL for your external customer support page.
        $support_url = 'https://www.dacdbsupport.com';

        // Check if the current page is the settings page
        if ($pagenow == 'options-general.php' && isset($_GET['page']) && $_GET['page'] == 'mmp-settings') {
            ?>
            <div class="updated settings-error error is-dismissible" style="padding: 10px;">
                <h2 style="margin: 0px;">DACdb Plus: <?php echo $error_message; ?></h2>
            </div>
            <?php
        } else {
            ?>
            <div class="updated settings-error error is-dismissible" style="display: flex; justify-content: space-between; align-items: center;">
                <h2 style="margin: 0;"><?php echo '<a href="' . esc_url($settings_url) . '" title="Click to access DACdb Plus plugin settings">DACdb Plus</a>: ' . $error_message . ''; ?></h2>
                <!-- Container for buttons to ensure they stay together -->
                <div>
                    <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary" style="margin: 10px;">
                        <?php _e('Go to Settings', 'dacdbplus'); ?>
                    </a>
                    <a href="<?php echo esc_url($support_url); ?>" class="button button-secondary" style="margin: 10px 0;">
                        <?php _e('Get Support', 'dacdbplus'); ?>
                    </a>
                </div>
            </div>
            <?php
        }
    }
}

if (!class_exists('InvalidShortcodeException')) {
    class InvalidShortcodeException extends Exception {}
}
//!SECTION - Error Handling

//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;
}

// Modified success notice with nonce verification
add_action('admin_notices', function() {
    if (
        isset($_GET['mmpdb_renamed']) 
        && $_GET['mmpdb_renamed'] === '1'
        && isset($_GET['_wpnonce'])
        && wp_verify_nonce($_GET['_wpnonce'], 'mmpdb_directory_renamed')
    ) {
        $message = wp_kses(
            '<div class="updated"><p>' .
            'DACdb Plus plugin directory has been updated successfully. Please reactivate the plugin.' .
            '</p></div>',
            array(
                'div' => array('class' => array()),
                'p' => array()
            )
        );
        echo $message;
    }
});

//!SECTION - Utility Functions