<?php
// config.php - AI Security Platform Configuration (SQLite Version)
// Powered by: Gemini AI + VirusTotal + WPScan
// Copyright © 2026 Christopher Khayere. All rights reserved.

session_start();

// Use SQLite - No MySQL setup required!
define('DB_FILE', __DIR__ . '/security.db');

// ============================================
// AI Configuration - Google Gemini (Primary)
// ============================================
define('GEMINI_API_KEY', 'AIzaSyB_qZZcp3BKM0_6889bdjD6htziWU1iNHk');
define('GEMINI_MODEL', 'gemini-2.0-flash');
define('GEMINI_URL', 'https://generativelanguage.googleapis.com/v1beta/models/' . GEMINI_MODEL . ':generateContent');

// ============================================
// VirusTotal API Configuration
// ============================================
define('VIRUSTOTAL_API_KEY', '8296f68f690f157d19e2fadc0bc2e1bc36c3d547f38c192f304454b6e43fe54f');
define('VIRUSTOTAL_URL', 'https://www.virustotal.com/api/v3');
define('VIRUSTOTAL_ENABLED', true);

// ============================================
// WPScan API Configuration
// ============================================
define('WPSCAN_API_KEY', 's7fk2wOKvtW5TZPOiPauYMonsCvx5V1UqH0uUisooG0');
define('WPSCAN_URL', 'https://wpscan.com/api/v3');
define('WPSCAN_ENABLED', true);

// ============================================
// API Rate Limiting & Cache Settings
// ============================================
define('AI_RATE_LIMIT', 3.5);        // Seconds between Gemini calls
define('VT_RATE_LIMIT', 15);         // Seconds between VirusTotal calls (free tier: 4/min)
define('WPSCAN_RATE_LIMIT', 5);      // Seconds between WPScan calls
define('AI_CACHE_ENABLED', true);
define('AI_CACHE_DIR', __DIR__ . '/cache');
define('AI_CACHE_TTL_SECURITY', 3600);    // 1 hour for security tips
define('AI_CACHE_TTL_ANALYSIS', 1800);    // 30 min for analysis
define('AI_CACHE_TTL_VT', 86400);         // 24 hours for VirusTotal results
define('AI_CACHE_TTL_WPSCAN', 43200);     // 12 hours for WPScan results

// ============================================
// Application Settings
// ============================================
define('APP_NAME', 'AI Security Platform');
define('APP_VERSION', '3.0.0');
define('COPYRIGHT', 'Christopher Khayere');

