<?php

/**
 * Checks if a Matomo tracking code has been set in the WordPress options.
 *
 * @return bool True if the tracking code exists, false otherwise.
 */
function sc_matomo_has_tracking_code()
{
    if (get_option('sc_matomo_tracking_code') !== false) {
        return true;
    } else {
        return false;
    }
}

/**
 * Saves or updates the Matomo tracking code in the WordPress options.
 *
 * @param string $trackingCode The tracking code to store.
 * @return void
 */
function sc_matomo_set_tracking_code(string $trackingCode)
{
    update_option('sc_matomo_tracking_code', $trackingCode);
}

/**
 * Retrieves the Matomo tracking code from the WordPress options.
 *
 * @return string The tracking code if set, or an empty string if not.
 */
function sc_matomo_get_tracking_code()
{
    $trackingCode = get_option('sc_matomo_tracking_code');
    if ($trackingCode === false) {
        return '';
    } else {
        return $trackingCode;
    }
}

function sc_matomo_can_render_tracking_code()
{
    $code = sc_matomo_get_tracking_code();

    if ($code === '') {
        return false;
    }

    // Quick safety check
    $blacklist = ['<iframe', '<object', '<embed', '<link', '<meta', 'onerror=', 'onload='];
    foreach ($blacklist as $tag) {
        if (stripos($code, $tag) !== false) {
            return false;
        }
    }

    // Must contain basic Matomo function calls
    $required = ['_paq.push', 'trackPageView', 'enableLinkTracking', 'setTrackerUrl', 'setSiteId'];
    foreach ($required as $item) {
        if (stripos($code, $item) === false) {
            return false;
        }
    }


    // Check that the script URL is only to your known analytics domain
    if (!str_contains($code, 'analytics.121domains.co.uk')) {
        return false;
    }

    return true;
}

function sc_matomo_tracking_code_empty()
{
    $code = sc_matomo_get_tracking_code();
    if ($code === '') {
        return true;
    }
    return false;
}

function sc_render_matomo_tracking_code()
{
    if (sc_matomo_can_render_tracking_code()) {
        $trackingCode = sc_matomo_get_tracking_code();
        print "<!-- START REG121 Tracking Code -->\n";
        if ($trackingCode !== '') {
            print $trackingCode;
        } else {
            print "<!-- No tracking code defined. -->\n";
        }
        print "<!-- END REG121 Tracking Code -->\n";
    } else {
        print "<!-- REG121 Maotmo Tracking Code Blocked For Security Reasons -->\n";
    }
}
