<?php
// config.php - Soul Guard Configuration
// 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);

// ============================================
// Application Settings
// ============================================
define('APP_NAME', 'Soul Guard');
define('APP_VERSION', '4.0.0');
define('COPYRIGHT', 'Christopher Khayere');

// ============================================
// Helper Functions (must be defined BEFORE getDBConnection)
// ============================================

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'];
    }
    return getSetting('theme');
}

// ============================================
// 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 with member fields
        $pdo->exec("CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE NOT NULL,
            email TEXT UNIQUE NOT NULL,
            password_hash TEXT NOT NULL,
            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
        )");
        
        // 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)
        )");
        
        // User sessions
        $pdo->exec("CREATE TABLE IF NOT EXISTS user_sessions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER,
            session_token TEXT UNIQUE,
            ip_address TEXT,
            user_agent TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            expires_at DATETIME,
            FOREIGN KEY (user_id) REFERENCES users(id)
        )");
        
        // User activity logs
        $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)
        )");
        
        // ============================================
        // Existing tables from your config
        // ============================================
        
        // 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
        )");
        
        // ============================================
        // DPA Assessment 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,
            FOREIGN KEY (user_id) REFERENCES users(id)
        )");
        
        $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,
            security_headers TEXT,
            ssl_info TEXT,
            privacy_findings TEXT,
            cookies TEXT
        )");
        
        // ============================================
        // 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, email, password_hash, full_name, is_admin, is_active) VALUES ('admin', 'admin@soulguard.com', ?, 'System Administrator', 1, 1)");
            $stmt->execute([$adminHash]);
        }
        
        // Insert default DPA questions if empty
        $count = $pdo->query("SELECT COUNT(*) FROM dpa_questions")->fetchColumn();
        if ($count == 0) {
            insertDefaultDPAQuestions($pdo);
        }
        
        // Insert default DPA recommendations if empty
        $count = $pdo->query("SELECT COUNT(*) FROM dpa_recommendations")->fetchColumn();
        if ($count == 0) {
            insertDefaultDPARecommendations($pdo);
        }
        
        // Insert default settings
        $defaultSettings = [
            'site_name' => 'Soul Guard',
            'site_description' => 'AI-Powered Security Platform',
            'maintenance_mode' => '0',
            'allow_registration' => '1',
            'require_activation' => '1',
            'session_timeout' => '7200',
            '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());
    }
}

// ============================================
// Insert Default DPA Questions
// ============================================
function insertDefaultDPAQuestions($pdo) {
    $questions = [
        ['Legal Basis & Lawful Processing','Has your organization identified and documented a lawful basis for every personal data processing activity?','DPA requires at least one of: consent, contract, legal obligation, vital interests, public task, or legitimate interests.',3.0,'Section 30, Kenya DPA 2019',1],
        ['Legal Basis & Lawful Processing','Do you obtain explicit, informed, and freely given consent from data subjects before processing their personal data?','Consent must be specific, informed, and unambiguous. Pre-ticked boxes are not valid consent.',3.0,'Section 32, Kenya DPA 2019',2],
        ['ODPC Registration & Governance','Is your organisation registered as a Data Controller/Processor with the Office of the Data Protection Commissioner (ODPC)?','Registration is mandatory under DPA Section 18. Failure attracts a KES 1,000,000 fine.',4.0,'Section 18, Kenya DPA 2019',3],
        ['ODPC Registration & Governance','Have you appointed a Data Protection Officer (DPO) if required under the DPA?','Public bodies and organisations processing large-scale or special category data must appoint a DPO.',3.0,'Section 24, Kenya DPA 2019',4],
        ['Data Security & Technical Measures','Is personal data encrypted at rest and in transit using industry-standard encryption?','AES-256 for data at rest; TLS 1.2+ for data in transit. Encryption keys must be securely managed.',3.0,'Section 41, Kenya DPA 2019',5],
        ['Data Security & Technical Measures','Do you have a documented, tested Data Breach Response Plan?','Breaches must be reported to ODPC within 72 hours and affected data subjects without undue delay.',3.5,'Section 43, Kenya DPA 2019',6],
        ['Data Subject Rights','Do data subjects have a clear mechanism to access their personal data held by your organization?','Right of access must be fulfilled within 21 days of request. Provide data in a commonly used format.',3.0,'Section 26, Kenya DPA 2019',7],
        ['Privacy Notices & Transparency','Do you have a clear, accessible privacy notice/policy published and made available to data subjects?','Privacy notice must be concise, transparent, intelligible and in plain language.',3.0,'Section 29, Kenya DPA 2019',8],
        ['Data Minimisation & Retention','Do you have a documented data retention schedule with defined retention periods for each data category?','Retention periods must be justified, documented, and communicated to data subjects.',2.5,'Section 25(e), Kenya DPA 2019',9],
        ['Data Processors & Third Parties','Do you have Data Processing Agreements with all third-party processors handling personal data on your behalf?','Written contracts with processors are mandatory. They must only act on documented instructions.',3.0,'Section 46, Kenya DPA 2019',10],
        ['Cross-Border Data Transfers','Do you transfer personal data outside Kenya? If yes, have you ensured adequate safeguards are in place?','International transfers require an adequacy decision or appropriate safeguards (SCCs, BCRs, or explicit consent).',3.0,'Section 48, Kenya DPA 2019',11],
        ['Staff Training & Awareness','Do all staff who handle personal data receive regular data protection training?','Training must be role-specific and repeated at least annually or when significant changes occur.',2.5,'Section 25, Kenya DPA 2019',12],
        ['Website & Digital Compliance','Does your website use HTTPS/TLS encryption for all pages handling personal data?','Unencrypted data transmission is a DPA Section 41 violation. All pages should use HTTPS.',3.0,'Section 41, Kenya DPA 2019',13],
        ['Website & Digital Compliance','Does your website display a comprehensive, DPA-compliant privacy policy?','Privacy policy must be prominently displayed and cover all Section 29 requirements.',3.0,'Section 29, Kenya DPA 2019',14],
        ['Website & Digital Compliance','Does your website have a functional cookie consent mechanism with granular opt-in controls?','Tracking cookies require explicit opt-in consent. Pre-consent cookies are limited to essential only.',2.5,'Section 32, Kenya DPA 2019',15],
    ];
    
    $stmt = $pdo->prepare("INSERT INTO dpa_questions (category, question, guidance, weight, kenya_dpa_reference, sort_order) VALUES (?, ?, ?, ?, ?, ?)");
    foreach ($questions as $q) {
        $stmt->execute($q);
    }
}