// ============================================
// Database Connection
// ============================================
function getDBConnection() {
    static $pdo = null;
    
    if ($pdo !== null) {
        return $pdo;
    }
    
    try {
        $pdo = new PDO("sqlite:" . DB_FILE);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        $pdo->exec("PRAGMA journal_mode=WAL");
        $pdo->exec("PRAGMA synchronous=NORMAL");
        $pdo->exec("PRAGMA foreign_keys = ON");
        $pdo->exec("PRAGMA cache_size = -8000");
        
        // Users table
        $pdo->exec("CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE NOT NULL,
            password_hash TEXT NOT NULL,
            email TEXT,
            is_admin INTEGER DEFAULT 0,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )");
        
        // Attack logs
        $pdo->exec("CREATE TABLE IF NOT EXISTS attack_logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
            attacker_ip TEXT,
            target_url TEXT,
            attack_type TEXT,
            payload TEXT,
            result TEXT,
            severity TEXT,
            user_agent TEXT
        )");
        
        // Defense logs
        $pdo->exec("CREATE TABLE IF NOT EXISTS defense_logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
            defender_ip TEXT,
            target_url TEXT,
            defense_type TEXT,
            findings TEXT,
            recommendations TEXT,
            risk_score INTEGER
        )");
        
        // Malware/VirusTotal logs
        $pdo->exec("CREATE TABLE IF NOT EXISTS malware_logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
            file_hash TEXT,
            file_name TEXT,
            virus_total_report TEXT,
            ai_analysis TEXT,
            malicious_count INTEGER,
            total_engines INTEGER,
            threat_label TEXT,
            file_type TEXT,
            file_size INTEGER
        )");
        
        // WPScan logs
        $pdo->exec("CREATE TABLE IF NOT EXISTS wpscan_logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
            target_url TEXT,
            wordpress_version TEXT,
            vulnerabilities_found INTEGER,
            wpscan_data TEXT,
            ai_analysis TEXT,
            theme_vulns INTEGER,
            plugin_vulns INTEGER
        )");
        
        // AI injection logs
        $pdo->exec("CREATE TABLE IF NOT EXISTS ai_injection_logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
            attacker_ip TEXT,
            target_ai_endpoint TEXT,
            injection_prompt TEXT,
            ai_response TEXT,
            success INTEGER
        )");
        
        // System settings
        $pdo->exec("CREATE TABLE IF NOT EXISTS system_settings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            setting_key TEXT UNIQUE,
            setting_value TEXT,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )");
        
        // Scan results
        $pdo->exec("CREATE TABLE IF NOT EXISTS scan_results (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            scan_date DATETIME DEFAULT CURRENT_TIMESTAMP,
            target_url TEXT,
            scan_type TEXT,
            vulnerabilities_found INTEGER,
            scan_data TEXT,
            ai_confidence REAL,
            fingerprint TEXT,
            deep_scan INTEGER DEFAULT 0,
            ai_provider TEXT DEFAULT 'gemini',
            vt_results TEXT,
            wpscan_results TEXT
        )");
        
        // API cache table
        $pdo->exec("CREATE TABLE IF NOT EXISTS api_cache (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            cache_key TEXT UNIQUE,
            api_type TEXT,
            response_data TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            expires_at DATETIME
        )");
        
        // Insert default admin user
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = 'admin'");
        $stmt->execute();
        if ($stmt->fetchColumn() == 0) {
            $adminHash = hash('sha256', 'Admin@2026');
            $stmt = $pdo->prepare("INSERT INTO users (username, password_hash, email, is_admin) VALUES ('admin', ?, 'admin@security.local', 1)");
            $stmt->execute([$adminHash]);
        }
        
        // Insert default settings
        $defaultSettings = [
            'virustotal_api_key' => VIRUSTOTAL_API_KEY,
            'wpscan_api_key' => WPSCAN_API_KEY,
            'gemini_api_key' => GEMINI_API_KEY,
            'ai_provider' => 'gemini',
            'scan_timeout' => '30',
            'max_scan_depth' => '3',
            'enable_ai_attacks' => '1',
            'enable_virustotal' => '1',
            'enable_wpscan' => '1',
            'log_all_attacks' => '1'
        ];
        
        foreach ($defaultSettings as $key => $value) {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM system_settings WHERE setting_key = ?");
            $stmt->execute([$key]);
            if ($stmt->fetchColumn() == 0) {
                $stmt = $pdo->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES (?, ?)");
                $stmt->execute([$key, $value]);
            }
        }
        
        return $pdo;
        
    } catch (PDOException $e) {
        die("Database Error: " . $e->getMessage());
    }
}

// ============================================
// API Cache System
// ============================================
function getAPICache($cacheKey, $apiType) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT response_data FROM api_cache WHERE cache_key = ? AND api_type = ? AND expires_at > datetime('now')");
        $stmt->execute([$cacheKey, $apiType]);
        $result = $stmt->fetch();
        return $result ? json_decode($result['response_data'], true) : false;
    } catch (Exception $e) {
        return false;
    }
}

function setAPICache($cacheKey, $apiType, $data, $ttl = 1800) {
    try {
        $pdo = getDBConnection();
        $expires = date('Y-m-d H:i:s', time() + $ttl);
        $stmt = $pdo->prepare("INSERT OR REPLACE INTO api_cache (cache_key, api_type, response_data, created_at, expires_at) VALUES (?, ?, ?, datetime('now'), ?)");
        $stmt->execute([$cacheKey, $apiType, json_encode($data), $expires]);
        
        // Cleanup old cache occasionally
        if (rand(1, 20) === 1) {
            $pdo->exec("DELETE FROM api_cache WHERE expires_at < datetime('now')");
        }
    } catch (Exception $e) {}
}

// Also cache to file system for speed
function getFileCache($key) {
    if (!is_dir(AI_CACHE_DIR)) {
        @mkdir(AI_CACHE_DIR, 0755, true);
    }
    $file = AI_CACHE_DIR . '/' . md5($key) . '.cache';
    if (file_exists($file)) {
        $data = @json_decode(file_get_contents($file), true);
        if ($data && isset($data['expires']) && time() < $data['expires']) {
            return $data['response'];
        }
        @unlink($file);
    }
    return false;
}

