<?php

namespace Macymed\MacymedLinkTracker\Utils;

use DOMDocument;

if (! defined('ABSPATH')) {
    exit; // Sécurité
}

class Tracking
{
    public static function init()
    {
        self::init_filters();
        $option = intval(get_option('macymed_tracker_exclusion_internal_pages', '1'));
        if ($option !== 1) {
            add_action('template_redirect', [static::class, 'track_page_visit_server']);
        }
    }

    public static function getTrackingPersonalData()
    {
        // Liste de base fournie par le plugin gratuit
        $list = [
            'REMOTE_ADDR' => 'IP',
            'HTTP_USER_AGENT' => 'User Agent',

        ];

        // Permet à d'autres plugins (comme le plugin Pro) de modifier ou étendre la liste
        return apply_filters('macymed_link_tracker_list_personal_data', $list);
    }

    public static function getTrackingType()
    {
        // Liste de base fournie par le plugin gratuit
        $list = [
            'internal' => 'Interne',
            'external' => 'Externe',
            'inbound' => 'Inbound',
        ];

        // Permet à d'autres plugins (comme le plugin Pro) de modifier ou étendre la liste
        return apply_filters('macymed_link_tracker_list_type_tracking', $list);
    }
    public static function getTrackingOptions()
    {
        // Liste de base fournie par le plugin gratuit
        $list = [
            'macymed_tracker_tracking_list_to_track',

        ];

        // Permet à d'autres plugins (comme le plugin Pro) de modifier ou étendre la liste
        return apply_filters('macymed_link_tracker_list_options', $list);
    }
    public static function track_page_visit_server()
    {
        // Ne pas enregistrer les visites des administrateurs
        if (current_user_can('manage_options')) {
            return;
        }

        global $wpdb;

        $url                 = esc_url_raw(home_url(TrackerHelper::get_current_uri()));
        $exclusionsUserAgent = get_option('macymed_tracker_exclusion_user_agents', []);
        if (! is_array($exclusionsUserAgent)) {
            $exclusionsUserAgent = explode(PHP_EOL, $exclusionsUserAgent);
        }
        $isExcludedUserAgent = self::is_user_agent_excluded($exclusionsUserAgent);
        if (! $isExcludedUserAgent) {
            self::recordClick($url);
        }
    }

