<?php
// Enhanced SSA Dashboard - Improved Version
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/config.php';

// Enhanced Security Class
class Security {
    public static function sanitizeInput($input) {
        return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
    }
    
    public static function validateIP($ip) {
        return filter_var($ip, FILTER_VALIDATE_IP);
    }
    
    public static function generateCSRFToken() {
        if (!isset($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf_token'];
    }
    
    public static function validateCSRFToken($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
}

// Start session with enhanced security settings
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', 1);
    ini_set('session.cookie_secure', 1);
    ini_set('session.use_only_cookies', 1);
    ini_set('session.cookie_samesite', 'Strict');
    session_start();
}

// Set admin as logged in (temporary - will be replaced with proper login)
$_SESSION['admin_logged_in'] = true;
$_SESSION['last_activity'] = time();

// Enhanced Log Path Configuration
class LogManager {
    private static $LOG_BASE_PATH = __DIR__ . '/data/analytics/';
    
    public static function getLogPath($type) {
        $paths = [
            'visits' => self::$LOG_BASE_PATH . 'visits.log',
            'downloads' => self::$LOG_BASE_PATH . 'downloads.log',
            'bots' => self::$LOG_BASE_PATH . 'bots.log',
            'errors' => self::$LOG_BASE_PATH . 'errors.log',
            'security' => self::$LOG_BASE_PATH . 'security.log'
        ];
        
        // Create directory if it doesn't exist
        $dir = dirname($paths[$type]);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        
        return $paths[$type] ?? null;
    }
}

// Enhanced IP Detection
function getRealIP() {
    $headers = [
        'HTTP_CF_CONNECTING_IP',
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
    ];
    
    foreach ($headers as $header) {
        if (isset($_SERVER[$header]) && !empty($_SERVER[$header])) {
            $ip = trim($_SERVER[$header]);
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                return $ip;
            }
        }
    }
    
    return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
}

$_SESSION['login_ip'] = getRealIP();

// Enhanced System Information
class SystemMonitor {
    public static function getSystemInfo() {
        return [
            'php_version' => PHP_VERSION,
            'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
            'memory' => [
                'usage' => memory_get_usage(true),
                'peak' => memory_get_peak_usage(true),
                'limit' => ini_get('memory_limit')
            ],
            'network' => [
                'server_ip' => $_SERVER['SERVER_ADDR'] ?? 'Unknown',
                'server_port' => $_SERVER['SERVER_PORT'] ?? 'Unknown',
                'client_ip' => getRealIP()
            ],
            'server_time' => date('Y-m-d H:i:s'),
            'timezone' => date_default_timezone_get(),
            'disk' => self::getDiskInfo(),
            'uptime' => self::getUptime()
        ];
    }
    
    private static function getDiskInfo() {
        $path = __DIR__;
        $total = disk_total_space($path);
        $free = disk_free_space($path);
        $used = $total - $free;
        
        return [
            'total' => $total,
            'free' => $free,
            'used' => $used,
            'usage_percent' => $total > 0 ? round(($used / $total) * 100, 2) : 0
        ];
    }
    
    private static function getUptime() {
        if (function_exists('sys_getloadavg')) {
            $load = sys_getloadavg();
            return [
                'load_1min' => $load[0] ?? 0,
                'load_5min' => $load[1] ?? 0,
                'load_15min' => $load[2] ?? 0
            ];
        }
        return null;
    }
}

// Enhanced Log Parser with Better Error Handling
class LogParser {
    public static function parseLogLine($line) {
        if (empty(trim($line))) return null;
        
        $parts = explode(' - ', $line);
        if (count($parts) >= 7) {
            return [
                'timestamp' => trim($parts[0]),
                'ip' => trim($parts[1]),
                'country' => trim($parts[2]),
                'region' => trim($parts[3]),
                'city' => trim($parts[4]),
                'isp' => trim($parts[5]),
                'os' => trim($parts[6]),
                'user_agent' => isset($parts[7]) ? trim($parts[7]) : 'Unknown'
            ];
        }
        return null;
    }
    
    public static function readLogFile($filename) {
        $data = [];
        if (!file_exists($filename)) {
            return $data;
        }
        
        try {
            $lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            if ($lines === false) return $data;
            
            foreach ($lines as $line) {
                if (strpos(basename($filename), 'bots') !== false) {
                    // Handle JSON data in bots log
                    $entry = json_decode($line, true);
                    if ($entry && json_last_error() === JSON_ERROR_NONE) {
                        $data[] = $entry;
                    }
                } else {
                    // Handle regular log format
                    $entry = self::parseLogLine($line);
                    if ($entry) {
                        $data[] = $entry;
                    }
                }
            }
        } catch (Exception $e) {
            error_log("Error reading log file $filename: " . $e->getMessage());
        }
        
        return $data;
    }
}

// Enhanced Analytics Engine
class AnalyticsEngine {
    public static function countUniqueIPs($data) {
        $ips = [];
        foreach ($data as $entry) {
            if (isset($entry['ip']) && Security::validateIP($entry['ip'])) {
                $ips[$entry['ip']] = true;
            }
        }
        return count($ips);
    }
    
    public static function countLastPeriod($data, $hours = 24) {
        $threshold = time() - ($hours * 3600);
        $count = 0;
        
        foreach ($data as $entry) {
            if (isset($entry['timestamp'])) {
                $timestamp = strtotime($entry['timestamp']);
                if ($timestamp !== false && $timestamp >= $threshold) {
                    $count++;
                }
            }
        }
        return $count;
    }
    
    public static function getTopEntries($data, $field, $limit = 10) {
        $entries = [];
        foreach ($data as $entry) {
            if (isset($entry[$field]) && !empty($entry[$field])) {
                $key = $entry[$field];
                $entries[$key] = ($entries[$key] ?? 0) + 1;
            }
        }
        arsort($entries);
        return array_slice($entries, 0, $limit, true);
    }
    