function setFileCache($key, $response, $ttl = 1800) {
    if (!is_dir(AI_CACHE_DIR)) {
        @mkdir(AI_CACHE_DIR, 0755, true);
    }
    $file = AI_CACHE_DIR . '/' . md5($key) . '.cache';
    @file_put_contents($file, json_encode([
        'expires' => time() + $ttl,
        'response' => $response
    ]));
}

// ============================================
// Gemini AI API Call (Optimized)
// ============================================
function callGeminiAI($prompt, $systemContext = "You are a cybersecurity expert AI assistant.") {
    static $lastCallTime = 0;
    
    // Rate limiting
    $elapsed = microtime(true) - $lastCallTime;
    if ($elapsed < AI_RATE_LIMIT) {
        usleep(intval((AI_RATE_LIMIT - $elapsed) * 1000000));
    }
    
    // Check cache
    $cacheKey = 'gemini_' . md5($prompt . $systemContext);
    $cached = getFileCache($cacheKey);
    if ($cached !== false) {
        return $cached;
    }
    
    $data = [
        'contents' => [
            ['parts' => [['text' => $systemContext . "\n\n" . $prompt]]]
        ],
        'generationConfig' => [
            'temperature' => 0.3,
            'maxOutputTokens' => 1024,
            'topP' => 0.8,
            'topK' => 20
        ],
        'safetySettings' => [
            ['category' => 'HARM_CATEGORY_HARASSMENT', 'threshold' => 'BLOCK_NONE'],
            ['category' => 'HARM_CATEGORY_HATE_SPEECH', 'threshold' => 'BLOCK_NONE'],
            ['category' => 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'threshold' => 'BLOCK_NONE'],
            ['category' => 'HARM_CATEGORY_DANGEROUS_CONTENT', 'threshold' => 'BLOCK_NONE']
        ]
    ];
    
    $ch = curl_init(GEMINI_URL . '?key=' . GEMINI_API_KEY);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_TIMEOUT => 15,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    $lastCallTime = microtime(true);
    
    if ($curlError) {
        error_log("Gemini cURL Error: " . $curlError);
        return "GEMINI_ERROR: Connection failed";
    }
    
    if ($httpCode == 200) {
        $result = json_decode($response, true);
        if (isset($result['candidates'][0]['content']['parts'][0]['text'])) {
            $text = trim($result['candidates'][0]['content']['parts'][0]['text']);
            setFileCache($cacheKey, $text, AI_CACHE_TTL_ANALYSIS);
            return $text;
        }
    }
    
    if ($httpCode == 429) {
        sleep(5);
        return "GEMINI_ERROR: Rate limited";
    }
    
    error_log("Gemini HTTP {$httpCode}: " . substr($response, 0, 200));
    return "GEMINI_ERROR: HTTP {$httpCode}";
}

// ============================================
// Unified AI Call
// ============================================
function callAI($prompt, $systemPrompt = "You are a cybersecurity expert AI assistant.") {
    return callGeminiAI($prompt, $systemPrompt);
}

// ============================================
// VirusTotal API Integration
// ============================================
function scanFileVirusTotal($filePath) {
    if (!VIRUSTOTAL_ENABLED) return ['error' => 'VirusTotal disabled'];
    
    $cacheKey = 'vt_file_' . md5_file($filePath);
    $cached = getAPICache($cacheKey, 'virustotal');
    if ($cached) return $cached;
    
    // Upload file
    $ch = curl_init(VIRUSTOTAL_URL . '/files');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ['x-apikey: ' . VIRUSTOTAL_API_KEY],
        CURLOPT_POSTFIELDS => ['file' => new CURLFile($filePath)],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode == 200) {
        $data = json_decode($response, true);
        $analysisId = $data['data']['id'] ?? '';
        
        // Wait and get analysis
        if ($analysisId) {
            sleep(5);
            return getVirusTotalAnalysis($analysisId);
        }
    }
    
    return ['error' => "Upload failed: HTTP {$httpCode}"];
}