    public static function init_filters()
    {
        add_filter('the_content', [static::class, 'replaceLinkInContent'], 10);
        add_filter('widget_text', [static::class, 'replaceLinkInContent'], 10);
        add_filter('widget_text_content', [static::class, 'replaceLinkInContent'], 10);
    }
    public static function MacymedExludeMyUrl($url)
    {
        $domain        = 'macymed.fr';
        $urlsToExclude = [
            $domain,
            '#',

        ];
        if (! $url || (($url !== null) && ! trim($url))) {
            return true;
        }
        foreach ($urlsToExclude as $urlToExclude) {
            if (strpos($url, $urlToExclude) !== false) {
                return true;
            }
        }
        if (strpos($url, 'http') === false) {
            return true;
        }
        if (strpos($url, '/') === 0) {
            return true;
        }
        return false;
    }
    public static function is_param_excluded($url, $exclusionsParamsGet)
    {
        // if (strpos($url, '/') === 0) {
        // return true;
        // }
        // Extraire la partie query de l'URL
        $query = wp_parse_url($url, PHP_URL_QUERY);

        // Convertir la chaîne de requête en tableau associatif
        $params = [];
        if ($query) {
            parse_str($query, $params);
        }

        // Vérifier chaque paramètre avec les exclusions
        foreach ($params as $param_name => $param_value) {
            $param_name = trim(strtolower($param_name));
            if (! $param_name) {
                continue;
            }
            $param_value = trim(strtolower($param_value));
            foreach ($exclusionsParamsGet as $pattern) {
                $pattern = trim(strtolower($pattern));
                if (! $pattern) {
                    continue;
                }
                // Si le motif commence par ^, il doit correspondre au début de la clé
                if (strpos($pattern, '^') === 0) {
                    $regex = '/^' . preg_quote(ltrim($pattern, '^'), '/') . '/';
                    if (preg_match($regex, $param_name)) {
                        return true; // Une condition est remplie
                    }
                }

                // Si le motif se termine par $, il doit correspondre exactement à la clé
                if (str_ends_with($pattern, '$')) {
                    $regex = '/' . preg_quote(rtrim($pattern, '$'), '/') . '$/';
                    if (preg_match($regex, $param_name)) {
                        return true; // Une condition est remplie
                    }
                }

                // Si le motif contient un `=`, il doit correspondre au paramètre complet (clé=valeur)
                if (strpos($pattern, '=') !== false) {
                    list($key, $value) = explode('=', $pattern, 2);
                    if ($param_name === $key && $param_value === $value) {
                        return true; // Une condition est remplie
                    }
                }

                // Sinon, recherche simple dans le nom du paramètre
                if (strpos($param_name, $pattern) !== false) {
                    return true; // Une condition est remplie
                }
            }
        }

        return false; // Aucune condition n'est remplie
    }
    public static function is_url_excluded($url, $exclusions)
    {
        // Découper l'URL en composants
        $parsed_url = wp_parse_url($url);

        // Extraire des parties de l'URL

        $path = $parsed_url['path'] ?? '';

        foreach ($exclusions as $pattern) {
            // Construire la regex à partir du motif
            $regex = '/' . str_replace('/', '\/', $pattern) . '/';

            if (preg_match($regex, $path)) {
                return true; // Exclu si une règle correspond
            }
        }
        return false; // Aucune règle ne correspond
    }
    public static function is_domain_excluded($url, $exclusions)
    {
        // Découper l'URL en composants
        $parsed_url = wp_parse_url($url);

        // Extraire des parties de l'URL
        $domain = trim(strtolower($parsed_url['host'] ?? ''));

        foreach ($exclusions as $pattern) {
            $pattern = trim(strtolower($pattern));

            if (strpos($domain, $pattern) !== false) {

                return true;
            }
        }
        return false; // Aucune règle ne correspond
    }
    public static function is_protocol_excluded($url, $exclusions)
    {
        // Découper l'URL en composants
        $parsed_url = wp_parse_url($url);

        // Extraire des parties de l'URL

        $protocol = trim(strtolower($parsed_url['scheme'] ?? ''));

        foreach ($exclusions as $pattern) {

            $pattern = trim(strtolower($pattern));

            if (strpos($protocol, $pattern) !== false) {

                return true;
            }
        }
        return false; // Aucune règle ne correspond
    }
    public static function is_user_agent_excluded($exclusions)
    {
        // Vérifier si le User-Agent est défini
        if (empty($_SERVER['HTTP_USER_AGENT'])) {
            return false; // Pas de User-Agent, on considère qu'il n'est pas exclu
        }

        $user_agent = TrackerHelper::get_user_agent();

        foreach ($exclusions as $exclusion) {
            // Vérifier si le User-Agent contient une des valeurs d'exclusion
            $exclusion = trim(strtolower($exclusion));
            if (stripos($user_agent, $exclusion) !== false) {
                return true; // Exclu
            }
        }

        return false; // Non exclu
    }
    public static function isExcludedIpAddress(array $exclusions, $ipParam = null): bool
    {
        $ip = $ipParam ? $ipParam : TrackerHelper::get_ip_address();
        foreach ($exclusions as $rule) {
            // Si c'est une plage délimitée par `...`
            if (strpos($rule, '...') !== false) {
                [$start, $end] = explode('...', $rule);

                // Remplace `X` par `0-255` pour gérer les wildcards
                $start = str_replace('X', '0', $start);
                $end   = str_replace('X', '255', $end);

                if (self::ipInRange($ip, $start, $end)) {
                    return true;
                }
            }
            // Si c'est une IP exacte ou avec des `X`
            else {
                // Remplace `X` par un motif regex
                $pattern = str_replace('.', '\.', $rule);
                $pattern = str_replace('X', '\d{1,3}', $pattern);
                $pattern = '/^' . $pattern . '$/';

                if (preg_match($pattern, $ip)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static function ipInRange(string $ip, string $start, string $end): bool
    {
        $ipLong    = ip2long($ip);
        $startLong = ip2long($start);
        $endLong   = ip2long($end);

        return $ipLong >= $startLong && $ipLong <= $endLong;
    }


    public static function replaceLinkInContent($content)
    {

        if (! $content) {

            return $content;
        }

        $macymed_tracker_tracking_use_external_redirect_page = intval(get_option('macymed_tracker_tracking_use_external_redirect_page', '0'));
        $useWebBeacon = intval(get_option('macymed_tracker_tracking_use_external_javascript_page', '1'));
       
        if (($macymed_tracker_tracking_use_external_redirect_page !== 1) && ($useWebBeacon !== 1)) { 
            return $content;
        }

        $exclusionsUserAgent = get_option('macymed_tracker_exclusion_user_agents', []);
        if (! is_array($exclusionsUserAgent)) {
            $exclusionsUserAgent = explode(PHP_EOL, $exclusionsUserAgent);
        }
        $exclusionsParamsGet = get_option('macymed_tracker_exclusion_get', []);
        if (! is_array($exclusionsParamsGet)) {
            $exclusionsParamsGet = explode(PHP_EOL, $exclusionsParamsGet);
        }
        $exclusionsUrl = []; // get_option('macymed_tracker_exclusion_url', []);
        if (! is_array($exclusionsUrl)) {
            $exclusionsUrl = explode(PHP_EOL, $exclusionsUrl);
        }
        $exclusionsDomains = get_option('macymed_tracker_exclusion_domains', []);
        if (! is_array($exclusionsDomains)) {
            $exclusionsDomains = explode(PHP_EOL, $exclusionsDomains);
        }
        $exclusionsIps = get_option('macymed_tracker_exclusion_ips', []);
        if (! is_array($exclusionsIps)) {
            $exclusionsIps = explode(PHP_EOL, $exclusionsIps);
        }

        $exclusionsProtocols = get_option('macymed_tracker_exclusion_protocols', []);
        if (! is_array($exclusionsProtocols)) {
            $exclusionsProtocols = explode(PHP_EOL, $exclusionsProtocols);
        }

        $macymed_tracker_exclusion_domains_relative_path = intval(get_option('macymed_tracker_exclusion_domains_relative_path', 1));


        

        $nonce = wp_create_nonce('redirect_external_action');
        $nonce_record = wp_create_nonce('link_tracker_record_action');

        $modifiedHtml = preg_replace_callback(
            '/<a[^>]*href=["\']([^"\']+)["\'][^>]*>/i',
            function ($matches) use ($useWebBeacon,$nonce, $nonce_record, $exclusionsIps, $macymed_tracker_exclusion_domains_relative_path, $exclusionsUserAgent, $exclusionsParamsGet, $exclusionsUrl, $exclusionsDomains, $exclusionsProtocols) {
                $href = $matches[1];
                if (is_string($href) && trim($href)) {
                    $isExcludedDomain = self::is_domain_excluded($href, $exclusionsDomains);
                    // $isExcludedUrl = self::is_url_excluded($href, $exclusionsUrl);
                    $isProtocolExcluded  = self::is_protocol_excluded($href, $exclusionsProtocols);
                    $isExcludedUserAgent = self::is_user_agent_excluded($exclusionsUserAgent);
                    $isExcludedParamsGet = self::is_param_excluded($href, $exclusionsParamsGet);
                    $isExcludedIp        = self::isExcludedIpAddress($exclusionsIps);

                    $isExcludedRelativePath = $macymed_tracker_exclusion_domains_relative_path === 1 ? strpos($href, '/') === 0 : false;
                    $isExcluded             = $isExcludedDomain
                        || $isExcludedUserAgent
                        || $isExcludedParamsGet
                        || $isProtocolExcluded
                        || $isExcludedRelativePath
                        || $isExcludedIp;
                    if (strpos($href, 'redirect_external.php') !== false) {
                        $isExcluded = true;
                    } elseif (strpos($href, 'redirect_external\.php') !== false) {
                        $isExcluded = true;
                    }
                    else if (strpos($href, 'link_tracker_record.php') !== false) {
                        $isExcluded = true;
                    } elseif (strpos($href, 'link_tracker_record\.php') !== false) {
                        $isExcluded = true;
                    }
                    
                    // debug de mes variables d'exclusions
                    // print_r([
                    //     'isExcludedDomain' => $isExcludedDomain,
                    //     'exclusionsDomains' => $exclusionsDomains,
                    //     'isExcludedUserAgent' => $isExcludedUserAgent,
                    //     'exclusionsUserAgent' => $exclusionsUserAgent,
                    //     'isExcludedParamsGet' => $isExcludedParamsGet,
                    //     // 'isExcludedUrl' => $isExcludedUrl,
                    //     'isExcludedDomain' => $isExcludedDomain,
                    //     'isExcludedIp' => $isExcludedIp,
                    //     'exclusionsIps' => $exclusionsIps,
                    //     'isExcludedProtocol' => $isProtocolExcluded,
                    //     'exclusionsProtocols' => $exclusionsProtocols,
                    //     'isExcludedRelativePath' => $isExcludedRelativePath,
                    //     'isExcluded' => $isExcluded,
                    // ]);
                    // die;
                    if ((strpos($href, '#') === 0)) {
                        $isExcluded = true;
                    }
                    if (! $isExcluded) {
                        $encoded_url = urlencode($href);
                        
                        // if($useWebBeacon == 1){
                        //     $originalTag = $matches[0];
                        //     $webBeaconUrl        = 'https://' . TrackerHelper::get_http_host() . "/link_tracker_record.php?macymed_tracker_record=1&redirect_type=php&mtl_nonce=$nonce_record&url=$encoded_url";
                        //     // Injecter une balise <img> invisible dans le lien
                        //     $webBeaconImg = '<img src="' . htmlspecialchars($webBeaconUrl) . '" style="display:none;" alt="">';

                        //     // Ajouter le web beacon dans le lien
                            
                        //      // Ajouter le web beacon dans le lien
                        //     $modifiedTag = str_replace('>', '>' . $webBeaconImg, $originalTag);

                        //     return $modifiedTag;
                        // }
                        if ($useWebBeacon === 1) {
                            $originalTag = $matches[0];
                            $webBeaconUrl = 'https://' . TrackerHelper::get_http_host() . "/link_tracker_record.php?macymed_tracker_record=1&redirect_type=php&mtl_nonce=$nonce_record&url=$encoded_url";
                        
                            // Ajouter un attribut data-track-url au lien pour JavaScript
                            $modifiedTag = preg_replace(
                                '/<a /',
                                // '<a data-link-tracker-track-url="' . htmlspecialchars($webBeaconUrl) . '" ',
                                '<a data-link-tracker-track-url="' . 1 . '" ',
                                $originalTag,
                                1
                            );
                        
                            return $modifiedTag;
                        }
                       
                       
                        $href        = 'https://' . TrackerHelper::get_http_host() . "/redirect_external.php?macymed_tracker=1&redirect_type=php&mtl_nonce=$nonce&url=$encoded_url";
                    }
                }
                // Remettre le href modifié
                return str_replace($matches[1], $href, $matches[0]);
            },
            $content
        );
        return $modifiedHtml;
    }
    public static function deleteAllRecords()
    {
        global $wpdb;
        $table_main   = $wpdb->prefix . MACYMED_LINK_TRACKER_TABLE_NAME;
        $table_clicks = $wpdb->prefix . MACYMED_LINK_TRACKER_CLICKS_TABLE_NAME;
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM " . $table_clicks);
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM " . $table_main);
        return;
    }
    public static function deleteAllRecordsFromUrl($url)
    {
        global $wpdb;
        $table_main   = $wpdb->prefix . MACYMED_LINK_TRACKER_TABLE_NAME;
        $table_clicks = $wpdb->prefix . MACYMED_LINK_TRACKER_CLICKS_TABLE_NAME;
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $existing     = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . $table_main . " WHERE url = %s", $url));
        if ($existing) {
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->query($wpdb->prepare("DELETE FROM " . $table_clicks . " WHERE url_id = %d", $existing->id));
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->query($wpdb->prepare("DELETE FROM " . $table_main . " WHERE url = %s", $url));
        }
    }
    public static function deleteAllRecordsFromKeyword($keyword)
    {
        global $wpdb;
        $table_main   = $wpdb->prefix . MACYMED_LINK_TRACKER_TABLE_NAME;
        $table_clicks = $wpdb->prefix . MACYMED_LINK_TRACKER_CLICKS_TABLE_NAME;
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $existings = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $table_main . " WHERE url LIKE %s", '%' . $wpdb->esc_like($keyword) . '%'));

        if ($existings && count($existings) > 0) {
            foreach ($existings as $existing) {
                // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->query($wpdb->prepare("DELETE FROM " . $table_clicks . " WHERE url_id = %d", $existing->id));
                // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->query($wpdb->prepare("DELETE FROM " . $table_main . " WHERE url = %s", $existing->url));
            }
        }
    }
    public static function recordClick($url_param = null)
    {

        // Récupérer le nonce depuis l'URL
        $nonce = isset($_GET['mtl_nonce']) ? sanitize_text_field(wp_unslash($_GET['mtl_nonce'])) : '';
        
        // Vérifier le nonce
        if ($nonce && !wp_verify_nonce($nonce, 'macymed-link-tracker-list') && !wp_verify_nonce($nonce, 'redirect_external_action') &&
        !wp_verify_nonce( $nonce, 'link_tracker_record_action' )) {
            
            wp_die(esc_html__('Invalid nonce or expired link.', 'macymed-link-tracker'));
        }


        if ($url_param || isset($_GET['url'])) {
            $url = $url_param ? $url_param : sanitize_text_field(wp_unslash($_GET['url']));
            $url = sanitize_url($url);
            if (strpos($url, 'redirect_external.php') !== false) {
                return;
            } elseif (strpos($url, 'redirect_external\.php') !== false) {
                return;
            }
            else if (strpos($url, 'link_tracker_record.php') !== false) {
                return;
            } elseif (strpos($url, 'link_tracker_record\.php') !== false) {
                return;
            }
            
            global $wpdb;
            $table_main   = $wpdb->prefix . MACYMED_LINK_TRACKER_TABLE_NAME;
            $table_clicks = $wpdb->prefix . MACYMED_LINK_TRACKER_CLICKS_TABLE_NAME;
            $table_page_views = $wpdb->prefix . MACYMED_LINK_TRACKER_PAGE_VIEWS_TABLE_NAME;

            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $existing = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . $table_main . " WHERE url = %s", $url));
            if (! $existing) {

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery
                $wpdb->insert(
                    $table_main,
                    [
                        'url' => $url,
                    ]
                );
            }

            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $existing    = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . $table_main . " WHERE url = %s", $url));
            $actual_link = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://" . TrackerHelper::get_http_host() . TrackerHelper::get_current_uri();
            $referer     = isset($_SERVER['HTTP_REFERER']) ? TrackerHelper::get_referrer() : '/';
            $url         = sanitize_url($referer);
            $data        = [
                'referer' => $referer,

            ];
            $listToTrack = get_option('macymed_tracker_tracking_list_to_track', []);

            if (!is_array($listToTrack)) {
                $listToTrack = [];
            }


            $listPersonalData = get_option('macymed_tracker_tracking_list_personal_data_to_track', []);
            $registerIp = false;
            $registerUserAgent = false;
            if (in_array('REMOTE_ADDR', $listPersonalData)) {
                $registerIp = true;
            }
            if (in_array('HTTP_USER_AGENT', $listPersonalData)) {
                $registerUserAgent = true;
            }

            
            $data = TrackerHelper::extractPersonalData();
            if ($registerIp) {
                $data['ip'] = TrackerHelper::get_ip_address();
            }

            if ($registerUserAgent) {
                $data['user_agent'] = TrackerHelper::get_user_agent();
            }
            $data['referer'] = TrackerHelper::get_referrer();
            $type_url = $url_param ? 'internal' : 'external';
            if (isset($data['referer'])) {
                if (($data['referer'] !== '/') && (strpos($data['referer'], Utils::get_current_domain()) === false)) {
                    $type_url = 'inbound';
                }
                if (strpos($data['referer'], 'redirect_external.php') !== false) {
                    return;
                } elseif (strpos($data['referer'], 'redirect_external\.php') !== false) {
                    return;
                }
                else if (strpos($data['referer'], 'link_tracker_record.php') !== false) {
                    return;
                } elseif (strpos($data['referer'], 'link_tracker_record\.php') !== false) {
                    return;
                }
                
            }

            if ($type_url === 'internal') {
                $macymed_tracker_tracking_refresh             = intval(get_option('macymed_tracker_tracking_refresh', 0));
                $macymed_tracker_tracking_record_excluded_ips = intval(get_option('macymed_tracker_tracking_record_excluded_ips', 0));

                $register4040 = get_option('macymed_tracker_tracking_record_404', '1') === '1';
                if (! $register4040) {
                    if (is_404()) {
                        return;
                    }
                } elseif (is_404()) {
                    $type_url = '404';
                }
                if ($macymed_tracker_tracking_refresh === 1) {
                    if ($referer === $url) {
                        return;
                    }
                }
                $exclusionsIps = get_option('macymed_tracker_exclusion_ips', []);
                if (! is_array($exclusionsIps)) {
                    $exclusionsIps = explode(PHP_EOL, $exclusionsIps);
                }
                $isExcludedIp = self::isExcludedIpAddress($exclusionsIps, TrackerHelper::get_ip_address());
                if ($macymed_tracker_tracking_record_excluded_ips === 1) {

                    if ($isExcludedIp) {
                        $type_url = 'excluded_ip';
                    }
                } elseif ($isExcludedIp) {
                    return;
                }
                if ($referer === '/') {
                    $type_url = 'direct_access';
                }
            }
            $type_click = isset($_GET['redirect_type']) ? sanitize_text_field(wp_unslash($_GET['redirect_type'])) : 'php';
            if (! in_array($type_click, ['php', 'js'])) {
                $type_click = 'php';
            }

            if (!in_array($type_url, $listToTrack)) {
                return;
            };
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            $wpdb->insert(
                $table_clicks,
                [
                    'url_id'     => $existing->id,
                    'last_click' => current_time('mysql'),
                    'type_click' => $type_click,
                    'full_url'   => $actual_link,
                    'data'       => wp_json_encode($data),
                    'type_url'   => $type_url,
                ]
            );
            if (!empty($referer) && $type_url === 'internal') {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery
                $wpdb->insert(
                    $table_page_views,
                    [
                        'page_url'   => $actual_link,
                        'viewed_at'  => current_time('mysql'),
                        'user_id'    => get_current_user_id() ?: null,
                        'session_id' => session_id(),
                        'referrer'   => $referer,
                        'user_agent' => TrackerHelper::get_user_agent(),
                    ]
                );
            }
        }
    }
}