    public static function getTopLocations($data, $limit = 10) {
        $locations = [];
        foreach ($data as $entry) {
            if (isset($entry['country'])) {
                $location = $entry['country'];
                if (isset($entry['city']) && !empty($entry['city'])) {
                    $location .= ', ' . $entry['city'];
                }
                $locations[$location] = ($locations[$location] ?? 0) + 1;
            }
        }
        arsort($locations);
        return array_slice($locations, 0, $limit, true);
    }
    
    public static function analyzeTimePatterns($data) {
        $patterns = [
            'morning' => ['count' => 0, 'unique_ips' => [], 'locations' => []],
            'afternoon' => ['count' => 0, 'unique_ips' => [], 'locations' => []],
            'evening' => ['count' => 0, 'unique_ips' => [], 'locations' => []],
            'night' => ['count' => 0, 'unique_ips' => [], 'locations' => []]
        ];
        
        $total_entries = count($data);
        if ($total_entries === 0) return $patterns;
        
        foreach ($data as $entry) {
            if (!isset($entry['timestamp'])) continue;
            
            try {
                $timestamp = strtotime($entry['timestamp']);
                if ($timestamp === false) continue;
                
                $hour = (int)date('G', $timestamp);
                $period = self::getTimePeriod($hour);
                
                $patterns[$period]['count']++;
                
                if (isset($entry['ip'])) {
                    $patterns[$period]['unique_ips'][$entry['ip']] = true;
                }
                
                if (isset($entry['country'])) {
                    $location = $entry['country'];
                    if (isset($entry['city']) && !empty($entry['city'])) {
                        $location .= ', ' . $entry['city'];
                    }
                    $patterns[$period]['locations'][$location] = 
                        ($patterns[$period]['locations'][$location] ?? 0) + 1;
                }
            } catch (Exception $e) {
                continue;
            }
        }
        
        // Calculate additional metrics
        foreach ($patterns as $period => &$data) {
            $data['unique_visitors'] = count($data['unique_ips']);
            $data['percentage'] = $total_entries > 0 ? 
                round(($data['count'] / $total_entries) * 100, 2) : 0;
            arsort($data['locations']);
            $data['top_locations'] = array_slice($data['locations'], 0, 3, true);
        }
        
        return $patterns;
    }
    
    private static function getTimePeriod($hour) {
        if ($hour >= 6 && $hour < 12) return 'morning';
        if ($hour >= 12 && $hour < 18) return 'afternoon';
        if ($hour >= 18 && $hour < 24) return 'evening';
        return 'night';
    }
    
    public static function analyzeUserBehavior($visits, $downloads) {
        $total_visits = count($visits);
        $total_downloads = count($downloads);
        
        return [
            'conversion_rate' => $total_visits > 0 ? 
                round(($total_downloads / $total_visits) * 100, 2) : 0,
            'bounce_rate' => self::calculateBounceRate($visits),
            'avg_session_duration' => self::calculateAvgSessionDuration($visits),
            'repeat_visitors' => self::calculateRepeatVisitors($visits)
        ];
    }
    
    private static function calculateBounceRate($visits) {
        // Simplified bounce rate calculation
        return rand(15, 35); // Placeholder - implement actual logic
    }
    
    private static function calculateAvgSessionDuration($visits) {
        // Simplified session duration calculation
        return rand(120, 300); // Placeholder - implement actual logic
    }
    
    private static function calculateRepeatVisitors($visits) {
        $ip_counts = [];
        foreach ($visits as $visit) {
            if (isset($visit['ip'])) {
                $ip_counts[$visit['ip']] = ($ip_counts[$visit['ip']] ?? 0) + 1;
            }
        }
        
        $repeat_count = 0;
        foreach ($ip_counts as $count) {
            if ($count > 1) $repeat_count++;
        }
        
        return $repeat_count;
    }
}

// Enhanced Bot Detection
class BotAnalyzer {
    public static function analyzeBotPatterns($data) {
        $patterns = [
            'suspicious_ips' => [],
            'high_frequency' => [],
            'malicious_attempts' => 0,
            'time_patterns' => [
                'morning' => 0, 'afternoon' => 0, 'evening' => 0, 'night' => 0
            ],
            'user_agents' => [],
            'countries' => []
        ];
        
        $ip_counts = [];
        $last_24h = time() - 86400;
        
        foreach ($data as $entry) {
            if (!isset($entry['ip'])) continue;
            
            // Count IP frequency
            $ip_counts[$entry['ip']] = ($ip_counts[$entry['ip']] ?? 0) + 1;
            
            // Analyze user agents
            if (isset($entry['user_agent'])) {
                $ua = strtolower($entry['user_agent']);
                if (self::isSuspiciousUserAgent($ua)) {
                    $patterns['malicious_attempts']++;
                }
                $patterns['user_agents'][$entry['user_agent']] = 
                    ($patterns['user_agents'][$entry['user_agent']] ?? 0) + 1;
            }
            
            // Analyze countries
            if (isset($entry['country'])) {
                $patterns['countries'][$entry['country']] = 
                    ($patterns['countries'][$entry['country']] ?? 0) + 1;
            }
            
            // Analyze time patterns
            if (isset($entry['timestamp'])) {
                try {
                    $timestamp = strtotime($entry['timestamp']);
                    if ($timestamp !== false) {
                        $hour = (int)date('G', $timestamp);
                        $period = AnalyticsEngine::getTimePeriod($hour);
                        $patterns['time_patterns'][$period]++;
                    }
                } catch (Exception $e) {
                    continue;
                }
            }
        }
        
        // Identify suspicious IPs
        foreach ($ip_counts as $ip => $count) {
            if ($count > 50) {
                $patterns['suspicious_ips'][] = ['ip' => $ip, 'count' => $count];
            } elseif ($count > 10) {
                $patterns['high_frequency'][] = ['ip' => $ip, 'count' => $count];
            }
        }
        
        // Sort by frequency
        arsort($patterns['user_agents']);
        arsort($patterns['countries']);
        
        return $patterns;
    }
    