function getVirusTotalAnalysis($analysisId) {
    $cacheKey = 'vt_analysis_' . $analysisId;
    $cached = getAPICache($cacheKey, 'virustotal');
    if ($cached) return $cached;
    
    $ch = curl_init(VIRUSTOTAL_URL . '/analyses/' . $analysisId);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ['x-apikey: ' . VIRUSTOTAL_API_KEY],
        CURLOPT_TIMEOUT => 20,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode == 200) {
        $data = json_decode($response, true);
        $result = [
            'malicious' => $data['data']['attributes']['stats']['malicious'] ?? 0,
            'suspicious' => $data['data']['attributes']['stats']['suspicious'] ?? 0,
            'harmless' => $data['data']['attributes']['stats']['harmless'] ?? 0,
            'undetected' => $data['data']['attributes']['stats']['undetected'] ?? 0,
            'total' => count($data['data']['attributes']['results'] ?? []),
            'threat_names' => []
        ];
        
        // Extract threat names
        foreach ($data['data']['attributes']['results'] ?? [] as $engine => $result_data) {
            if (!empty($result_data['result'])) {
                $result['threat_names'][] = $engine . ': ' . $result_data['result'];
            }
        }
        
        setAPICache($cacheKey, 'virustotal', $result, AI_CACHE_TTL_VT);
        return $result;
    }
    
    return ['error' => "Analysis failed: HTTP {$httpCode}"];
}

function getVirusTotalFileReport($fileHash) {
    if (!VIRUSTOTAL_ENABLED) return ['error' => 'VirusTotal disabled'];
    
    $cacheKey = 'vt_hash_' . $fileHash;
    $cached = getAPICache($cacheKey, 'virustotal');
    if ($cached) return $cached;
    
    $ch = curl_init(VIRUSTOTAL_URL . '/files/' . $fileHash);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ['x-apikey: ' . VIRUSTOTAL_API_KEY],
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode == 200) {
        $data = json_decode($response, true);
        $result = [
            'found' => true,
            'malicious' => $data['data']['attributes']['last_analysis_stats']['malicious'] ?? 0,
            'suspicious' => $data['data']['attributes']['last_analysis_stats']['suspicious'] ?? 0,
            'harmless' => $data['data']['attributes']['last_analysis_stats']['harmless'] ?? 0,
            'total' => count($data['data']['attributes']['last_analysis_results'] ?? []),
            'threat_label' => $data['data']['attributes']['popular_threat_classification']['suggested_threat_label'] ?? 'Unknown',
            'file_type' => $data['data']['attributes']['type_description'] ?? 'Unknown',
            'file_size' => $data['data']['attributes']['size'] ?? 0,
            'first_seen' => $data['data']['attributes']['first_submission_date'] ?? null,
            'threat_names' => []
        ];
        
        foreach ($data['data']['attributes']['last_analysis_results'] ?? [] as $engine => $r) {
            if (!empty($r['result'])) {
                $result['threat_names'][] = $engine . ': ' . $r['result'];
            }
        }
        
        setAPICache($cacheKey, 'virustotal', $result, AI_CACHE_TTL_VT);
        return $result;
    }
    
    if ($httpCode == 404) {
        return ['found' => false, 'message' => 'File not found in VirusTotal database'];
    }
    
    return ['error' => "Lookup failed: HTTP {$httpCode}"];
}

