<?php 

defined('ABSPATH') or die("You can't access this file directly.");

function qcld_seohelp_ai_tracker_enqueue_scripts($hook) {
    // Only load on your specific plugin page
    //var_dump( $hook );
    //wp_die();
    if ($hook !== 'seo-help_page_ai-bot-trackers') {
        return;
    }

    // Load Chart.js from a full, reliable URL
    wp_enqueue_script(
        'seo-help-chart-js', 
        qcld_seohelp_assets_url . '/js/chart.js', 
        array(), 
        '4.4.1', 
        true // Load in footer for better performance
    );
}
add_action('admin_enqueue_scripts', 'qcld_seohelp_ai_tracker_enqueue_scripts');

// 1. Create/Update Database Table
register_activation_hook(__FILE__, 'qcld_seohelp_ai_tracker_create_db');
function qcld_seohelp_ai_tracker_create_db() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'qcld_ai_bot_tracker';
    $charset_collate = $wpdb->get_charset_collate();
	$collate = '';

	if ( $wpdb->has_cap( 'collation' ) ) {

		if ( ! empty( $wpdb->charset ) ) {

			$collate .= "DEFAULT CHARACTER SET $wpdb->charset";
		}
		if ( ! empty( $wpdb->collate ) ) {

			$collate .= " COLLATE $wpdb->collate";

		}
	}

	require_once ABSPATH . 'wp-admin/includes/upgrade.php';

	$sql = "
	  CREATE TABLE IF NOT EXISTS {$table_name} (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        bot_name varchar(100) NOT NULL,
        bot_source varchar(100) NOT NULL,
		ip_address varchar(45) NOT NULL,
		location varchar(100) DEFAULT 'Unknown' NOT NULL,
        visit_count int DEFAULT 1 NOT NULL,
        request_url text NOT NULL,
        last_visit datetime DEFAULT '1000-01-01 00:00:00' NOT NULL,
        PRIMARY KEY  (id)
	) $collate AUTO_INCREMENT=1";

	dbDelta($sql);
	
}