    private static function isSuspiciousUserAgent($ua) {
        $suspicious_patterns = [
            'bot', 'crawler', 'spider', 'scraper', 'hack', 'exploit',
            'injection', 'sqlmap', 'nikto', 'nmap', 'masscan'
        ];
        
        foreach ($suspicious_patterns as $pattern) {
            if (strpos($ua, $pattern) !== false) {
                return true;
            }
        }
        return false;
    }
}

// API Credits Monitor
class APICreditsMonitor {
    public static function fetchRemainingCredits() {
        if (!defined('IPDETECTIVE_API_KEY') || empty(IPDETECTIVE_API_KEY)) {
            return ['error' => 'API key not configured'];
        }
        
        $url = "https://api.ipdetective.io/usage";
        $ch = curl_init($url);
        
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ["x-api-key: " . IPDETECTIVE_API_KEY],
            CURLOPT_TIMEOUT => 10,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_USERAGENT => 'SSA-Dashboard/1.0'
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($response === false || $httpCode !== 200) {
            return ['error' => 'Failed to fetch credits data'];
        }
        
        $data = json_decode($response, true);
        if (!$data || !isset($data['lookup_limit'], $data['lookup_hits'])) {
            return ['error' => 'Invalid response format'];
        }
        
        $total = (int)$data['lookup_limit'];
        $used = (int)$data['lookup_hits'];
        
        return [
            'remaining' => $total - $used,
            'used' => $used,
            'total' => $total,
            'percent_used' => $total > 0 ? round(($used / $total) * 100, 2) : 0,
            'last_updated' => date('Y-m-d H:i:s')
        ];
    }
}

// Load system information
$systemInfo = SystemMonitor::getSystemInfo();

// Read log files using new path structure
$visits = LogParser::readLogFile(LogManager::getLogPath('visits'));
$downloads = LogParser::readLogFile(LogManager::getLogPath('downloads'));
$bots = LogParser::readLogFile(LogManager::getLogPath('bots'));

// Process analytics data
$stats = [
    'visits' => [
        'total' => count($visits),
        'unique' => AnalyticsEngine::countUniqueIPs($visits),
        'last24h' => AnalyticsEngine::countLastPeriod($visits, 24),
        'last7d' => AnalyticsEngine::countLastPeriod($visits, 168),
        'hourly' => array_fill(0, 24, 0),
        'daily' => array_fill(0, 7, 0),
        'top_locations' => AnalyticsEngine::getTopLocations($visits, 10),
        'top_isps' => AnalyticsEngine::getTopEntries($visits, 'isp', 10),
        'top_os' => AnalyticsEngine::getTopEntries($visits, 'os', 10),
        'time_patterns' => AnalyticsEngine::analyzeTimePatterns($visits)
    ],
    'downloads' => [
        'total' => count($downloads),
        'unique' => AnalyticsEngine::countUniqueIPs($downloads),
        'last24h' => AnalyticsEngine::countLastPeriod($downloads, 24),
        'last7d' => AnalyticsEngine::countLastPeriod($downloads, 168),
        'hourly' => array_fill(0, 24, 0),
        'daily' => array_fill(0, 7, 0),
        'top_locations' => AnalyticsEngine::getTopLocations($downloads, 10),
        'top_isps' => AnalyticsEngine::getTopEntries($downloads, 'isp', 10),
        'top_os' => AnalyticsEngine::getTopEntries($downloads, 'os', 10),
        'time_patterns' => AnalyticsEngine::analyzeTimePatterns($downloads)
    ],
    'bots' => [
        'total' => count($bots),
        'unique' => AnalyticsEngine::countUniqueIPs($bots),
        'last24h' => AnalyticsEngine::countLastPeriod($bots, 24),
        'last7d' => AnalyticsEngine::countLastPeriod($bots, 168),
        'patterns' => BotAnalyzer::analyzeBotPatterns($bots)
    ],
    'behavior' => AnalyticsEngine::analyzeUserBehavior($visits, $downloads)
];

// Process hourly and daily distribution
foreach (['visits', 'downloads'] as $type) {
    $data = ${$type};
    foreach ($data as $entry) {
        if (isset($entry['timestamp'])) {
            try {
                $timestamp = strtotime($entry['timestamp']);
                if ($timestamp !== false) {
                    $hour = (int)date('G', $timestamp);
                    $day = (int)date('w', $timestamp);
                    $stats[$type]['hourly'][$hour]++;
                    $stats[$type]['daily'][$day]++;
                }
            } catch (Exception $e) {
                continue;
            }
        }
    }
}

// Get API credits
$apiCredits = APICreditsMonitor::fetchRemainingCredits();

// Handle settings update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_settings') {
    if (!Security::validateCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $newConfig = [
            'IPDETECTIVE_API_KEY' => Security::sanitizeInput($_POST['IPDETECTIVE_API_KEY'] ?? ''),
            'telegram_bot_token' => Security::sanitizeInput($_POST['telegram_bot_token'] ?? ''),
            'telegram_chat_id' => Security::sanitizeInput($_POST['telegram_chat_id'] ?? '')
        ];

        $configFile = __DIR__ . '/config.json';
        $existingConfig = [];
        if (file_exists($configFile)) {
            $configContent = file_get_contents($configFile);
            if ($configContent !== false) {
                $existingConfig = json_decode($configContent, true) ?? [];
            }
        }

        $updatedConfig = array_merge($existingConfig, $newConfig);

        if (file_put_contents($configFile, json_encode($updatedConfig, JSON_PRETTY_PRINT))) {
            header('Location: ' . $_SERVER['PHP_SELF'] . '?settings_updated=1');
            exit;
        } else {
            $error = 'Failed to save settings. Please check file permissions.';
        }
    }
}

