<?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);
define('VT_RATE_LIMIT', 15);
define('WPSCAN_RATE_LIMIT', 5);
define('AI_CACHE_ENABLED', true);
define('AI_CACHE_DIR', __DIR__ . '/cache');
define('AI_CACHE_TTL_SECURITY', 3600);
define('AI_CACHE_TTL_ANALYSIS', 1800);
define('AI_CACHE_TTL_VT', 86400);
define('AI_CACHE_TTL_WPSCAN', 43200);

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

// ============================================
// Helper Functions
// ============================================

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 getTheme() {
    if (isset($_COOKIE['soulguard_theme'])) {
        return $_COOKIE['soulguard_theme'];
    }
    $theme = getSetting('theme');
    return $theme ? $theme : 'dark';
}

// ============================================
// Database Connection with Full Schema
// ============================================
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 - Complete with all columns
        // ============================================
        $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 UNIQUE,
            full_name TEXT,
            phone TEXT,
            organization_id INTEGER,
            is_admin INTEGER DEFAULT 0,
            is_active INTEGER DEFAULT 0,
            activation_token TEXT,
            reset_token TEXT,
            reset_expires DATETIME,
            last_login DATETIME,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )");
        
        // Check and add missing columns to users table (for existing databases)
        $columns = $pdo->query("PRAGMA table_info(users)")->fetchAll(PDO::FETCH_COLUMN, 1);
        
        $requiredColumns = [
            'full_name' => 'TEXT',
            'phone' => 'TEXT',
            'organization_id' => 'INTEGER',
            'is_active' => 'INTEGER DEFAULT 0',
            'activation_token' => 'TEXT',
            'reset_token' => 'TEXT',
            'reset_expires' => 'DATETIME',
            'last_login' => 'DATETIME',
            'updated_at' => 'DATETIME DEFAULT CURRENT_TIMESTAMP'
        ];
        
        foreach ($requiredColumns as $col => $type) {
            if (!in_array($col, $columns)) {
                try {
                    $pdo->exec("ALTER TABLE users ADD COLUMN $col $type");
                } catch (Exception $e) {
                    // Column might already exist, ignore error
                }
            }
        }
        
        // ============================================
        // ORGANIZATIONS TABLE
        // ============================================
        $pdo->exec("CREATE TABLE IF NOT EXISTS organizations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            website TEXT,
            industry TEXT,
            size TEXT,
            address TEXT,
            phone TEXT,
            email TEXT,
            registration_number TEXT,
            tax_id TEXT,
            created_by INTEGER,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
        )");
        
        // ============================================
        // USER SESSIONS TABLE
        // ============================================
        $pdo->exec("CREATE TABLE IF NOT EXISTS user_sessions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER,
            session_token TEXT UNIQUE NOT NULL,
            ip_address TEXT,
            user_agent TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            expires_at DATETIME,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )");
        
        // ============================================
        // USER ACTIVITY TABLE
        // ============================================
        $pdo->exec("CREATE TABLE IF NOT EXISTS user_activity (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER,
            action TEXT,
            details TEXT,
            ip_address TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )");
        
        // ============================================
        // EXISTING TABLES
        // ============================================
        
        $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
        )");
        
        $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
        )");
        
        $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
        )");
        
        $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
        )");
        
        $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
        )");
        
        $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
        )");
        
        $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
        )");
        
        $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
        )");
        
        // ============================================
        // DPA TABLES
        // ============================================
        
        $pdo->exec("CREATE TABLE IF NOT EXISTS dpa_assessments (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER,
            company_name TEXT NOT NULL,
            company_website TEXT,
            company_industry TEXT,
            company_size TEXT,
            assessment_date DATETIME DEFAULT CURRENT_TIMESTAMP,
            assessor_name TEXT,
            risk_score REAL,
            risk_level TEXT,
            compliance_percent FLOAT,
            total_questions INTEGER,
            answered_questions INTEGER,
            responses TEXT,
            recommendations TEXT,
            category_scores TEXT,
            report_ref TEXT UNIQUE,
            report_html TEXT,
            website_scan TEXT,
            verified INTEGER DEFAULT 0,
            completed INTEGER DEFAULT 0
        )");
        
        $pdo->exec("CREATE TABLE IF NOT EXISTS dpa_questions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            category TEXT NOT NULL,
            question TEXT NOT NULL,
            guidance TEXT,
            weight REAL DEFAULT 1.0,
            kenya_dpa_reference TEXT,
            sort_order INTEGER
        )");
        
        $pdo->exec("CREATE TABLE IF NOT EXISTS dpa_recommendations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            risk_level TEXT,
            category TEXT,
            priority TEXT,
            recommendation TEXT NOT NULL,
            timeframe TEXT,
            legal_reference TEXT,
            penalty_risk TEXT
        )");
        
        $pdo->exec("CREATE TABLE IF NOT EXISTS website_scan_cache (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            domain TEXT UNIQUE,
            scan_data TEXT,
            scan_date DATETIME DEFAULT CURRENT_TIMESTAMP
        )");
        
        // ============================================
        // INSERT DEFAULT DATA
        // ============================================
        
        // Insert default admin user
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = 'admin'");
        $stmt->execute();
        if ($stmt->fetchColumn() == 0) {
            $adminHash = password_hash('Admin@2026', PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, password_hash, email, full_name, is_admin, is_active) VALUES ('admin', ?, 'admin@security.local', 'System Administrator', 1, 1)");
            $stmt->execute([$adminHash]);
        } else {
            // Ensure admin is active and has required fields
            $pdo->exec("UPDATE users SET is_active = 1, full_name = 'System Administrator' WHERE username = 'admin'");
        }
        
        // 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',
            'theme' => 'dark'
        ];
        
        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());
    }
}