// 2. Bot Detection & Logging Logic
add_action('template_redirect', 'qcld_seohelp_ai_tracker_log_bot_visit');
function qcld_seohelp_ai_tracker_log_bot_visit() {
	if ( is_admin() ) return;
	if ( empty($_SERVER['HTTP_USER_AGENT']) ) return;
		
    //$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
	$user_agent 	= isset( $_SERVER['HTTP_USER_AGENT'] ) ? strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) ) : '';
    if (empty($user_agent)) return;
	
	$ai_bots = [
        'gptbot'           => 'GPTBot',
        'chatgpt-user'     => 'ChatGPT-User',
        'chatgpt-browser'  => 'ChatGPT-Browser',
        'oai-searchbot'    => 'OAI-SearchBot',
        'claudebot'        => 'ClaudeBot',
        'claude-web'       => 'Claude-Web',
        'claude-searchbot' => 'Claude-SearchBot',
        'claude-user'      => 'Claude-User',
        'anthropic-ai'     => 'Anthropic-AI',
        'perplexitybot'    => 'PerplexityBot',
        'perplexity-user'  => 'Perplexity-User',
        'ccbot'            => 'CCBot',
        'omgilibot'        => 'Omgilibot',
        'omgili'           => 'Omgili',
        'mistralai-user'   => 'MistralAI-User',
        'mistral le chat'  => 'Mistral-Le-Chat',
        'youbot'           => 'YouBot',
        'timpibot'         => 'Timpibot',
        'diffbot'          => 'Diffbot',
        'ai2bot'           => 'AI2Bot',
        'cohere-ai'        => 'Cohere-AI',
        'cohere-command'   => 'Cohere-Command',
        'google-extended'  => 'Google-Extended',
        'google-cloudvertexbot' => 'Google-CloudVertexBot',
        'googleagent-mariner' => 'GoogleAgent-Mariner',
        'gemini-deep-research' => 'Gemini-Deep-Research',
        'gemini-ai'        => 'Gemini-AI',
        'bard-ai'          => 'Bard-AI',
        'apis-google'      => 'APIs-Google',
        'novaact'          => 'NovaAct',
        'devin'            => 'Devin',
        'linerbot'         => 'LinerBot',
        'qualifiedbot'     => 'QualifiedBot',
        'applebot-extended'=> 'Applebot-Extended',
        'meta-externalagent' => 'Meta-ExternalAgent',
        'meta-externalfetcher' => 'Meta-ExternalFetcher',
        'facebookexternalhit' => 'FacebookExternalHit',
        'facebookbot'      => 'FacebookBot',
        'linkedinbot'      => 'LinkedInBot',
        'bytespider'       => 'Bytespider',
        'amazonbot'        => 'Amazonbot',
        'proratainc'       => 'ProRataInc',
        'xai-bot'          => 'xAI-Bot',
        'deepseekbot'      => 'DeepSeekBot',
        'huggingface-bot'  => 'HuggingFace-Bot',
        'character-ai'     => 'Character-AI',
        'groq-bot'         => 'Groq-Bot',
        'together-bot'     => 'Together-Bot',
        'replicate-bot'    => 'Replicate-Bot',
        'duckassistbot'    => 'DuckAssistBot',
        'andibot'          => 'Andibot',
        'pangubot'         => 'PanguBot',
        'petalbot'         => 'PetalBot',
        'firecrawlagent'   => 'FirecrawlAgent',
        'runpod-bot'       => 'RunPod-Bot',
        'brightbot'        => 'BrightBot',
        'webzio-extended'  => 'Webzio-Extended',
        'imagesiftbot'     => 'ImagesiftBot',
        'bigsur.ai'        => 'BigSur-AI',
	];

    foreach ($ai_bots as $key => $info) {
        if (stripos($user_agent, $key) !== false) {
            global $wpdb;
            $table_name = $wpdb->prefix . 'qcld_ai_bot_tracker';
            $url = home_url(add_query_arg([], $GLOBALS['wp']->request));
			
			
			$bot_name 		= $key;
			$bot_source 	= $info;

            // Check if this bot+url combo exists
            $existing = $wpdb->get_row($wpdb->prepare(
                "SELECT id, visit_count FROM $table_name WHERE bot_name = %s AND request_url = %s",
                $bot_name, $url
            ));

            // Inside qcld_seohelp_ai_tracker_log_visit():
            $ip = $_SERVER['REMOTE_ADDR']; // The most reliable header for the visitor's IP
            $location = qcld_seohelp_ai_tracker_get_geo($ip);

            if ($existing) {
                $wpdb->update($table_name, 
                    ['visit_count' => $existing->visit_count + 1, 'last_visit' => current_time('mysql')],
                    ['id' => $existing->id]
                );
            } else {
                $wpdb->insert($table_name, [
                    'bot_name'      => $bot_name,
                    'bot_source'    => $bot_source,
                    'ip_address'    => $ip,
                    'location'      => $location,
                    'visit_count'   => 1,
                    'request_url'   => $url,
                    'last_visit'    => current_time('mysql')
                ]);
            }
            break; 
        }
    }
}

function qcld_seohelp_ai_tracker_get_geo($ip) {
    // Skip local IPs
    if ($ip === '127.0.0.1' || $ip === '::1') return 'Localhost';

    $url = "http://ip-api.com/json/{$ip}?fields=status,message,country,city";
    $response = wp_remote_get($url, ['timeout' => 5]);

    if (is_wp_error($response)) return 'API Error';

    $data = json_decode(wp_remote_retrieve_body($response));

    if (isset($data->status) && $data->status === 'success') {
        return esc_html($data->city . ', ' . $data->country);
    }

    return 'Unknown Location';
}

// 3. Admin Menu & Dashboard
if ( ! function_exists( 'qcld_seohelp_ai_tracker_menu_setup' ) ) {
 	function qcld_seohelp_ai_tracker_menu_setup(){

    	//add_menu_page('AI Bot Analytics', 'AI Bot Tracker', 'manage_options', 'ai-bot-tracker', 'qcld_seohelp_ai_tracker_render_dashboard', 'dashicons-chart-line');

    	    add_submenu_page(
		      'seo-help',
		      esc_html('AI Bot Analytics', 'seo-help'),
		      esc_html('AI Bot Tracker', 'seo-help'),
		      'manage_options',
		      'ai-bot-trackers',
		      'qcld_seohelp_ai_tracker_render_dashboard'
		    );
	}
}

//add_action('admin_menu','qcld_seohelp_ai_tracker_menu_setup', 99 );