// ============================================
// WPScan API Integration
// ============================================
function scanWordPressSite($targetUrl) {
    if (!WPSCAN_ENABLED) return ['error' => 'WPScan disabled'];
    
    // Extract domain from URL
    $parsed = parse_url($targetUrl);
    $domain = $parsed['host'] ?? str_replace(['http://', 'https://'], '', $targetUrl);
    
    $cacheKey = 'wpscan_' . md5($domain);
    $cached = getAPICache($cacheKey, 'wpscan');
    if ($cached) return $cached;
    
    // First check if it's WordPress
    $response = curlGet($targetUrl);
    $isWordPress = (stripos($response, 'wp-content') !== false || 
                    stripos($response, 'wp-includes') !== false ||
                    stripos($response, 'wordpress') !== false);
    
    if (!$isWordPress) {
        return ['is_wordpress' => false, 'message' => 'Not a WordPress site'];
    }
    
    // Get WordPress version from page source
    $wpVersion = 'Unknown';
    if (preg_match('/WordPress\s+([\d.]+)/i', $response, $m)) {
        $wpVersion = $m[1];
    } elseif (preg_match('/\?ver=([\d.]+)/i', $response, $m)) {
        $wpVersion = $m[1];
    }
    
    // Check common WordPress REST API for version
    $apiResponse = curlGet($targetUrl . '/wp-json/wp/v2/');
    $apiVersion = '';
    if ($apiResponse) {
        $apiData = json_decode($apiResponse, true);
        // Version may be in headers or namespace
    }
    
    // WPScan API - Get vulnerability data via domain lookup
    $ch = curl_init(WPSCAN_URL . '/wordpresses?url=' . urlencode($domain));
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Token token=' . WPSCAN_API_KEY,
            'Accept: application/json'
        ],
        CURLOPT_TIMEOUT => 20,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    $apiResponse = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    $result = [
        'is_wordpress' => true,
        'version' => $wpVersion,
        'vulnerabilities' => [],
        'total_vulnerabilities' => 0,
        'theme_vulnerabilities' => [],
        'plugin_vulnerabilities' => []
    ];
    
    if ($httpCode == 200) {
        $data = json_decode($apiResponse, true);
        
        // Process WordPress core vulnerabilities
        if (isset($data[0]['vulnerabilities'])) {
            foreach ($data[0]['vulnerabilities'] as $vuln) {
                $result['vulnerabilities'][] = [
                    'title' => $vuln['title'] ?? 'Unknown',
                    'cve' => $vuln['references']['cve'][0] ?? 'N/A',
                    'severity' => $vuln['severity'] ?? 'Unknown',
                    'fixed_in' => $vuln['fixed_in'] ?? 'N/A',
                    'published' => $vuln['published_date'] ?? 'Unknown'
                ];
            }
            $result['total_vulnerabilities'] = count($data[0]['vulnerabilities']);
        }
    }
    
    // Detect common WordPress plugins
    $knownPlugins = [
        'woocommerce', 'yoast-seo', 'elementor', 'contact-form-7',
        'jetpack', 'wordfence', 'wpforms', 'all-in-one-seo-pack',
        'updraftplus', 'wp-super-cache', 'w3-total-cache', 'akismet'
    ];
    
    foreach ($knownPlugins as $plugin) {
        if (stripos($response, '/plugins/' . $plugin) !== false) {
            $result['plugins_found'][] = $plugin;
        }
    }
    
    // Detect theme
    if (preg_match('/\/themes\/([^\/]+)\//i', $response, $m)) {
        $result['theme'] = $m[1];
    }
    
    setAPICache($cacheKey, 'wpscan', $result, AI_CACHE_TTL_WPSCAN);
    return $result;
}

function getWordPressVulnerabilityDetails($wpId) {
    $cacheKey = 'wpscan_id_' . $wpId;
    $cached = getAPICache($cacheKey, 'wpscan');
    if ($cached) return $cached;
    
    $ch = curl_init(WPSCAN_URL . '/wordpresses/' . $wpId);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Token token=' . WPSCAN_API_KEY,
            'Accept: application/json'
        ],
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode == 200) {
        $data = json_decode($response, true);
        setAPICache($cacheKey, 'wpscan', $data, AI_CACHE_TTL_WPSCAN);
        return $data;
    }
    
    return ['error' => "WPScan API error: HTTP {$httpCode}"];
}

// ============================================
// Helper: Simple cURL GET
// ============================================
function curlGet($url) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 3,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0 SecurityScanner/3.0'
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

// ============================================
// Settings Management
// ============================================
function getSetting($key) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        return isset($result['setting_value']) ? $result['setting_value'] : '';
    } catch (Exception $e) {
        return '';
    }
}

function updateSetting($key, $value) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("UPDATE system_settings SET setting_value = ?, updated_at = CURRENT_TIMESTAMP WHERE setting_key = ?");
        $stmt->execute([$value, $key]);
        return true;
    } catch (Exception $e) {
        return false;
    }
}

// ============================================
// Authentication
// ============================================
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function isAdmin() {
    return isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1;
}

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: index.php?error=login_required');
        exit;
    }
}

function requireAdmin() {
    requireLogin();
    if (!isAdmin()) {
        header('Location: index.php?error=unauthorized');
        exit;
    }
}

// ============================================
// Logging Functions
// ============================================
function logAttack($targetUrl, $attackType, $payload, $result, $severity = 'Medium') {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("INSERT INTO attack_logs (attacker_ip, target_url, attack_type, payload, result, severity, user_agent) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',
            $targetUrl, $attackType,
            is_array($payload) ? json_encode($payload) : $payload,
            is_array($result) ? json_encode($result) : $result, $severity,
            isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''
        ]);
    } catch (Exception $e) {}
}