// ============================================
// Insert Default DPA Recommendations
// ============================================
function insertDefaultDPARecommendations($pdo) {
    $recs = [
        ['critical,very-high,high','ODPC Registration','immediate','Register as a Data Controller/Processor with the Office of the Data Protection Commissioner (ODPC). Non-registration carries a mandatory KES 1,000,000 fine.','30 days','Section 18, Kenya DPA 2019','KES 1,000,000 fixed penalty'],
        ['critical,very-high,high','Data Breach Response','immediate','Establish and test a Data Breach Response Plan. Breaches must be reported to ODPC within 72 hours.','30 days','Section 43, Kenya DPA 2019','KES 5,000,000 fine'],
        ['critical,very-high','Data Security','immediate','Implement encryption (AES-256 at rest, TLS 1.2+ in transit) immediately.','14 days','Section 41, Kenya DPA 2019','Criminal liability + unlimited civil damages'],
        ['all','Privacy Notice','immediate','Publish a comprehensive privacy policy covering all Section 29 requirements.','30 days','Section 29, Kenya DPA 2019','ODPC enforcement notice'],
        ['critical,very-high,high,moderate','Data Subject Rights','short-term','Implement a Data Subject Rights Management process with documented procedures.','60 days','Section 26-35, Kenya DPA 2019','ODPC complaints + damages'],
    ];
    
    $stmt = $pdo->prepare("INSERT INTO dpa_recommendations (risk_level, category, priority, recommendation, timeframe, legal_reference, penalty_risk) VALUES (?, ?, ?, ?, ?, ?, ?)");
    foreach ($recs as $r) {
        $stmt->execute($r);
    }
}

// ============================================
// Member Authentication 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();
        
        // Log activity
        logUserActivity($userId, 'register', 'User registered successfully');
        
        return ['success' => true, 'message' => 'Registration successful. Please wait for admin activation.', 'activation_token' => $activationToken, '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'];
        }
        
        if ($user['is_active'] != 1) {
            return ['success' => false, 'message' => 'Account not activated. Please contact administrator.'];
        }
        
        if (!password_verify($password, $user['password_hash'])) {
            // Log failed attempt
            logUserActivity($user['id'], 'login_failed', 'Failed login attempt');
            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'];
        $_SESSION['is_admin'] = $user['is_admin'];
        $_SESSION['organization_id'] = $user['organization_id'];
        
        // Create session token for remember me
        if ($remember) {
            $sessionToken = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', time() + 30 * 24 * 3600); // 30 days
            
            $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);
        }
        
        // Log successful login
        logUserActivity($user['id'], 'login', 'User logged in');
        
        return ['success' => true, 'message' => 'Login successful', 'user' => $user];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Login failed: ' . $e->getMessage()];
    }
}

function activateUser($userId) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("UPDATE users SET is_active = 1, activation_token = NULL WHERE id = ?");
        $stmt->execute([$userId]);
        
        logUserActivity($userId, 'activated', 'Account activated by admin');
        
        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]);
        
        logUserActivity($userId, 'deactivated', 'Account deactivated by admin');
        
        return true;
    } catch (Exception $e) {
        return false;
    }
}

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);
        
        // Update session data
        if (isset($data['full_name'])) $_SESSION['full_name'] = $data['full_name'];
        if (isset($data['email'])) $_SESSION['email'] = $data['email'];
        
        logUserActivity($userId, 'profile_update', 'Profile updated');
        
        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]);
        
        logUserActivity($userId, 'password_change', 'Password changed');
        
        return ['success' => true, 'message' => 'Password changed successfully'];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Password change failed'];
    }
}