if (!class_exists('WP_List_Table')) {
    require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

class qcld_seohelp_AI_Bot_Table extends WP_List_Table {
    function get_columns() {
		return [
            'cb'          => '<input type="checkbox" />',
            'bot_name'    => 'Bot Name',
            'ip_address'  => 'IP Address', // New Column
            'location'    => 'Location',   // New Column
            'request_url' => 'Requested URL',
            'url_status'  => 'URL Status',
            'visit_count' => 'Visits',
            'last_visit'  => 'Last Visit'
        ];
	}
	
    function column_bot_name($item) {
		// 1. Create a secure delete URL
		$delete_url = sprintf(
			'?page=%s&action=%s&id=%s&_wpnonce=%s',
			esc_attr($_REQUEST['page']),
			'delete',
			absint($item['id']),
			wp_create_nonce('delete_bot_record')
		);

		// 2. Define the action link
		$actions = [
			'delete' => sprintf(
				'<a href="%s" style="color:red;" onclick="return confirm(\'Delete this record?\')">Delete</a>',
				$delete_url
			),
		];

		// 3. Return the Name + the hidden action links
		return sprintf('%1$s %2$s', 
			'<strong>' . esc_html($item['bot_name']) . '</strong>', 
			$this->row_actions($actions)
		);
	}

    function column_default($item, $column_name) {
        return $item[$column_name];
    }
	
	function column_cb($item) {
		return sprintf(
			'<input type="checkbox" name="bulk-delete[]" value="%s" />',
			absint($item['id'])
		);
	}
	
	function column_request_url($item) {
		$url = $item['request_url'];
		$display_url = (strlen($url) > 50) ? substr($url, 0, 47) . '...' : $url;

		return sprintf(
			'<a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a>',
			esc_url($url),
			esc_html($display_url)
		);
	}
    
    function column_url_status($item) {
        $url            = isset($item['request_url']) ? $item['request_url'] : '';
        $response       = wp_remote_get($url, array( 'timeout' => 10 ));
        $response_code  = wp_remote_retrieve_response_code($response);


        if ( ! is_wp_error( $response_code ) ) {

            if ( $response_code >= 200 && $response_code < 300 ) {
                $ui = array( 'bg' => '#46b450', 'text' => '#ffffff', 'label' => 'OK' ); // Green
            } elseif ( $response_code >= 300 && $response_code < 400 ) {
                $ui = array( 'bg' => '#2271b1', 'text' => '#ffffff', 'label' => 'Redirect' ); // Blue
            } elseif ( $response_code === 404 ) {
                $ui = array( 'bg' => '#ffb900', 'text' => '#000000', 'label' => 'Dead End' ); // Yellow
            } elseif ( $response_code >= 500 ) {
                $ui = array( 'bg' => '#dc3232', 'text' => '#ffffff', 'label' => 'Critical' ); // Red
            }
            
            echo sprintf(
                '<span style="background:%s; color:%s; padding:4px 10px; border-radius:4px; font-weight:bold;">%d : %s</span>',
                esc_attr( $ui['bg'] ),
                esc_attr( $ui['text'] ),
                intval( $response_code ),
                esc_html( $ui['label'] )
            );
        } else {
            echo '<span style="color:#dc3232;">Connection Error</span>';
        }
    }
	
	function get_bulk_actions() {
		return [
			'bulk-delete' => 'Delete'
		];
	}
	
	public function prepare_items() {
		global $wpdb;
		$table_name = $wpdb->prefix . 'qcld_ai_bot_tracker';

		// 1. Define how many items per page
		$per_page = 20; 

		// 2. Get the current page number
		$current_page = $this->get_pagenum();

		// Handle Filtering Logic
		//$where = "";
		$where = "WHERE 1=1";
		if (!empty($_REQUEST['filter_bot'])) {
			$where = $wpdb->prepare("WHERE bot_name = %s", $_REQUEST['filter_bot']);
		}

		// Handle Search Query
		if (!empty($_REQUEST['s'])) {
			$search = '%' . $wpdb->esc_like($_REQUEST['s']) . '%';
			$where .= $wpdb->prepare(" AND (bot_name LIKE %s OR request_url LIKE %s OR bot_source LIKE %s)", $search, $search, $search);
		}

		// 3. Count total items in the database
		//$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $table_name"); 
		// Count total with filter
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $table_name $where");


		// 4. Set pagination arguments for the WP_List_Table class
		$this->set_pagination_args([
			'total_items' => $total_items,
			'per_page'    => $per_page,
			'total_pages' => ceil($total_items / $per_page)
		]);

		// 5. Fetch only the data for the current page
		$offset = ($current_page - 1) * $per_page;
		$query = $wpdb->prepare(
			"SELECT * FROM $table_name $where ORDER BY last_visit DESC LIMIT %d OFFSET %d",
			$per_page,
			$offset
		);

		$this->items = $wpdb->get_results($query, ARRAY_A);

		// 6. Define column headers
		$this->_column_headers = [$this->get_columns(), [], []];
	}
	
	function extra_tablenav($which) {
		if ($which == 'top') {
			global $wpdb;
			$table_name = $wpdb->prefix . 'qcld_ai_bot_tracker';
			$bots = $wpdb->get_col("SELECT DISTINCT bot_name FROM $table_name");

			echo '<div class="alignleft actions">';
			echo '<select name="filter_bot">';
			echo '<option value="">All Bots</option>';
			foreach ($bots as $bot) {
				$selected = (isset($_REQUEST['filter_bot']) && $_REQUEST['filter_bot'] == $bot) ? 'selected' : '';
				echo sprintf('<option value="%s" %s>%s</option>', esc_attr($bot), esc_attr($selected), esc_html($bot));
			}
			echo '</select>';
			submit_button('Filter', 'button', 'filter_action', false);
			echo '</div>';
			
			// Add Export Button
			echo '<div class="alignleft actions">';
			$export_url = add_query_arg(['action' => 'export_csv', '_wpnonce' => wp_create_nonce('qcld_seohelp_ai_tracker_export')], menu_page_url('ai-bot-tracker', false));
			echo '<a href="' . esc_url($export_url) . '" class="page-title-action">Export to CSV</a>';
			echo '</div>';
		}
	}
}

function qcld_seohelp_ai_tracker_render_dashboard() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'qcld_ai_bot_tracker';

    $table = new qcld_seohelp_AI_Bot_Table();

    // 1. Handle Bulk Actions
    $action = $table->current_action();
    if ($action === 'bulk-delete' && !empty($_REQUEST['bulk-delete'])) {
        // Verify nonce for security
        check_admin_referer('bulk-' . $table->_args['plural']);
        
        $ids = array_map('absint', $_REQUEST['bulk-delete']);
        $ids_string = implode(',', $ids);
        
        $wpdb->query("DELETE FROM $table_name WHERE id IN ($ids_string)");
        echo '<div class="updated notice"><p>Selected records deleted.</p></div>';
    }

    // 2. Handle Single Row Delete (from previous step)
    if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
        check_admin_referer('delete_bot_record');
        $wpdb->delete($table_name, ['id' => absint($_GET['id'])]);
        echo '<div class="updated notice"><p>Record deleted!</p></div>';
    }

	$stats = qcld_seohelp_ai_tracker_get_stats();
    $table->prepare_items();
	
    ?>
    <div class="wrap">
        <h1 class="wp-heading-inline">AI Bot Visits Tracker</h1>
		<?php 
		    echo '
				<div class="ai-stats-container">
					<div class="ai-card all-time">
						<h3>Total Hits</h3>
						<div class="value">' . number_format($stats['all_time']) . '</div>
						<div class="subtitle">All time recorded visits</div>
					</div>
					<div class="ai-card week">
						<h3>Weekly</h3>
						<div class="value">' . number_format($stats['week']) . '</div>
						<div class="subtitle">Last 7 days</div>
					</div>
					<div class="ai-card month">
						<h3>Monthly</h3>
						<div class="value">' . number_format($stats['month']) . '</div>
						<div class="subtitle">Last 30 days</div>
					</div>
					<div class="ai-card quarter">
						<h3>Quarterly</h3>
						<div class="value">' . number_format($stats['quarter']) . '</div>
						<div class="subtitle">Last 90 days</div>
					</div>
				</div>';
		?>
        <?php 
            // Get total hits for percentage calculation
            $total_hits = $wpdb->get_var("SELECT SUM(visit_count) FROM $table_name") ?: 1;
            $paths = qcld_seohelp_ai_tracker_get_path_stats();
            
            // Get Top 5 Bots
            $top_bots = $wpdb->get_results("
                SELECT bot_name, SUM(visit_count) as bot_hits 
                FROM $table_name 
                GROUP BY bot_name 
                ORDER BY bot_hits DESC 
                LIMIT 5
            ");

            if (!empty($top_bots) && !empty($paths)){
                echo '<div class="ai-leaderboard-wrap">';
                echo '<div class="ai-leaderboard-path-wrap">';
            }

            if (!empty($top_bots)){

                echo '<div class="ai-leaderboard-container">';
                echo '<div class="ai-leaderboard-header">';
                echo '<span class="dashicons dashicons-chart-bar"></span>';
                echo '<h2>Top AI Visitors Leaderboard</h2>';
                echo '</div>';

                foreach ($top_bots as $index => $bot) {
                    $percentage = round(($bot->bot_hits / $total_hits) * 100);
                    echo '<div class="bot-rank-row rank-' . esc_attr($index) . '">';
                    echo '  <div class="bot-info">';
                    echo '      <span class="bot-name">' . esc_html($bot->bot_name) . '</span>';
                    echo '      <span class="bot-percentage">' . number_format($bot->bot_hits) . ' hits (' . esc_attr($percentage) . '%)</span>';
                    echo '  </div>';
                    echo '  <div class="progress-bar-bg">';
                    echo '      <div class="progress-bar-fill" style="width: ' . esc_attr($percentage) . '%;"></div>';
                    echo '  </div>';
                    echo '</div>';
                }
                echo '</div>';
            }
        ?>
        <?php 
            if (!empty($paths)) {

                $max_hits = $paths[0]->total_hits ?: 1;

                echo '<div class="ai-path-card">';
                echo '  <div class="ai-path-header">';
                echo '      <h2><span class="dashicons dashicons-visibility"></span> Most Visited Content Paths</h2>';
                echo '      <span class="ai-pressure-badge">Live Analysis</span>';
                echo '  </div>';

                foreach ($paths as $p) {
                    $relative_url = str_replace(get_site_url(), '', $p->request_url);
                    $relative_url = ($relative_url == '') ? '/' : $relative_url;
                    
                    echo '<div class="path-row">';
                    echo '  <div class="path-main">';
                    echo '      <a href="' . esc_url($p->request_url) . '" target="_blank" class="path-url-display">' . esc_html($relative_url) . '</a>';
                    echo '      <div class="path-meta-info">Last crawl: ' . esc_attr(human_time_diff(strtotime($p->latest_hit))) . ' ago</div>';
                    echo '  </div>';
                    echo '  <div class="path-metrics">';
                    echo '      <div class="metric-box"><span class="label">Bots</span><span class="val">' . esc_html($p->bot_count) . '</span></div>';
                    echo '      <div class="metric-box"><span class="label">Total Hits</span><span class="val">' . number_format($p->total_hits) . '</span></div>';
                    echo '  </div>';
                    echo '</div>';
                }
                echo '</div>';
            }

            if (!empty($top_bots) && !empty($paths)){
                echo '</div>';
            	qcld_seohelp_ai_tracker_render_trend_chart();
                echo '</div>';
            }

        ?>
        <form method="post"> <!-- Change to POST for bulk actions -->
            <?php 
			echo '<input type="hidden" name="page" value="' . esc_attr($_REQUEST['page']) . '" />';
			$table->search_box('Search Bots', 'search_id');
            $table->display(); 
            // Important: Nonce and referrer fields for WP security
            wp_nonce_field('bulk-' . $table->_args['plural']);
            ?>
        </form>
    </div>
    <?php
}