// ============================================
// MEMBER FUNCTIONS
// ============================================

function registerUser($username, $email, $password, $fullName = '', $phone = '') {
    try {
        $pdo = getDBConnection();
        
        // Check if username or email exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
        $stmt->execute([$username, $email]);
        if ($stmt->fetch()) {
            return ['success' => false, 'message' => 'Username or email already exists'];
        }
        
        // Hash password
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);
        
        // Generate activation token
        $activationToken = bin2hex(random_bytes(32));
        
        // Insert user
        $stmt = $pdo->prepare("INSERT INTO users (username, email, password_hash, full_name, phone, is_active, activation_token) VALUES (?, ?, ?, ?, ?, 0, ?)");
        $stmt->execute([$username, $email, $passwordHash, $fullName, $phone, $activationToken]);
        
        $userId = $pdo->lastInsertId();
        
        return ['success' => true, 'message' => 'Registration successful. Please wait for admin activation.', 'user_id' => $userId];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Registration failed: ' . $e->getMessage()];
    }
}

function loginUser($email, $password, $remember = false) {
    try {
        $pdo = getDBConnection();
        
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if (!$user) {
            return ['success' => false, 'message' => 'Invalid email or password'];
        }
        
        // Check if account is active
        if (!isset($user['is_active']) || $user['is_active'] != 1) {
            return ['success' => false, 'message' => 'Account not activated. Please contact administrator.'];
        }
        
        if (!password_verify($password, $user['password_hash'])) {
            return ['success' => false, 'message' => 'Invalid email or password'];
        }
        
        // Update last login
        $stmt = $pdo->prepare("UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->execute([$user['id']]);
        
        // Create session
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['email'] = $user['email'];
        $_SESSION['full_name'] = $user['full_name'] ?? $user['username'];
        $_SESSION['is_admin'] = $user['is_admin'] ?? 0;
        $_SESSION['organization_id'] = $user['organization_id'] ?? null;
        
        // Remember me
        if ($remember) {
            $sessionToken = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', time() + 30 * 24 * 3600);
            
            $stmt = $pdo->prepare("INSERT INTO user_sessions (user_id, session_token, ip_address, user_agent, expires_at) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$user['id'], $sessionToken, $_SERVER['REMOTE_ADDR'] ?? '', $_SERVER['HTTP_USER_AGENT'] ?? '', $expires]);
            
            setcookie('soulguard_session', $sessionToken, time() + 30 * 24 * 3600, '/', '', false, true);
        }
        
        return ['success' => true, 'message' => 'Login successful', 'user' => $user];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Login failed: ' . $e->getMessage()];
    }
}

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

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

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: member/login.php');
        exit;
    }
}

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

function logUserActivity($userId, $action, $details = '') {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("INSERT INTO user_activity (user_id, action, details, ip_address) VALUES (?, ?, ?, ?)");
        $stmt->execute([$userId, $action, $details, $_SERVER['REMOTE_ADDR'] ?? '']);
    } catch (Exception $e) {}
}

function getUserById($userId) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        return $stmt->fetch();
    } catch (Exception $e) {
        return null;
    }
}

function updateUserProfile($userId, $data) {
    try {
        $pdo = getDBConnection();
        $fields = [];
        $params = [];
        
        $allowedFields = ['full_name', 'phone', 'email'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $fields[] = "$field = ?";
                $params[] = $data[$field];
            }
        }
        
        if (empty($fields)) {
            return false;
        }
        
        $params[] = $userId;
        $stmt = $pdo->prepare("UPDATE users SET " . implode(', ', $fields) . ", updated_at = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->execute($params);
        
        return true;
    } catch (Exception $e) {
        return false;
    }
}