// Handle AJAX requests
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    echo json_encode([
        'stats' => $stats,
        'system' => $systemInfo,
        'api_credits' => $apiCredits,
        'timestamp' => time()
    ]);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="robots" content="noindex, nofollow">
    <title>Enhanced SSA Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --primary: #00ff41;
            --secondary: #00d4ff;
            --accent: #ff6b35;
            --bg-dark: #0a0a0a;
            --bg-card: #1a1a1a;
            --bg-sidebar: #151515;
            --text: #e0e0e0;
            --text-muted: #888;
            --text-dim: #666;
            --border: #333;
            --border-light: #444;
            --success: #00ff41;
            --warning: #ffb347;
            --danger: #ff4757;
            --info: #3498db;
        }
        
        * { 
            margin: 0; 
            padding: 0; 
            box-sizing: border-box; 
        }
        
        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: var(--bg-dark);
            color: var(--text);
            line-height: 1.6;
            font-size: 14px;
            display: flex;
            min-height: 100vh;
        }

        /* Enhanced Sidebar */
        .sidebar { 
            width: 320px;
            background: var(--bg-sidebar);
            border-right: 2px solid var(--border);
            padding: 25px;
            position: fixed;
            height: 100vh; 
            overflow-y: auto;
            box-shadow: 4px 0 15px rgba(0, 0, 0, 0.3);
        }

        .sidebar::-webkit-scrollbar {
            width: 6px;
        }

        .sidebar::-webkit-scrollbar-track {
            background: var(--bg-dark);
        }

        .sidebar::-webkit-scrollbar-thumb {
            background: var(--primary);
            border-radius: 3px;
        }

        .sidebar h1 {
            color: var(--primary);
            font-size: 24px;
            margin-bottom: 35px;
            text-transform: uppercase;
            letter-spacing: 3px;
            border-bottom: 3px solid var(--primary);
            padding-bottom: 15px;
            text-align: center;
            text-shadow: 0 0 10px var(--primary);
        }

        /* Enhanced Info Cards */
        .info-card {
            background: linear-gradient(135deg, var(--bg-card) 0%, #1f1f1f 100%);
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .info-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
        }

        .info-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(0, 255, 65, 0.1);
            border-color: var(--primary);
        }

        .info-card h3 {
            color: var(--secondary);
            font-size: 16px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 600;
        }

        .info-value {
            font-size: 18px;
            color: var(--primary);
            font-weight: bold;
            margin-bottom: 8px;
            text-shadow: 0 0 5px var(--primary);
        }

        .progress-bar {
            width: 100%; 
            height: 6px;
            background: var(--border);
            border-radius: 3px;
            overflow: hidden;
            margin-top: 10px;
            position: relative;
        }

        .progress-bar-fill {
            height: 100%;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            transition: width 0.6s ease;
            border-radius: 3px;
        }

        /* Main Content */
        .main-content { 
            flex: 1;
            margin-left: 320px;
            padding: 30px;
            background: var(--bg-dark);
        }

        /* Enhanced Summary Stats */
        .summary-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 25px;
            margin-bottom: 40px;
        }

        .stat-card {
            background: linear-gradient(135deg, var(--bg-card) 0%, #1f1f1f 100%);
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 30px;
            text-align: center;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0, 255, 65, 0.15);
        }

        .stat-card h3 {
            color: var(--secondary);
            font-size: 16px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            font-weight: 600;
        }

        .stat-value {
            font-size: 32px;
            color: var(--primary);
            font-weight: bold;
            text-shadow: 0 0 10px var(--primary);
            margin-bottom: 10px;
        }

        .stat-change {
            font-size: 12px;
            color: var(--success);
        }

        /* Enhanced Analysis Grid */
        .analysis-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 25px;
            margin-bottom: 40px;
        }

        .analysis-card {
            background: linear-gradient(135deg, var(--bg-card) 0%, #1f1f1f 100%);
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 25px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .analysis-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, var(--secondary), var(--accent));
        }

        .analysis-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0, 212, 255, 0.1);
        }

        .analysis-card h3 {
            color: var(--secondary);
            font-size: 18px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 600;
        }

        .analysis-list {
            list-style: none;
        }

        .analysis-list li {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid var(--border);
            transition: all 0.3s ease;
        }

        .analysis-list li:last-child {
            border-bottom: none;
        }

        .analysis-list li:hover {
            background: rgba(0, 255, 65, 0.05);
            padding-left: 10px;
            border-radius: 6px;
        }

        .analysis-value {
            color: var(--primary);
            font-weight: bold;
            text-shadow: 0 0 5px var(--primary);
        }

        /* Enhanced Charts */
        .charts-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
            gap: 30px;
            margin-bottom: 30px;
        }

        .chart-container {
            background: linear-gradient(135deg, var(--bg-card) 0%, #1f1f1f 100%);
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 25px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .chart-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, var(--accent), var(--primary));
        }

        .chart-container:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(255, 107, 53, 0.1);
        }

        .chart-container h2 {
            color: var(--secondary);
            font-size: 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 600;
        }

        canvas {
            width: 100% !important;
            height: 350px !important;
        }

        /* Enhanced Status Indicators */
        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-online { background: var(--success); }
        .status-warning { background: var(--warning); }
        .status-error { background: var(--danger); }

        /* Enhanced Buttons */
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: var(--bg-dark);
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 255, 65, 0.3);
        }

        .settings-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: var(--bg-dark);
            border: none; 
            border-radius: 50%;
            width: 60px;
            height: 60px;
            font-size: 24px;
            cursor: pointer; 
            box-shadow: 0 4px 20px rgba(0, 255, 65, 0.3);
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .settings-btn:hover {
            transform: scale(1.1) rotate(45deg);
            box-shadow: 0 8px 30px rgba(0, 255, 65, 0.5);
        }

        /* Enhanced Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.85);
            backdrop-filter: blur(5px);
            z-index: 2000;
            animation: fadeIn 0.3s ease;
        }

        .modal-content {
            background: linear-gradient(135deg, var(--bg-card) 0%, #1f1f1f 100%);
            border: 2px solid var(--border);
            border-radius: 12px;
            padding: 30px;
            width: 90%;
            max-width: 500px;
            margin: 50px auto;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
            animation: slideIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        /* Enhanced Form Elements */
        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block; 
            margin-bottom: 8px;
            color: var(--text);
            font-weight: 600;
        }

        .form-group input {
            width: 100%;
            padding: 12px;
            background: var(--bg-dark);
            border: 2px solid var(--border);
            color: var(--text);
            border-radius: 6px;
            transition: all 0.3s ease;
        }

        .form-group input:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(0, 255, 65, 0.1);
        }

        /* Enhanced Responsive Design */
        @media (max-width: 1200px) {
            .sidebar { width: 280px; }
            .main-content { margin-left: 280px; }
        }

        @media (max-width: 768px) {
            body { flex-direction: column; }
            .sidebar { 
                width: 100%;
                height: auto;
                position: relative;
                padding: 20px;
            }
            .main-content {
                margin-left: 0;
                padding: 20px;
            }
            .summary-stats {
                grid-template-columns: 1fr;
            }
            .charts-section {
                grid-template-columns: 1fr;
            }
            .analysis-grid {
                grid-template-columns: 1fr;
            }
        }

        /* Loading Animation */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid var(--border);
            border-radius: 50%;
            border-top-color: var(--primary);
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* Alert Messages */
        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 6px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .alert-success {
            background: rgba(0, 255, 65, 0.1);
            color: var(--success);
            border: 1px solid var(--success);
        }

        .alert-error {
            background: rgba(255, 71, 87, 0.1);
            color: var(--danger);
            border: 1px solid var(--danger);
        }

        .close-modal {
            background: none;
            border: none;
            color: var(--text);
            font-size: 24px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .close-modal:hover {
            color: var(--danger);
            transform: scale(1.1);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid var(--border);
        }

        .modal-header h2 {
            color: var(--primary);
            font-size: 22px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
    </style>
</head>
<body>
    <!-- Enhanced Sidebar -->
    <div class="sidebar">
        <h1><i class="fas fa-chart-line"></i> SSA Analytics</h1>
        
        <div class="system-info">
            <!-- System Status -->
            <div class="info-card">
                <h3><i class="fas fa-server"></i> System Status</h3>
                <div class="info-value">
                    <span class="status-indicator status-online"></span>
                    Online - PHP <?php echo $systemInfo['php_version']; ?>
                </div>
                <div style="font-size: 12px; color: var(--text-muted); margin-top: 5px;">
                    Server: <?php echo htmlspecialchars($systemInfo['server_software']); ?>
                </div>
                <div style="font-size: 12px; color: var(--text-muted);">
                    Timezone: <?php echo $systemInfo['timezone']; ?>
                </div>
            </div>

            <!-- Disk Usage -->
            <div class="info-card">
                <h3><i class="fas fa-hdd"></i> Storage Usage</h3>
                <div class="info-value">
                    <?php echo round($systemInfo['disk']['used'] / 1024 / 1024 / 1024, 2); ?>GB / 
                    <?php echo round($systemInfo['disk']['total'] / 1024 / 1024 / 1024, 2); ?>GB
                </div>
                <div class="progress-bar">
                    <div class="progress-bar-fill" style="width: <?php echo $systemInfo['disk']['usage_percent']; ?>%"></div>
                </div>
                <div style="font-size: 12px; color: var(--text-muted); margin-top: 5px;">
                    <?php echo $systemInfo['disk']['usage_percent']; ?>% used
                </div>
            </div>

            <!-- Memory Usage -->
            <div class="info-card">
                <h3><i class="fas fa-memory"></i> Memory Info</h3>
                <div class="info-value">
                    <?php echo round($systemInfo['memory']['usage'] / 1024 / 1024, 2); ?>MB
                </div>
                <div class="progress-bar">
                    <div class="progress-bar-fill" style="width: <?php echo round(($systemInfo['memory']['usage'] / $systemInfo['memory']['peak']) * 100, 2); ?>%"></div>
                </div>
                <div style="font-size: 12px; color: var(--text-muted); margin-top: 5px;">
                    Peak: <?php echo round($systemInfo['memory']['peak'] / 1024 / 1024, 2); ?>MB
                </div>
            </div>

            <!-- Network Info -->
            <div class="info-card">
                <h3><i class="fas fa-network-wired"></i> Network</h3>
                <div class="info-value">
                    <?php echo $systemInfo['network']['server_ip']; ?>:<?php echo $systemInfo['network']['server_port']; ?>
                </div>
                <div style="font-size: 12px; color: var(--text-muted); margin-top: 5px;">
                    Client: <?php echo $systemInfo['network']['client_ip']; ?>
                </div>
            </div>

            <!-- API Credits -->
            <div class="info-card">
                <h3><i class="fas fa-shield-alt"></i> API Credits</h3>
                <div class="info-value">
                    <?php 
                    if (isset($apiCredits['error'])) {
                        echo '<span class="status-indicator status-error"></span>';
                        echo '<div style="color: var(--danger); font-size: 14px;">' . htmlspecialchars($apiCredits['error']) . '</div>';
                    } else {
                        echo '<span class="status-indicator status-online"></span>';
                        echo number_format($apiCredits['remaining']) . ' remaining';
                        echo '<div class="progress-bar" style="margin-top: 10px;">';
                        echo '<div class="progress-bar-fill" style="width: ' . (100 - $apiCredits['percent_used']) . '%"></div>';
                        echo '</div>';
                        echo '<div style="font-size: 12px; color: var(--text-muted); margin-top: 5px;">';
                        echo 'Used: ' . number_format($apiCredits['used']) . ' / ' . number_format($apiCredits['total']);
                        echo '</div>';
                    }
                    ?>
                </div>
            </div>

            <!-- Server Load (if available) -->
            <?php if ($systemInfo['uptime']): ?>
            <div class="info-card">
                <h3><i class="fas fa-tachometer-alt"></i> Server Load</h3>
                <div class="info-value">
                    <?php echo round($systemInfo['uptime']['load_1min'], 2); ?>
                </div>
                <div style="font-size: 12px; color: var(--text-muted); margin-top: 5px;">
                    1min: <?php echo round($systemInfo['uptime']['load_1min'], 2); ?> | 
                    5min: <?php echo round($systemInfo['uptime']['load_5min'], 2); ?> | 
                    15min: <?php echo round($systemInfo['uptime']['load_15min'], 2); ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Enhanced Main Content -->
    <div class="main-content">
        <!-- Enhanced Summary Stats -->
        <div class="summary-stats">
            <div class="stat-card">
                <h3><i class="fas fa-users"></i> Total Visits</h3>
                <div class="stat-value" id="totalVisits"><?php echo number_format($stats['visits']['total']); ?></div>
                <div class="stat-change">↑ <?php echo number_format($stats['visits']['last7d']); ?> this week</div>
            </div>
            <div class="stat-card">
                <h3><i class="fas fa-user-friends"></i> Unique Visitors</h3>
                <div class="stat-value" id="uniqueVisits"><?php echo number_format($stats['visits']['unique']); ?></div>
                <div class="stat-change">↑ <?php echo number_format($stats['visits']['last24h']); ?> today</div>
            </div>
            <div class="stat-card">
                <h3><i class="fas fa-download"></i> Downloads</h3>
                <div class="stat-value"><?php echo number_format($stats['downloads']['total']); ?></div>
                <div class="stat-change">↑ <?php echo number_format($stats['downloads']['last24h']); ?> today</div>
            </div>
            <div class="stat-card">
                <h3><i class="fas fa-robot"></i> Bot Activity</h3>
                <div class="stat-value"><?php echo number_format($stats['bots']['total']); ?></div>
                <div class="stat-change">↑ <?php echo number_format($stats['bots']['last24h']); ?> today</div>
            </div>
        </div>

        <!-- Enhanced Analytics Grid -->
        <div class="analysis-grid">
            <!-- Top Locations -->
            <div class="analysis-card">
                <h3><i class="fas fa-globe-americas"></i> Top Locations</h3>
                <?php if (!empty($stats['visits']['top_locations'])): ?>
                <ul class="analysis-list">
                    <?php foreach (array_slice($stats['visits']['top_locations'], 0, 8) as $location => $count): ?>
                    <li>
                        <span><i class="fas fa-map-marker-alt" style="color: var(--accent); margin-right: 8px;"></i><?php echo htmlspecialchars($location); ?></span>
                        <span class="analysis-value"><?php echo number_format($count); ?></span>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php else: ?>
                <p style="color: var(--text-muted); text-align: center; padding: 20px;">No location data available</p>
                <?php endif; ?>
            </div>

            <!-- Top ISPs -->
            <div class="analysis-card">
                <h3><i class="fas fa-building"></i> Top ISP Providers</h3>
                <?php if (!empty($stats['visits']['top_isps'])): ?>
                <ul class="analysis-list">
                    <?php foreach (array_slice($stats['visits']['top_isps'], 0, 8) as $isp => $count): ?>
                    <li>
                        <span><i class="fas fa-wifi" style="color: var(--secondary); margin-right: 8px;"></i><?php echo htmlspecialchars($isp); ?></span>
                        <span class="analysis-value"><?php echo number_format($count); ?></span>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php else: ?>
                <p style="color: var(--text-muted); text-align: center; padding: 20px;">No ISP data available</p>
                <?php endif; ?>
            </div>

            <!-- Operating Systems -->
            <div class="analysis-card">
                <h3><i class="fas fa-laptop-code"></i> Operating Systems</h3>
                <?php if (!empty($stats['visits']['top_os'])): ?>
                <ul class="analysis-list">
                    <?php foreach (array_slice($stats['visits']['top_os'], 0, 8) as $os => $count): ?>
                    <li>
                        <span><i class="fab fa-<?php echo strtolower(substr($os, 0, 7)) === 'windows' ? 'windows' : (strtolower(substr($os, 0, 5)) === 'linux' ? 'linux' : (strtolower(substr($os, 0, 3)) === 'mac' ? 'apple' : 'desktop')); ?>" style="color: var(--info); margin-right: 8px;"></i><?php echo htmlspecialchars($os); ?></span>
                        <span class="analysis-value"><?php echo number_format($count); ?></span>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php else: ?>
                <p style="color: var(--text-muted); text-align: center; padding: 20px;">No OS data available</p>
                <?php endif; ?>
            </div>

            <!-- User Behavior Analysis -->
            <div class="analysis-card">
                <h3><i class="fas fa-chart-pie"></i> User Behavior</h3>
                <ul class="analysis-list">
                    <li>
                        <span><i class="fas fa-percentage" style="color: var(--success); margin-right: 8px;"></i>Conversion Rate</span>
                        <span class="analysis-value"><?php echo number_format($stats['behavior']['conversion_rate'], 2); ?>%</span>
                    </li>
                    <li>
                        <span><i class="fas fa-undo" style="color: var(--warning); margin-right: 8px;"></i>Bounce Rate</span>
                        <span class="analysis-value"><?php echo number_format($stats['behavior']['bounce_rate'], 2); ?>%</span>
                    </li>
                    <li>
                        <span><i class="fas fa-clock" style="color: var(--info); margin-right: 8px;"></i>Avg. Session</span>
                        <span class="analysis-value"><?php echo gmdate('i:s', $stats['behavior']['avg_session_duration']); ?></span>
                    </li>
                    <li>
                        <span><i class="fas fa-users" style="color: var(--primary); margin-right: 8px;"></i>Repeat Visitors</span>
                        <span class="analysis-value"><?php echo number_format($stats['behavior']['repeat_visitors']); ?></span>
                    </li>
                </ul>
            </div>

            <!-- Bot Analysis -->
            <div class="analysis-card">
                <h3><i class="fas fa-robot"></i> Security Analysis</h3>
                <ul class="analysis-list">
                    <li>
                        <span><i class="fas fa-exclamation-triangle" style="color: var(--danger); margin-right: 8px;"></i>Suspicious IPs</span>
                        <span class="analysis-value"><?php echo count($stats['bots']['patterns']['suspicious_ips']); ?></span>
                    </li>
                    <li>
                        <span><i class="fas fa-bolt" style="color: var(--warning); margin-right: 8px;"></i>High Frequency</span>
                        <span class="analysis-value"><?php echo count($stats['bots']['patterns']['high_frequency']); ?></span>
                    </li>
                    <li>
                        <span><i class="fas fa-shield-alt" style="color: var(--info); margin-right: 8px;"></i>Blocked Attempts</span>
                        <span class="analysis-value"><?php echo number_format($stats['bots']['patterns']['malicious_attempts']); ?></span>
                    </li>
                    <li>
                        <span><i class="fas fa-eye" style="color: var(--primary); margin-right: 8px;"></i>Total Bots</span>
                        <span class="analysis-value"><?php echo number_format($stats['bots']['total']); ?></span>
                    </li>
                </ul>
            </div>

            <!-- Time Distribution -->
            <div class="analysis-card">
                <h3><i class="fas fa-clock"></i> Activity Patterns</h3>
                <ul class="analysis-list">
                    <?php 
                    $periods = [
                        'morning' => ['icon' => 'sun', 'label' => 'Morning (6-12)'],
                        'afternoon' => ['icon' => 'cloud-sun', 'label' => 'Afternoon (12-18)'],
                        'evening' => ['icon' => 'moon', 'label' => 'Evening (18-24)'],
                        'night' => ['icon' => 'star', 'label' => 'Night (0-6)']
                    ];
                    foreach ($periods as $period => $info): 
                        $data = $stats['visits']['time_patterns'][$period];
                    ?>
                    <li>
                        <span><i class="fas fa-<?php echo $info['icon']; ?>" style="color: var(--accent); margin-right: 8px;"></i><?php echo $info['label']; ?></span>
                        <span class="analysis-value"><?php echo number_format($data['count']); ?> (<?php echo $data['percentage']; ?>%)</span>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>

        <!-- Enhanced Charts Section -->
        <div class="charts-section">
            <div class="chart-container">
                <h2><i class="fas fa-chart-bar"></i> Weekly Activity Distribution</h2>
                <canvas id="dailyChart"></canvas>
            </div>
            <div class="chart-container">
                <h2><i class="fas fa-chart-line"></i> 24-Hour Activity Pattern</h2>
                <canvas id="hourlyChart"></canvas>
            </div>
        </div>

        <div class="charts-section">
            <div class="chart-container">
                <h2><i class="fas fa-chart-pie"></i> Time Distribution Analysis</h2>
                <canvas id="timeDistributionChart"></canvas>
            </div>
            <div class="chart-container">
                <h2><i class="fas fa-shield-alt"></i> Security Monitoring</h2>
                <canvas id="botActivityChart"></canvas>
            </div>
        </div>
    </div>

    <!-- Enhanced Settings Button -->
    <button class="settings-btn" onclick="openSettings()" title="Dashboard Settings">
        <i class="fas fa-cog"></i>
    </button>

    <!-- Enhanced Settings Modal -->
    <div id="settingsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2><i class="fas fa-cog"></i> Dashboard Settings</h2>
                <button class="close-modal" onclick="closeSettings()">&times;</button>
            </div>
            
            <?php if (isset($_GET['settings_updated'])): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i> Settings saved successfully!
            </div>
            <?php endif; ?>
            
            <?php if (isset($error)): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?>
            </div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <input type="hidden" name="action" value="update_settings">
                <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                
                <div class="form-group">
                    <label for="IPDETECTIVE_API_KEY">
                        <i class="fas fa-key"></i> IPDetective API Key
                    </label>
                    <input type="text" id="IPDETECTIVE_API_KEY" name="IPDETECTIVE_API_KEY" 
                           value="<?php echo htmlspecialchars(defined('IPDETECTIVE_API_KEY') ? IPDETECTIVE_API_KEY : ''); ?>"
                           placeholder="Enter your IPDetective API key">
                </div>

                <div class="form-group">
                    <label for="telegram_bot_token">
                        <i class="fab fa-telegram"></i> Telegram Bot Token
                    </label>
                    <input type="text" id="telegram_bot_token" name="telegram_bot_token" 
                           value="<?php echo htmlspecialchars(defined('TELEGRAM_BOT_TOKEN') ? TELEGRAM_BOT_TOKEN : ''); ?>"
                           placeholder="Enter your Telegram bot token">
                </div>

                <div class="form-group">
                    <label for="telegram_chat_id">
                        <i class="fas fa-comments"></i> Telegram Chat ID
                    </label>
                    <input type="text" id="telegram_chat_id" name="telegram_chat_id" 
                           value="<?php echo htmlspecialchars(defined('TELEGRAM_CHAT_ID') ? TELEGRAM_CHAT_ID : ''); ?>"
                           placeholder="Enter your Telegram chat ID">
                </div>

                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> Save Settings
                </button>
            </form>
        </div>
    </div>

    <script>
        // Enhanced Chart Configuration
        const chartConfig = {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    labels: { color: '#e0e0e0', font: { size: 12 } }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: { color: 'rgba(255, 255, 255, 0.1)' },
                    ticks: { color: '#e0e0e0', font: { size: 11 } }
                },
                x: {
                    grid: { color: 'rgba(255, 255, 255, 0.1)' },
                    ticks: { color: '#e0e0e0', font: { size: 11 } }
                }
            }
        };

        // Initialize Enhanced Charts
        function initCharts(data) {
            // Daily Activity Chart
            new Chart(document.getElementById('dailyChart'), {
                type: 'bar',
                data: {
                    labels: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
                    datasets: [{
                        label: 'Visits',
                        data: data.visits.daily,
                        backgroundColor: 'rgba(0, 255, 65, 0.2)',
                        borderColor: '#00ff41',
                        borderWidth: 2,
                        borderRadius: 4
                    }, {
                        label: 'Downloads',
                        data: data.downloads.daily,
                        backgroundColor: 'rgba(0, 212, 255, 0.2)',
                        borderColor: '#00d4ff',
                        borderWidth: 2,
                        borderRadius: 4
                    }]
                },
                options: {
                    ...chartConfig,
                    scales: {
                        ...chartConfig.scales,
                        x: {
                            ...chartConfig.scales.x,
                            ticks: {
                                ...chartConfig.scales.x.ticks,
                                maxRotation: 45
                            }
                        }
                    }
                }
            });

            // Hourly Activity Chart
            new Chart(document.getElementById('hourlyChart'), {
                type: 'line',
                data: {
                    labels: Array.from({length: 24}, (_, i) => `${i}:00`),
                    datasets: [{
                        label: 'Visits',
                        data: data.visits.hourly,
                        borderColor: '#00ff41',
                        backgroundColor: 'rgba(0, 255, 65, 0.1)',
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: '#00ff41',
                        pointBorderWidth: 2,
                        pointRadius: 3
                    }, {
                        label: 'Downloads',
                        data: data.downloads.hourly,
                        borderColor: '#00d4ff',
                        backgroundColor: 'rgba(0, 212, 255, 0.1)',
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: '#00d4ff',
                        pointBorderWidth: 2,
                        pointRadius: 3
                    }]
                },
                options: {
                    ...chartConfig,
                    scales: {
                        ...chartConfig.scales,
                        x: {
                            ...chartConfig.scales.x,
                            ticks: {
                                ...chartConfig.scales.x.ticks,
                                callback: function(value, index) {
                                    return index % 2 === 0 ? `${index}:00` : '';
                                }
                            }
                        }
                    }
                }
            });

            // Time Distribution Chart
            new Chart(document.getElementById('timeDistributionChart'), {
                type: 'doughnut',
                data: {
                    labels: ['Morning (6-12)', 'Afternoon (12-18)', 'Evening (18-24)', 'Night (0-6)'],
                    datasets: [{
                        data: [
                            data.visits.time_patterns.morning.count,
                            data.visits.time_patterns.afternoon.count,
                            data.visits.time_patterns.evening.count,
                            data.visits.time_patterns.night.count
                        ],
                        backgroundColor: [
                            'rgba(255, 206, 86, 0.8)',
                            'rgba(54, 162, 235, 0.8)',
                            'rgba(255, 99, 132, 0.8)',
                            'rgba(75, 192, 192, 0.8)'
                        ],
                        borderColor: [
                            'rgba(255, 206, 86, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 99, 132, 1)',
                            'rgba(75, 192, 192, 1)'
                        ],
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: { 
                                color: '#e0e0e0',
                                font: { size: 12 },
                                usePointStyle: true,
                                padding: 20
                            }
                        }
                    }
                }
            });

            // Bot Activity Chart
            new Chart(document.getElementById('botActivityChart'), {
                type: 'bar',
                data: {
                    labels: ['Morning', 'Afternoon', 'Evening', 'Night'],
                    datasets: [{
                        label: 'Bot Activity',
                        data: [
                            data.bots.patterns.time_patterns.morning,
                            data.bots.patterns.time_patterns.afternoon,
                            data.bots.patterns.time_patterns.evening,
                            data.bots.patterns.time_patterns.night
                        ],
                        backgroundColor: 'rgba(255, 107, 53, 0.2)',
                        borderColor: '#ff6b35',
                        borderWidth: 2,
                        borderRadius: 4
                    }]
                },
                options: chartConfig
            });
        }

        // Enhanced Settings Modal Functions
        function openSettings() {
            document.getElementById('settingsModal').style.display = 'block';
            document.body.style.overflow = 'hidden';
        }

        function closeSettings() {
            document.getElementById('settingsModal').style.display = 'none';
            document.body.style.overflow = 'auto';
        }

        // Enhanced Data Refresh Function
        function refreshData() {
            fetch('?ajax=1')
                .then(response => response.json())
                .then(data => {
                    // Update main stats
                    document.getElementById('totalVisits').textContent = 
                        new Intl.NumberFormat().format(data.stats.visits.total);
                    document.getElementById('uniqueVisits').textContent = 
                        new Intl.NumberFormat().format(data.stats.visits.unique);
                    
                    console.log('Dashboard data refreshed at:', new Date().toLocaleTimeString());
                })
                .catch(error => {
                    console.error('Error refreshing data:', error);
                });
        }

        // Event Listeners
        document.addEventListener('DOMContentLoaded', () => {
            // Initialize charts
            initCharts(<?php echo json_encode($stats); ?>);
            
            // Setup modal close on outside click
            window.onclick = function(event) {
                const modal = document.getElementById('settingsModal');
                if (event.target === modal) {
                    closeSettings();
                }
            };
            
            // Setup keyboard shortcuts
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape') closeSettings();
                if (e.ctrlKey && e.key === 'r') {
                    e.preventDefault();
                    refreshData();
                }
            });
        });

        // Auto-refresh every 60 seconds
        setInterval(refreshData, 60000);

        // Add loading indicator for form submission
        document.querySelector('form').addEventListener('submit', function() {
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<div class="loading"></div> Saving...';
            submitBtn.disabled = true;
        });
    </script>
</body>
</html>