function qcld_seohelp_ai_tracker_get_stats() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'qcld_ai_bot_tracker';

    $stats = [];
    // All Time
    $stats['all_time'] = $wpdb->get_var("SELECT SUM(visit_count) FROM $table_name") ?: 0;
    
    // Last 7 Days
    $stats['week'] = $wpdb->get_var("SELECT SUM(visit_count) FROM $table_name WHERE last_visit >= DATE_SUB(NOW(), INTERVAL 7 DAY)") ?: 0;
    
    // Last 30 Days
    $stats['month'] = $wpdb->get_var("SELECT SUM(visit_count) FROM $table_name WHERE last_visit >= DATE_SUB(NOW(), INTERVAL 30 DAY)") ?: 0;
    
    // Last 90 Days (Quarter)
    $stats['quarter'] = $wpdb->get_var("SELECT SUM(visit_count) FROM $table_name WHERE last_visit >= DATE_SUB(NOW(), INTERVAL 90 DAY)") ?: 0;

    return $stats;
}

function qcld_seohelp_ai_tracker_get_path_stats() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'qcld_ai_bot_tracker';
    return $wpdb->get_results("
        SELECT request_url, 
               SUM(visit_count) as total_hits, 
               COUNT(DISTINCT bot_name) as bot_count,
               MAX(last_visit) as latest_hit
        FROM $table_name 
        GROUP BY request_url 
        ORDER BY total_hits DESC 
        LIMIT 8
    ");
}