function updateOrganization($userId, $orgId, $data) {
    try {
        $pdo = getDBConnection();
        
        // Verify user owns this organization or is admin
        $stmt = $pdo->prepare("SELECT id FROM organizations WHERE id = ? AND (created_by = ? OR ? = 1)");
        $stmt->execute([$orgId, $userId, $_SESSION['is_admin'] ?? 0]);
        if (!$stmt->fetch()) {
            return false;
        }
        
        $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);
        
        logUserActivity($userId, 'org_update', 'Organization details updated');
        
        return true;
        
    } catch (Exception $e) {
        return false;
    }
}

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

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;
        
        logUserActivity($userId, 'org_create', 'New organization created');
        
        return $orgId;
        
    } catch (Exception $e) {
        return false;
    }
}

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

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 getAllOrganizations() {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->query("SELECT * FROM organizations ORDER BY created_at DESC");
        return $stmt->fetchAll();
    } catch (Exception $e) {
        return [];
    }
}

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 getUserActivity($userId, $limit = 50) {
    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 requestPasswordReset($email) {
    try {
        $pdo = getDBConnection();
        
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if (!$user) {
            return ['success' => false, 'message' => 'Email not found'];
        }
        
        $resetToken = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', time() + 3600); // 1 hour
        
        $stmt = $pdo->prepare("UPDATE users SET reset_token = ?, reset_expires = ? WHERE id = ?");
        $stmt->execute([$resetToken, $expires, $user['id']]);
        
        logUserActivity($user['id'], 'password_reset_request', 'Password reset requested');
        
        return ['success' => true, 'message' => 'Reset token generated', 'token' => $resetToken];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Reset request failed'];
    }
}

function resetPassword($token, $newPassword) {
    try {
        $pdo = getDBConnection();
        
        $stmt = $pdo->prepare("SELECT id FROM users WHERE reset_token = ? AND reset_expires > CURRENT_TIMESTAMP");
        $stmt->execute([$token]);
        $user = $stmt->fetch();
        
        if (!$user) {
            return ['success' => false, 'message' => 'Invalid or expired reset token'];
        }
        
        $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE users SET password_hash = ?, reset_token = NULL, reset_expires = NULL WHERE id = ?");
        $stmt->execute([$newHash, $user['id']]);
        
        logUserActivity($user['id'], 'password_reset', 'Password reset completed');
        
        return ['success' => true, 'message' => 'Password reset successfully'];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Reset failed'];
    }
}

function getDashboardStats($userId) {
    try {
        $pdo = getDBConnection();
        
        $stats = [];
        
        // DPA assessments count
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM dpa_assessments WHERE user_id = ?");
        $stmt->execute([$userId]);
        $stats['total_assessments'] = $stmt->fetchColumn();
        
        // Latest assessment
        $stmt = $pdo->prepare("SELECT * FROM dpa_assessments WHERE user_id = ? ORDER BY assessment_date DESC LIMIT 1");
        $stmt->execute([$userId]);
        $stats['latest_assessment'] = $stmt->fetch();
        
        // Attack logs count
        $stmt = $pdo->query("SELECT COUNT(*) FROM attack_logs");
        $stats['total_attacks'] = $stmt->fetchColumn();
        
        // Scans count
        $stmt = $pdo->query("SELECT COUNT(*) FROM scan_results");
        $stats['total_scans'] = $stmt->fetchColumn();
        
        return $stats;
        
    } catch (Exception $e) {
        return [];
    }
}

// ============================================
// 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) {
    $cacheDir = __DIR__ . '/cache';
    if (!is_dir($cacheDir)) {
        @mkdir($cacheDir, 0755, true);
    }
    $file = $cacheDir . '/' . 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) {
    $cacheDir = __DIR__ . '/cache';
    if (!is_dir($cacheDir)) {
        @mkdir($cacheDir, 0755, true);
    }
    $file = $cacheDir . '/' . 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;
    $rateLimit = 3.5; // Seconds between calls
    if ($elapsed < $rateLimit) {
        usleep(intval(($rateLimit - $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, 1800); // 30 min cache
            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}";
}

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

// Session check from cookie
function checkSessionCookie() {
    if (isset($_COOKIE['soulguard_session']) && !isset($_SESSION['user_id'])) {
        try {
            $pdo = getDBConnection();
            $token = $_COOKIE['soulguard_session'];
            
            $stmt = $pdo->prepare("SELECT s.*, u.* FROM user_sessions s JOIN users u ON s.user_id = u.id WHERE s.session_token = ? AND s.expires_at > CURRENT_TIMESTAMP AND u.is_active = 1");
            $stmt->execute([$token]);
            $session = $stmt->fetch();
            
            if ($session) {
                $_SESSION['user_id'] = $session['user_id'];
                $_SESSION['username'] = $session['username'];
                $_SESSION['email'] = $session['email'];
                $_SESSION['full_name'] = $session['full_name'];
                $_SESSION['is_admin'] = $session['is_admin'];
                $_SESSION['organization_id'] = $session['organization_id'];
            }
        } catch (Exception $e) {}
    }
}

// Call this at the beginning
checkSessionCookie();

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

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