<?php
/**
 * Analytics functionality for LLMS.txt Generator
 */
if (!defined('ABSPATH')) {
    exit;
}
class CCSPLLMS_Analytics {
    
    private $database;
    
    public function __construct() {
        $this->database = new CCSPLLMS_Database();
    }
    
    public function log_request() {
        $user_agent = sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ?? '' ) );
        $ip_address = $this->get_client_ip();
        $bot_name = $this->identify_bot($user_agent);

        error_log('[CCSP LLms.txt Generator]: Bot Access - ' . ($bot_name ?: 'Unknown') . ' | IP: ' . $ip_address);
        
        // Check if bot is blocked
        if ($this->is_bot_blocked($bot_name)) {
            http_response_code(403);
            exit('Access denied');
        }
        
        $this->database->log_bot_visit($bot_name, $ip_address, $user_agent);
        
        // Send notification if enabled
        if (get_option('ccspllms_email_notifications') && $this->is_new_bot($bot_name)) {
            $this->send_new_bot_notification($bot_name, $ip_address);
        }
    }
    
    private function get_client_ip() {
        $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR');
        
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', sanitize_text_field(wp_unslash($_SERVER[$key]))) as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                        return $ip;
                    }
                }
            }
        }
        
        $ip_address = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : 'unknown';

        return $ip_address ?: 'unknown';

    }
    
    private function identify_bot($user_agent) {
        global $wpdb;
        $bots_table = $wpdb->prefix . 'ccspllms_bots';

        // Get all bots from DB
        $bots = $wpdb->get_results("
            SELECT bot_name, user_agent_pattern 
            FROM $bots_table
        ");

        if ($bots) {
            foreach ($bots as $bot) {
                if (!empty($bot->user_agent_pattern) && stripos($user_agent, $bot->user_agent_pattern) !== false) {
                    return $bot->bot_name;
                }
            }
        }

        // Check for generic bot indicators
        $generic_patterns = array('bot', 'crawler', 'spider', 'scraper');
        foreach ($generic_patterns as $pattern) {
            if (stripos($user_agent, $pattern) !== false) {
                return 'Unknown Bot';
            }
        }

        return null; // Not a bot
    }

    
    private function is_bot_blocked($bot_name) {
        if (!$bot_name) {
            return false;
        }
        
        global $wpdb;
        $bots_table = $wpdb->prefix . 'ccspllms_bots';
        
        $result = $wpdb->get_var($wpdb->prepare("
            SELECT status FROM $bots_table 
            WHERE bot_name = %s
        ", $bot_name));
        
        return $result === 'blocked';
    }
    
    private function is_new_bot($bot_name) {
        if (!$bot_name) {
            return false;
        }
        
        global $wpdb;
        $bots_table = $wpdb->prefix . 'ccspllms_bots';
        
        $count = $wpdb->get_var($wpdb->prepare("
            SELECT visit_count FROM $bots_table 
            WHERE bot_name = %s
        ", $bot_name));
        
        return $count <= 1; // First or second visit
    }
    
    private function send_new_bot_notification($bot_name, $ip_address) {
        $email = get_option('ccspllms_notification_email') ?: get_option('admin_email');
        $subject = 'New Bot Detected - LLMS.txt Generator';
        
        $message = "A new bot has been detected accessing your LLMS.txt file:\n\n";
        $message .= "Bot Name: {$bot_name}\n";
        $message .= "IP Address: {$ip_address}\n";
        $message .= "Time: " . current_time('Y-m-d H:i:s') . "\n";
        $message .= "Site: " . get_site_url() . "\n\n";
        $message .= "You can manage bot access in your WordPress admin panel.";
        
        wp_mail($email, $subject, $message);
    }
    
    public function get_analytics_data() {
        $data = array();
        
        // Get daily stats for last 30 days
        $data['daily_stats'] = $this->database->get_analytics_data(30);
        
        // Get bot statistics
        $data['bot_stats'] = $this->database->get_bot_stats();
        
        // Get total counts
        $data['totals'] = $this->get_total_stats();
        
        // Get recent visits
        $data['recent_visits'] = $this->get_recent_visits();
        
        return $data;
    }

   
    
    private function get_total_stats() {
        global $wpdb;
        $analytics_table = $wpdb->prefix . 'ccspllms_analytics';
        
        $stats = $wpdb->get_row("
            SELECT 
                COUNT(*) as total_visits,
                COUNT(DISTINCT ip_address) as unique_visitors,
                COUNT(DISTINCT bot_name) as unique_bots,
                COUNT(CASE WHEN DATE(request_time) = CURDATE() THEN 1 END) as today_visits
            FROM $analytics_table
        ", ARRAY_A);
        
        return $stats;
    }
    
    private function get_recent_visits($limit = 10) {
        global $wpdb;
        $analytics_table = $wpdb->prefix . 'ccspllms_analytics';
        
        $results = $wpdb->get_results($wpdb->prepare("
            SELECT bot_name, ip_address, request_time, user_agent
            FROM $analytics_table
            ORDER BY request_time DESC
            LIMIT %d
        ", $limit));
        
        return $results;
    }
    
    public function export_analytics_data($format = 'csv') {
        $data = $this->get_analytics_data();

        
        if ($format === 'csv') {
            return $this->export_to_csv($data);
        } elseif ($format === 'json') {
            return json_encode($data, JSON_PRETTY_PRINT);
        }
        
        return false;
    }
    
    private function export_to_csv($data) {
        $output = "Date,Bot Name,IP Address,User Agent\n";
        
        foreach ($data['recent_visits'] as $visit) {
            $output .= sprintf(
                "%s,%s,%s,%s\n",
                $visit->request_time,
                $visit->bot_name ?: 'Unknown',
                $visit->ip_address,
                str_replace(',', ';', $visit->user_agent)
            );
        }
        
        return $output;
    }
}