function qcld_seohelp_ai_tracker_get_30_day_trend() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'qcld_ai_bot_tracker';
    
    // Query hits per day for the last 30 days
    $results = $wpdb->get_results("
        SELECT DATE(last_visit) as visit_date, SUM(visit_count) as daily_hits
        FROM $table_name
        WHERE last_visit >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        GROUP BY DATE(last_visit)
        ORDER BY visit_date ASC
    ", ARRAY_A);

    // Fill in missing dates with zero hits to ensure a continuous line
    $trend = [];
    for ($i = 29; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $found = false;
        foreach ($results as $row) {
            if ($row['visit_date'] === $date) {
                $trend[$date] = (int)$row['daily_hits'];
                $found = true;
                break;
            }
        }
        if (!$found) $trend[$date] = 0;
    }
    return $trend;
}

function qcld_seohelp_ai_tracker_render_trend_chart() {
    $trend_data = qcld_seohelp_ai_tracker_get_30_day_trend();
    $labels = json_encode(array_keys($trend_data));
    $values = json_encode(array_values($trend_data));

    echo '
    <div class="ai-card trend-container" style="margin-bottom:20px; padding:25px; background:#fff; border-radius:12px; border:1px solid #e2e8f0;">
        <h2 style="margin:0 0 20px 0; font-size:1.1rem; color:#1e293b;">
            <span class="dashicons dashicons-chart-line" style="vertical-align:middle; margin-right:8px; color:#3b82f6;"></span>
            AI Bot Traffic Trend (Last 30 Days)
        </h2>
        <canvas id="aiTrendChart" height="100"></canvas>
    </div>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const ctx = document.getElementById("aiTrendChart").getContext("2d");
            new Chart(ctx, {
                type: "line",
                data: {
                    labels: ' . esc_attr($labels) . ',
                    datasets: [{
                        label: "Total Hits",
                        data: ' . esc_attr($values) . ',
                        borderColor: "#3b82f6",
                        backgroundColor: "rgba(59, 130, 246, 0.1)",
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointRadius: 2,
                        pointHoverRadius: 6
                    }]
                },
                options: {
                    responsive: true,
                    plugins: { legend: { display: false } },
                    scales: {
                        x: { display: false },
                        y: { 
                            beginAtZero: true, 
                            grid: { color: "#f1f5f9" },
                            ticks: { font: { size: 10 }, color: "#64748b" }
                        }
                    }
                }
            });
        });
    </script>';
}


