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

session_start();

// ============================================
// DATABASE CONFIGURATION - SQLite
// ============================================
define('DB_TYPE', 'sqlite');
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');

// ============================================
// Database Connection Function - SQLite
// ============================================
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");
        
        return $pdo;
        
    } catch (PDOException $e) {
        die("Database Connection Error: " . $e->getMessage());
    }
}

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

// ============================================
// USER AUTHENTICATION FUNCTIONS
// ============================================

function loginUser($usernameOrEmail, $password, $remember = false) {
    try {
        $pdo = getDBConnection();
        
        // Check if input is email or username
        if (filter_var($usernameOrEmail, FILTER_VALIDATE_EMAIL)) {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        } else {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        }
        $stmt->execute([$usernameOrEmail]);
        $user = $stmt->fetch();
        
        if (!$user) {
            return ['success' => false, 'message' => 'Invalid username/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 username/email or password'];
        }
        
        // Update last login - SQLite uses CURRENT_TIMESTAMP
        $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: /login.php');
        exit;
    }
}

function requireAdmin() {
    if (!isLoggedIn() || !isAdmin()) {
        header('Location: /login.php?error=Unauthorized+access');
        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;
    }
}

// ============================================
// Admin Functions
// ============================================

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

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

// ============================================
// API Cache Functions - SQLite Compatible
// ============================================

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

// ============================================
// AI Functions
// ============================================

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 Cache Directory
// ============================================
if (AI_CACHE_ENABLED && !is_dir(AI_CACHE_DIR)) {
    @mkdir(AI_CACHE_DIR, 0755, true);
}

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