<?php

/**
 * LinkCentral Click Tracker
 *
 * Handles click recording, analytics integration, and click filtering.
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Exit if accessed directly
class LinkCentral_Tracker {
    private $visitor_manager;

    private $geolocation;

    public function __construct( $visitor_manager, $geolocation = null ) {
        $this->visitor_manager = $visitor_manager;
        $this->geolocation = $geolocation;
    }

    /**
     * Send click data to Google Analytics.
     */
    public function send_to_google_analytics( $link_id, $slug, $destination_url ) {
        // Check if Google Analytics integration is enabled
        if ( !get_option( 'linkcentral_enable_ga' ) ) {
            return;
            // Don't send if GA integration is not enabled
        }
        $measurement_id = get_option( 'linkcentral_ga_measurement_id' );
        $api_secret = get_option( 'linkcentral_ga_api_secret' );
        if ( empty( $measurement_id ) || empty( $api_secret ) ) {
            return;
            // Don't send if Measurement ID or API secret is not set
        }
        $client_id = $this->get_client_id();
        $url = "https://www.google-analytics.com/mp/collect?measurement_id={$measurement_id}&api_secret={$api_secret}";
        $data = [
            'client_id'        => $client_id,
            'timestamp_micros' => round( microtime( true ) * 1000000 ),
            'events'           => [[
                'name'   => 'outbound_link_click',
                'params' => [
                    'link_url'        => home_url( $this->get_url_prefix() . '/' . $slug ),
                    'link_title'      => get_the_title( $link_id ),
                    'link_id'         => $link_id,
                    'destination_url' => $destination_url,
                    'plugin'          => 'LinkCentral',
                ],
            ]],
        ];
        $args = [
            'body'     => wp_json_encode( $data ),
            'headers'  => [
                'Content-Type' => 'application/json',
            ],
            'blocking' => false,
            'timeout'  => 1,
        ];
        wp_remote_post( $url, $args );
    }

    /**
     * Get or generate a client ID for Google Analytics.
     */
    private function get_client_id() {
        if ( !isset( $_COOKIE['_ga'] ) ) {
            $client_id = wp_generate_uuid4();
            setcookie(
                '_ga',
                $client_id,
                time() + 2 * 365 * 24 * 60 * 60,
                '/'
            );
        } else {
            $client_id = sanitize_text_field( wp_unslash( $_COOKIE['_ga'] ) );
        }
        return $client_id;
    }

    /**
     * Get URL prefix from options
     */
    private function get_url_prefix() {
        return get_option( 'linkcentral_url_prefix', 'go' );
    }

    /**
     * Record a click for a link.
     */
    public function record_click( $link_id, $slug, $destination_url ) {
        // Check if reporting is disabled
        if ( get_option( 'linkcentral_disable_reporting', false ) ) {
            return;
        }
        if ( $this->should_record_click( $link_id ) ) {
            // Send data to Google Analytics
            $this->send_to_google_analytics( $link_id, $slug, $destination_url );
            global $wpdb;
            $table_name = $wpdb->prefix . 'linkcentral_stats';
            $data = array(
                'link_id'         => $link_id,
                'click_date'      => current_time( 'mysql' ),
                'referring_url'   => ( wp_get_referer() ? wp_get_referer() : '' ),
                'destination_url' => $destination_url,
            );
            // Only add user_agent if tracking is enabled and the header is set
            if ( get_option( 'linkcentral_track_user_agent', true ) ) {
                $user_agent = $this->get_user_agent();
                if ( !empty( $user_agent ) ) {
                    $data['user_agent'] = $user_agent;
                }
            }
            // Check if unique visitor tracking is enabled
            if ( get_option( 'linkcentral_track_unique_visitors', true ) ) {
                $visitor_id = $this->visitor_manager->get_or_set_visitor_id();
                $data['visitor_id'] = $visitor_id;
                // Track per-link unique clicks using cookies
                $first_click = $this->visitor_manager->is_first_click_for_link( $link_id );
                $data['first_click'] = ( $first_click ? 1 : 0 );
            }
            $wpdb->insert( $table_name, $data );
        }
    }

    /**
     * Get user agent (delegates to visitor manager)
     */
    private function get_user_agent() {
        return $this->visitor_manager->get_user_agent();
    }

    /**
     * Determine if a click should be recorded.
     */
    public function should_record_click( $link_id ) {
        $excluded_ips = get_option( 'linkcentral_excluded_ips', '' );
        $excluded_ip_list = array_map( 'trim', explode( "\n", $excluded_ips ) );
        $current_ip = $this->visitor_manager->get_ip_address();
        if ( in_array( $current_ip, $excluded_ip_list ) ) {
            return false;
        }
        $excluded_roles = get_option( 'linkcentral_excluded_roles', array() );
        $current_user = wp_get_current_user();
        if ( array_intersect( $current_user->roles, $excluded_roles ) ) {
            return false;
        }
        // Check if bot exclusion is enabled and if the current request is from a bot
        if ( get_option( 'linkcentral_exclude_bots', false ) && $this->is_bot() ) {
            return false;
        }
        // Check for duplicate clicks
        if ( $this->visitor_manager->prevent_duplicate_click( $link_id, 'check' ) ) {
            return false;
        }
        // Set the duplicate prevention flag
        $this->visitor_manager->prevent_duplicate_click( $link_id, 'set' );
        return true;
    }

    /**
     * Determine if the current request is from a bot.
     */
    private function is_bot() {
        $user_agent = strtolower( $this->get_user_agent() );
        if ( empty( $user_agent ) ) {
            return false;
        }
        $bot_keywords = array(
            'bot',
            'crawler',
            'spider',
            'slurp',
            'googlebot',
            'bingbot',
            'yandexbot'
        );
        foreach ( $bot_keywords as $keyword ) {
            if ( strpos( $user_agent, $keyword ) !== false ) {
                return true;
            }
        }
        return false;
    }

}