function logDefense($targetUrl, $defenseType, $findings, $recommendations, $riskScore) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("INSERT INTO defense_logs (defender_ip, target_url, defense_type, findings, recommendations, risk_score) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',
            $targetUrl, $defenseType,
            is_array($findings) ? json_encode($findings) : $findings,
            is_array($recommendations) ? json_encode($recommendations) : $recommendations,
            $riskScore
        ]);
    } catch (Exception $e) {}
}

function logMalwareAnalysis($fileHash, $fileName, $vtReport, $aiAnalysis, $maliciousCount, $totalEngines) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("INSERT INTO malware_logs (file_hash, file_name, virus_total_report, ai_analysis, malicious_count, total_engines) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $fileHash, $fileName,
            is_array($vtReport) ? json_encode($vtReport) : $vtReport,
            $aiAnalysis, $maliciousCount, $totalEngines
        ]);
    } catch (Exception $e) {}
}

function logWPScan($targetUrl, $wpVersion, $vulnCount, $data, $aiAnalysis) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("INSERT INTO wpscan_logs (target_url, wordpress_version, vulnerabilities_found, wpscan_data, ai_analysis) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$targetUrl, $wpVersion, $vulnCount, json_encode($data), $aiAnalysis]);
    } catch (Exception $e) {}
}

function logScanResult($targetUrl, $scanType, $vulnerabilities, $aiConfidence, $fingerprint, $deepScan = false, $vtData = null, $wpData = null) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("INSERT INTO scan_results (target_url, scan_type, vulnerabilities_found, scan_data, ai_confidence, fingerprint, deep_scan, ai_provider, vt_results, wpscan_results) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $targetUrl, $scanType, count($vulnerabilities),
            json_encode($vulnerabilities), $aiConfidence, json_encode($fingerprint),
            $deepScan ? 1 : 0, 'gemini',
            $vtData ? json_encode($vtData) : null,
            $wpData ? json_encode($wpData) : null
        ]);
    } catch (Exception $e) {}
}

// ============================================
// Helper Functions
// ============================================
function getScanHistory($limit = 10) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT * FROM scan_results ORDER BY scan_date DESC LIMIT ?");
        $stmt->execute([$limit]);
        return $stmt->fetchAll();
    } catch (Exception $e) {
        return [];
    }
}

function getAttackStats() {
    try {
        $pdo = getDBConnection();
        return [
            'total_attacks' => $pdo->query("SELECT COUNT(*) FROM attack_logs")->fetchColumn(),
            'by_severity' => $pdo->query("SELECT severity, COUNT(*) as count FROM attack_logs GROUP BY severity")->fetchAll(),
            'recent_targets' => $pdo->query("SELECT DISTINCT target_url FROM attack_logs ORDER BY id DESC LIMIT 5")->fetchAll()
        ];
    } catch (Exception $e) {
        return ['total_attacks' => 0, 'by_severity' => [], 'recent_targets' => []];
    }
}

function formatReport($data, $title) {
    return "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>{$title}</title><style>body{font-family:Arial;margin:40px;line-height:1.6}.header{border-bottom:2px solid #333;margin-bottom:30px;text-align:center}.critical{color:#dc3545}.high{color:#fd7e14}.medium{color:#ffc107}.low{color:#28a745}table{width:100%;border-collapse:collapse}th,td{border:1px solid #ddd;padding:8px}th{background:#f2f2f2}</style></head><body><div class='header'><h1>{$title}</h1><p>" . APP_NAME . " | Powered by Gemini AI + VirusTotal + WPScan | " . date('Y-m-d H:i:s') . "</p></div>{$data}</body></html>";
}

function cleanAIResponse($response) {
    $response = preg_replace('/```json\s*/', '', $response);
    $response = preg_replace('/```\s*/', '', $response);
    $response = trim($response);
    if (preg_match('/\{.*\}|\[.*\]/s', $response, $matches)) return $matches[0];
    return $response;
}

// ============================================
// Initialize
// ============================================
try {
    getDBConnection();
} catch (Exception $e) {}

if (AI_CACHE_ENABLED && !is_dir(AI_CACHE_DIR)) {
    @mkdir(AI_CACHE_DIR, 0755, true);
}

if (!headers_sent()) {
    header('X-Frame-Options: DENY');
    header('X-Content-Type-Options: nosniff');
    header('X-XSS-Protection: 1; mode=block');
}
?>