function changePassword($userId, $currentPassword, $newPassword) {
    try {
        $pdo = getDBConnection();
        
        $stmt = $pdo->prepare("SELECT password_hash FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        
        if (!password_verify($currentPassword, $user['password_hash'])) {
            return ['success' => false, 'message' => 'Current password is incorrect'];
        }
        
        $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->execute([$newHash, $userId]);
        
        return ['success' => true, 'message' => 'Password changed successfully'];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Password change failed'];
    }
}

function getUserOrganization($userId) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("
            SELECT o.* FROM organizations o 
            JOIN users u ON u.organization_id = o.id 
            WHERE u.id = ?
        ");
        $stmt->execute([$userId]);
        return $stmt->fetch();
    } catch (Exception $e) {
        return null;
    }
}

function createOrganization($userId, $data) {
    try {
        $pdo = getDBConnection();
        
        $stmt = $pdo->prepare("INSERT INTO organizations (name, website, industry, size, address, phone, email, registration_number, tax_id, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $data['name'] ?? '',
            $data['website'] ?? '',
            $data['industry'] ?? '',
            $data['size'] ?? '',
            $data['address'] ?? '',
            $data['phone'] ?? '',
            $data['email'] ?? '',
            $data['registration_number'] ?? '',
            $data['tax_id'] ?? '',
            $userId
        ]);
        
        $orgId = $pdo->lastInsertId();
        
        // Update user's organization
        $stmt = $pdo->prepare("UPDATE users SET organization_id = ? WHERE id = ?");
        $stmt->execute([$orgId, $userId]);
        
        $_SESSION['organization_id'] = $orgId;
        
        return $orgId;
        
    } catch (Exception $e) {
        return false;
    }
}

function updateOrganization($userId, $orgId, $data) {
    try {
        $pdo = getDBConnection();
        
        $fields = [];
        $params = [];
        $allowedFields = ['name', 'website', 'industry', 'size', 'address', 'phone', 'email', 'registration_number', 'tax_id'];
        
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $fields[] = "$field = ?";
                $params[] = $data[$field];
            }
        }
        
        if (empty($fields)) {
            return false;
        }
        
        $params[] = $orgId;
        $stmt = $pdo->prepare("UPDATE organizations SET " . implode(', ', $fields) . ", updated_at = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->execute($params);
        
        return true;
        
    } catch (Exception $e) {
        return false;
    }
}

function getDashboardStats($userId) {
    try {
        $pdo = getDBConnection();
        
        $stats = [];
        
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM scan_results");
        $stmt->execute();
        $stats['total_scans'] = $stmt->fetchColumn();
        
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM attack_logs");
        $stmt->execute();
        $stats['total_attacks'] = $stmt->fetchColumn();
        
        return $stats;
        
    } catch (Exception $e) {
        return ['total_scans' => 0, 'total_attacks' => 0];
    }
}

function getUserActivity($userId, $limit = 10) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT * FROM user_activity WHERE user_id = ? ORDER BY created_at DESC LIMIT ?");
        $stmt->execute([$userId, $limit]);
        return $stmt->fetchAll();
    } catch (Exception $e) {
        return [];
    }
}

function activateUser($userId) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("UPDATE users SET is_active = 1, activation_token = NULL WHERE id = ?");
        $stmt->execute([$userId]);
        return true;
    } catch (Exception $e) {
        return false;
    }
}

function deactivateUser($userId) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("UPDATE users SET is_active = 0 WHERE id = ? AND is_admin = 0");
        $stmt->execute([$userId]);
        return true;
    } catch (Exception $e) {
        return false;
    }
}

function getAllUsers() {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->query("SELECT u.*, o.name as organization_name FROM users u LEFT JOIN organizations o ON u.organization_id = o.id ORDER BY u.created_at DESC");
        return $stmt->fetchAll();
    } catch (Exception $e) {
        return [];
    }
}

// ============================================
// REST OF YOUR ORIGINAL FUNCTIONS
// ============================================

// 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]);
        if (rand(1, 20) === 1) {
            $pdo->exec("DELETE FROM api_cache WHERE expires_at < datetime('now')");
        }
    } catch (Exception $e) {}
}

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
    ]));
}

function callGeminiAI($prompt, $systemContext = "You are a cybersecurity expert AI assistant.") {
    static $lastCallTime = 0;
    
    $elapsed = microtime(true) - $lastCallTime;
    if ($elapsed < AI_RATE_LIMIT) {
        usleep(intval((AI_RATE_LIMIT - $elapsed) * 1000000));
    }
    
    $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
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    $lastCallTime = microtime(true);
    
    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;
        }
    }
    
    return "GEMINI_ERROR: Unable to get response";
}

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

// ============================================
// 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');
}
?>