function qcld_seohelp_ai_tracker_handle_csv_export() {
    if (isset($_GET['action']) && $_GET['action'] === 'export_csv') {
        // 1. Security check
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'qcld_seohelp_ai_tracker_export')) {
            wp_die('Security check failed.');
        }

        // 2. Clear buffers to ensure only CSV data is sent
        if (ob_get_level()) ob_end_clean();

        // 3. Set download headers
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=ai_bot_visits_' . date('Y-m-d') . '.csv');

        // 4. Fetch all data
        global $wpdb;
        $table_name = $wpdb->prefix . 'qcld_ai_bot_tracker';
        $rows = $wpdb->get_results("SELECT id, bot_name, bot_source, ip_address, location, request_url, visit_count, last_visit FROM $table_name ORDER BY last_visit DESC", ARRAY_A);

        // 5. Open output stream
        $output = fopen('php://output', 'w');

        // 6. Add Column Headers
        fputcsv($output, ['ID', 'Bot Name', 'User Agent Source', 'IP Address', 'Location', 'Requested URL', 'Visits', 'Last Visit']);

        // 7. Loop through data and write to CSV
        if (!empty($rows)) {
            foreach ($rows as $row) {
                fputcsv($output, $row);
            }
        }

        fclose($output);
        wp_die(); // Important: Stop WordPress from loading the rest of the page
    }
}
add_action('admin_init', 'qcld_seohelp_ai_tracker_handle_csv_export');
