<?php
// compliance-scoring.php - Soul Guard Compliance Scoring Engine
// SQLite-compatible version with full data entry forms (no AJAX)

require_once '../config.php';
requireLogin();

// Fix: Ensure user_id is properly set
$userId = $_SESSION['user_id'] ?? 0;

// Fallback: get user ID from database using email if session is missing
if ($userId == 0 && isset($_SESSION['email'])) {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$_SESSION['email']]);
    $userRow = $stmt->fetch();
    if ($userRow) {
        $userId = $userRow['id'];
        $_SESSION['user_id'] = $userId;
    }
}

$user = getUserById($userId);
$org = getUserOrganization($userId);
$pdo = getDBConnection();
$theme = getTheme();

// =============================================
// HANDLE FORM SUBMISSIONS (POST requests)
// =============================================

$message = '';
$messageType = '';

// Handle DPO Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    if ($_POST['action'] === 'add_dpo') {
        $dpoName = trim($_POST['dpo_name'] ?? '');
        $dpoEmail = trim($_POST['dpo_email'] ?? '');
        $dpoPhone = trim($_POST['dpo_phone'] ?? '');
        $appointmentDate = $_POST['appointment_date'] ?? date('Y-m-d');
        $dpoType = $_POST['dpo_type'] ?? 'internal';
        $isPublished = isset($_POST['is_published']) ? 1 : 0;
        
        if ($dpoName && $dpoEmail) {
            try {
                // Handle file upload if present
                $uploadPath = null;
                if (isset($_FILES['appointment_letter']) && $_FILES['appointment_letter']['error'] === UPLOAD_ERR_OK) {
                    $uploadDir = '../uploads/dpo/';
                    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
                    $fileName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $_FILES['appointment_letter']['name']);
                    move_uploaded_file($_FILES['appointment_letter']['tmp_name'], $uploadDir . $fileName);
                    $uploadPath = $uploadDir . $fileName;
                }
                
                // SQLite version - check if DPO already exists for this organization
                $stmt = $pdo->prepare("SELECT id FROM organization_dpo WHERE organization_id = ?");
                $stmt->execute([$org['id']]);
                $existing = $stmt->fetch();
                
                if ($existing) {
                    // UPDATE existing record
                    $stmt = $pdo->prepare("
                        UPDATE organization_dpo 
                        SET name = ?, email = ?, phone = ?, appointment_date = ?, 
                            dpo_type = ?, contact_published = ?, appointment_letter_path = ?,
                            status = 'active', updated_at = datetime('now')
                        WHERE organization_id = ?
                    ");
                    $stmt->execute([$dpoName, $dpoEmail, $dpoPhone, $appointmentDate, $dpoType, $isPublished, $uploadPath, $org['id']]);
                } else {
                    // INSERT new record
                    $stmt = $pdo->prepare("
                        INSERT INTO organization_dpo (organization_id, name, email, phone, appointment_date, dpo_type, contact_published, appointment_letter_path, status, created_at, updated_at)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', datetime('now'), datetime('now'))
                    ");
                    $stmt->execute([$org['id'], $dpoName, $dpoEmail, $dpoPhone, $appointmentDate, $dpoType, $isPublished, $uploadPath]);
                }
                
                $message = "DPO information saved successfully!";
                $messageType = "success";
            } catch (Exception $e) {
                $message = "Error saving DPO: " . $e->getMessage();
                $messageType = "error";
            }
        } else {
            $message = "Please provide DPO name and email.";
            $messageType = "error";
        }
    }
    
    // Handle Processor Form Submission
    elseif ($_POST['action'] === 'add_processor') {
        $processorName = trim($_POST['processor_name'] ?? '');
        $serviceType = trim($_POST['service_type'] ?? '');
        $contractStart = $_POST['contract_start'] ?? null;
        $contractEnd = $_POST['contract_end'] ?? null;
        $dataLeavesKenya = isset($_POST['data_leaves_kenya']) ? 1 : 0;
        $transferCountry = trim($_POST['transfer_country'] ?? '');
        $hasDpaClauses = isset($_POST['has_dpa_clauses']) ? 1 : 0;
        
        // Data categories (checkbox array)
        $dataCategories = isset($_POST['data_categories']) ? implode(',', $_POST['data_categories']) : '';
        
        if ($processorName) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO processor_assessments (organization_id, processor_name, service_type, contract_start_date, contract_end_date, data_categories, data_leaves_kenya, transfer_country, contract_has_dpa_clauses, status, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', datetime('now'))
                ");
                $stmt->execute([$org['id'], $processorName, $serviceType, $contractStart, $contractEnd, $dataCategories, $dataLeavesKenya, $transferCountry, $hasDpaClauses]);
                $message = "Data processor added successfully!";
                $messageType = "success";
            } catch (Exception $e) {
                $message = "Error saving processor: " . $e->getMessage();
                $messageType = "error";
            }
        } else {
            $message = "Please provide processor name.";
            $messageType = "error";
        }
    }
    
    // Handle DPIA Form Submission
    elseif ($_POST['action'] === 'add_dpia') {
        $activityName = trim($_POST['activity_name'] ?? '');
        $riskLevel = $_POST['risk_level'] ?? 'medium';
        $riskFindings = trim($_POST['risk_findings'] ?? '');
        $mitigations = trim($_POST['mitigations'] ?? '');
        
        // High-risk indicators
        $riskIndicators = [];
        if (isset($_POST['risk_indicators'])) {
            $riskIndicators = $_POST['risk_indicators'];
        }
        
        if ($activityName) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO dpia_records (organization_id, activity_name, risk_level, risk_indicators, risk_findings, mitigations, assessment_date, status, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, datetime('now'), 'completed', datetime('now'))
                ");
                $stmt->execute([$org['id'], $activityName, $riskLevel, json_encode($riskIndicators), $riskFindings, $mitigations]);
                $message = "DPIA assessment saved successfully!";
                $messageType = "success";
            } catch (Exception $e) {
                $message = "Error saving DPIA: " . $e->getMessage();
                $messageType = "error";
            }
        } else {
            $message = "Please provide activity name.";
            $messageType = "error";
        }
    }
    
    // Handle Breach Report Form Submission
    elseif ($_POST['action'] === 'report_breach') {
        $breachDate = $_POST['breach_date'] ?? date('Y-m-d');
        $discoveryDate = $_POST['discovery_date'] ?? date('Y-m-d');
        $description = trim($_POST['description'] ?? '');
        $affectedCount = (int)($_POST['affected_count'] ?? 0);
        $notifiedOdpc = isset($_POST['notified_odpc']) ? 1 : 0;
        $notifiedSubjects = isset($_POST['notified_subjects']) ? 1 : 0;
        
        if ($description) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO breach_reports (organization_id, breach_date, discovery_date, description, affected_individuals_count, notified_odpc, notified_affected, status, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, 'reported', datetime('now'))
                ");
                $stmt->execute([$org['id'], $breachDate, $discoveryDate, $description, $affectedCount, $notifiedOdpc, $notifiedSubjects]);
                $message = "Breach report submitted. ODPC requires notification within 72 hours.";
                $messageType = "warning";
            } catch (Exception $e) {
                $message = "Error saving breach report: " . $e->getMessage();
                $messageType = "error";
            }
        } else {
            $message = "Please provide breach description.";
            $messageType = "error";
        }
    }
    
    // Handle DSAR Form Submission
    elseif ($_POST['action'] === 'add_dsar') {
        $requestType = $_POST['request_type'] ?? 'access';
        $requesterName = trim($_POST['requester_name'] ?? '');
        $requesterEmail = trim($_POST['requester_email'] ?? '');
        $requestDetails = trim($_POST['request_details'] ?? '');
        $responseDeadline = $_POST['response_deadline'] ?? date('Y-m-d', strtotime('+30 days'));
        
        if ($requesterName && $requesterEmail) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO data_subject_requests (organization_id, request_type, requester_name, requester_email, request_details, status, received_date, response_deadline, created_at)
                    VALUES (?, ?, ?, ?, ?, 'new', datetime('now'), ?, datetime('now'))
                ");
                $stmt->execute([$org['id'], $requestType, $requesterName, $requesterEmail, $requestDetails, $responseDeadline]);
                $message = "Data subject request logged. Deadline for response: " . date('M j, Y', strtotime($responseDeadline));
                $messageType = "success";
            } catch (Exception $e) {
                $message = "Error saving DSAR: " . $e->getMessage();
                $messageType = "error";
            }
        } else {
            $message = "Please provide requester name and email.";
            $messageType = "error";
        }
    }
    
    // Handle Organization Registration Update
    elseif ($_POST['action'] === 'update_registration') {
        $odpcRegNumber = trim($_POST['odpc_reg_number'] ?? '');
        $regDate = $_POST['registration_date'] ?? date('Y-m-d');
        $privacyPolicyUrl = trim($_POST['privacy_policy_url'] ?? '');
        
        try {
            $stmt = $pdo->prepare("
                UPDATE organizations 
                SET odpc_registration_number = ?, odpc_registration_date = ?, privacy_policy_url = ?, updated_at = datetime('now')
                WHERE id = ?
            ");
            $stmt->execute([$odpcRegNumber, $regDate, $privacyPolicyUrl, $org['id']]);
            $message = "Organization registration updated!";
            $messageType = "success";
        } catch (Exception $e) {
            $message = "Error updating registration: " . $e->getMessage();
            $messageType = "error";
        }
    }
    
    // Handle Security Measures Form (SQLite compatible - no ON CONFLICT)
    elseif ($_POST['action'] === 'update_security') {
        $hasEncryption = isset($_POST['has_encryption']) ? 1 : 0;
        $hasMfa = isset($_POST['has_mfa']) ? 1 : 0;
        $hasBackup = isset($_POST['has_backup']) ? 1 : 0;
        $hasAccessControl = isset($_POST['has_access_control']) ? 1 : 0;
        
        try {
            // SQLite version - delete old record first, then insert new
            $pdo->prepare("DELETE FROM security_measures WHERE organization_id = ?")->execute([$org['id']]);
            
            $stmt = $pdo->prepare("
                INSERT INTO security_measures (organization_id, has_encryption, has_mfa, has_backup, has_access_control, assessment_date)
                VALUES (?, ?, ?, ?, ?, datetime('now'))
            ");
            $stmt->execute([$org['id'], $hasEncryption, $hasMfa, $hasBackup, $hasAccessControl]);
            $message = "Security measures updated!";
            $messageType = "success";
        } catch (Exception $e) {
            $message = "Error updating security measures: " . $e->getMessage();
            $messageType = "error";
        }
    }
}

// =============================================
// FETCH ALL DATA FOR DISPLAY
// =============================================

// Get organization basic info
$orgData = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM organizations WHERE id = ?");
    $stmt->execute([$org['id'] ?? 0]);
    $orgData = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
} catch (Exception $e) {}

// Get DPO info
$dpoData = null;
try {
    $stmt = $pdo->prepare("SELECT * FROM organization_dpo WHERE organization_id = ? AND status = 'active' ORDER BY created_at DESC LIMIT 1");
    $stmt->execute([$org['id'] ?? 0]);
    $dpoData = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

// Get processors
$processors = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM processor_assessments WHERE organization_id = ? AND status = 'active' ORDER BY created_at DESC");
    $stmt->execute([$org['id'] ?? 0]);
    $processors = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

// Get DPIAs
$dpiaRecords = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM dpia_records WHERE organization_id = ? ORDER BY assessment_date DESC");
    $stmt->execute([$org['id'] ?? 0]);
    $dpiaRecords = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

// Get breach reports
$breaches = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM breach_reports WHERE organization_id = ? ORDER BY breach_date DESC LIMIT 10");
    $stmt->execute([$org['id'] ?? 0]);
    $breaches = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

// Get DSARs
$dsars = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM data_subject_requests WHERE organization_id = ? ORDER BY received_date DESC LIMIT 10");
    $stmt->execute([$org['id'] ?? 0]);
    $dsars = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

// Get security measures
$securityMeasures = null;
try {
    $stmt = $pdo->prepare("SELECT * FROM security_measures WHERE organization_id = ? ORDER BY assessment_date DESC LIMIT 1");
    $stmt->execute([$org['id'] ?? 0]);
    $securityMeasures = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

// =============================================
// GET FILE RISK ANALYSES - FIXED QUERY
// =============================================
$files = [];
try {
    // First try by user_id
    $stmt = $pdo->prepare("SELECT * FROM file_risk_analyses WHERE user_id = ? ORDER BY created_at DESC LIMIT 10");
    $stmt->execute([$userId]);
    $files = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // If no files found by user_id, try by organization_id
    if (empty($files) && isset($org['id']) && $org['id'] > 0) {
        $stmt = $pdo->prepare("SELECT * FROM file_risk_analyses WHERE organization_id = ? ORDER BY created_at DESC LIMIT 10");
        $stmt->execute([$org['id']]);
        $files = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Debug comment visible in HTML source
    echo "<!-- Files found: " . count($files) . " for user_id: " . $userId . " -->";
    
} catch (Exception $e) {
    error_log("Error fetching files: " . $e->getMessage());
    echo "<!-- Error fetching files: " . $e->getMessage() . " -->";
}

// =============================================
// CALCULATE COMPLIANCE SCORE
// =============================================

$complianceFactors = [
    'pii_risk' => ['score' => 0, 'weight' => 20, 'label' => 'PII Risk Management', 'details' => []],
    'data_subject_rights' => ['score' => 0, 'weight' => 20, 'label' => 'Data Subject Rights', 'details' => []],
    'accountability' => ['score' => 0, 'weight' => 15, 'label' => 'Accountability', 'details' => []],
    'data_security' => ['score' => 0, 'weight' => 15, 'label' => 'Data Security', 'details' => []],
    'dpia_readiness' => ['score' => 0, 'weight' => 10, 'label' => 'DPIA Readiness', 'details' => []],
    'processor_management' => ['score' => 0, 'weight' => 10, 'label' => 'Processor Management', 'details' => []],
    'data_handling' => ['score' => 0, 'weight' => 10, 'label' => 'Data Handling', 'details' => []]
];

// Factor 1: PII Risk (based on file scans)
$piiScore = 70; // Default
$totalRisk = 0;
$riskCount = 0;

if (!empty($files)) {
    foreach ($files as $f) { 
        $riskScore = isset($f['risk_score']) ? (int)$f['risk_score'] : 0;
        $totalRisk += $riskScore;
        $riskCount++;
    }
    
    if ($riskCount > 0) {
        $avgRisk = $totalRisk / $riskCount;
        // Lower risk = higher compliance score
        $piiScore = max(0, min(100, 100 - $avgRisk));
    }
}

$complianceFactors['pii_risk']['score'] = round($piiScore);
$complianceFactors['pii_risk']['details'] = [
    'files_analyzed' => count($files),
    'average_risk' => isset($avgRisk) ? round($avgRisk) . '%' : 'N/A'
];

// Factor 2: Data Subject Rights
$dsrScore = 30;
$dsrDetails = [];
if ($dpoData && $dpoData['contact_published']) { $dsrScore += 20; $dsrDetails['dpo_published'] = true; }
if (!empty($dsars)) { $dsrScore += min(30, count($dsars) * 10); $dsrDetails['dsars_logged'] = count($dsars); }
if (!empty($orgData['privacy_policy_url'])) { $dsrScore += 20; $dsrDetails['has_privacy_policy'] = true; }
$complianceFactors['data_subject_rights']['score'] = min(100, $dsrScore);
$complianceFactors['data_subject_rights']['details'] = $dsrDetails;

// Factor 3: Accountability
$accScore = 20;
$accDetails = [];
if (!empty($orgData['odpc_registration_number'])) { $accScore += 30; $accDetails['odpc_registered'] = true; }
if ($dpoData) { $accScore += 30; $accDetails['dpo_appointed'] = true; }
if (!empty($dpiaRecords)) { $accScore += 20; $accDetails['dpia_count'] = count($dpiaRecords); }
$complianceFactors['accountability']['score'] = min(100, $accScore);
$complianceFactors['accountability']['details'] = $accDetails;

// Factor 4: Data Security
$secScore = 25;
$secDetails = [];
if ($securityMeasures) {
    if ($securityMeasures['has_encryption']) { $secScore += 25; $secDetails['encryption'] = true; }
    if ($securityMeasures['has_mfa']) { $secScore += 25; $secDetails['mfa'] = true; }
    if ($securityMeasures['has_backup']) { $secScore += 15; $secDetails['backup'] = true; }
    if ($securityMeasures['has_access_control']) { $secScore += 15; $secDetails['access_control'] = true; }
}
$complianceFactors['data_security']['score'] = min(100, $secScore);
$complianceFactors['data_security']['details'] = $secDetails;

// Factor 5: DPIA Readiness
$dpiaScore = 0;
if (!empty($dpiaRecords)) {
    $dpiaScore = min(100, 40 + (count($dpiaRecords) * 15));
}
$complianceFactors['dpia_readiness']['score'] = $dpiaScore;
$complianceFactors['dpia_readiness']['details'] = ['dpia_count' => count($dpiaRecords)];

// Factor 6: Processor Management
$procScore = 0;
if (!empty($processors)) {
    $procScore = min(100, 30 + (count($processors) * 15));
}
$complianceFactors['processor_management']['score'] = $procScore;
$complianceFactors['processor_management']['details'] = ['processor_count' => count($processors)];

// Factor 7: Data Handling
$handlingScore = 25;
if (!empty($orgData['retention_policy'])) { $handlingScore += 25; }
if (!empty($dpiaRecords)) { $handlingScore += 25; }
$complianceFactors['data_handling']['score'] = min(100, $handlingScore);

// Calculate overall
$totalWeighted = 0;
$totalWeight = 0;
foreach ($complianceFactors as $factor) {
    $totalWeighted += ($factor['score'] * $factor['weight']);
    $totalWeight += $factor['weight'];
}
$overallScore = $totalWeight > 0 ? round($totalWeighted / $totalWeight) : 0;
$riskLevel = $overallScore >= 70 ? 'Low' : ($overallScore >= 40 ? 'Medium' : 'High');

// =============================================
// DETERMINE WHICH SECTION TO SHOW (view parameter)
// =============================================

$activeView = $_GET['view'] ?? 'dashboard';
$activeForm = $_GET['form'] ?? null;

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Compliance Scoring - Soul Guard</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Inter', sans-serif;
            background: #f1f5f9;
            color: #1e293b;
            line-height: 1.5;
        }
        body.dark { background: #0f172a; color: #e2e8f0; }
        
        .navbar {
            background: #0f3b5c;
            padding: 0 32px;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        body.light .navbar { background: white; border-bottom: 1px solid #e2e8f0; }
        
        .nav-container {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            min-height: 64px;
        }
        .logo h2 { background: linear-gradient(135deg, #fff, #94a3b8); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 22px; }
        body.light .logo h2 { background: linear-gradient(135deg, #0f3b5c, #2c7da0); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        
        .nav-links { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
        .nav-links a {
            color: rgba(255,255,255,0.8);
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 10px;
            font-weight: 500;
            font-size: 14px;
        }
        body.light .nav-links a { color: #1e293b; }
        .nav-links a:hover, .nav-links a.active { background: rgba(255,255,255,0.15); color: white; }
        body.light .nav-links a:hover, body.light .nav-links a.active { background: #0f3b5c; color: white; }
        
        .theme-toggle {
            background: rgba(255,255,255,0.15);
            border: none;
            border-radius: 50%;
            width: 36px;
            height: 36px;
            cursor: pointer;
            font-size: 18px;
        }
        body.light .theme-toggle { background: #f1f5f9; }
        
        .container { max-width: 1400px; margin: 0 auto; padding: 32px; }
        
        .message {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 24px;
        }
        .message-success { background: rgba(16,185,129,0.12); border: 1px solid #10b981; color: #10b981; }
        .message-error { background: rgba(239,68,68,0.12); border: 1px solid #ef4444; color: #ef4444; }
        .message-warning { background: rgba(245,158,11,0.12); border: 1px solid #f59e0b; color: #f59e0b; }
        
        .compliance-header {
            background: linear-gradient(135deg, #0f3b5c, #082c44);
            border-radius: 24px;
            padding: 32px;
            margin-bottom: 32px;
            color: white;
        }
        .score-container { display: flex; align-items: center; gap: 32px; flex-wrap: wrap; }
        .score-circle {
            width: 140px;
            height: 140px;
            border-radius: 50%;
            background: rgba(255,255,255,0.15);
            backdrop-filter: blur(4px);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        .score-number { font-size: 56px; font-weight: 800; }
        .risk-badge { display: inline-block; padding: 6px 16px; border-radius: 30px; font-size: 14px; font-weight: 600; margin-bottom: 16px; }
        .risk-low { background: rgba(16,185,129,0.2); color: #10b981; }
        .risk-medium { background: rgba(245,158,11,0.2); color: #f59e0b; }
        .risk-high { background: rgba(239,68,68,0.2); color: #ef4444; }
        
        .form-card {
            background: white;
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 24px;
            border: 1px solid #e2e8f0;
        }
        body.dark .form-card { background: #1e293b; border-color: #334155; }
        
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 500; font-size: 14px; }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #cbd5e1;
            border-radius: 10px;
            font-family: inherit;
            font-size: 14px;
        }
        body.dark .form-group input, body.dark .form-group select, body.dark .form-group textarea {
            background: #0f172a;
            border-color: #334155;
            color: #e2e8f0;
        }
        
        .checkbox-group { display: flex; flex-wrap: wrap; gap: 16px; margin-top: 8px; }
        .checkbox-group label { display: flex; align-items: center; gap: 8px; font-weight: normal; margin: 0; }
        
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 500;
            font-size: 14px;
            text-decoration: none;
            cursor: pointer;
            border: none;
        }
        .btn-primary { background: #0f3b5c; color: white; }
        .btn-primary:hover { background: #082c44; }
        .btn-success { background: #10b981; color: white; }
        .btn-outline { background: transparent; border: 1px solid #2c7da0; color: #2c7da0; }
        .btn-danger { background: #ef4444; color: white; }
        
        .factors-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 32px;
        }
        .factor-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            border: 1px solid #e2e8f0;
        }
        body.dark .factor-card { background: #1e293b; border-color: #334155; }
        .progress-bar { background: #e2e8f0; height: 8px; border-radius: 4px; overflow: hidden; margin: 12px 0; }
        .progress-fill { height: 100%; border-radius: 4px; transition: width 0.3s; }
        
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 12px 8px; text-align: left; border-bottom: 1px solid #e2e8f0; }
        body.dark .data-table th, body.dark .data-table td { border-bottom-color: #334155; }
        
        .badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }
        .badge-success { background: rgba(16,185,129,0.12); color: #10b981; }
        .badge-warning { background: rgba(245,158,11,0.12); color: #f59e0b; }
        .badge-danger { background: rgba(239,68,68,0.12); color: #ef4444; }
        .badge-info { background: rgba(59,130,246,0.12); color: #3b82f6; }
        
        .action-buttons { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 24px; }
        .action-btn {
            background: #f1f5f9;
            padding: 12px 20px;
            border-radius: 12px;
            text-align: center;
            text-decoration: none;
            color: #1e293b;
            border: 1px solid #e2e8f0;
        }
        body.dark .action-btn { background: #1e293b; color: #e2e8f0; border-color: #334155; }
        
        @media (max-width: 768px) {
            .container { padding: 16px; }
            .nav-links { gap: 4px; }
            .nav-links a { padding: 6px 12px; font-size: 12px; }
        }
    </style>
</head>
<body class="<?php echo $theme; ?>">
    <nav class="navbar">
        <div class="nav-container">
            <div class="logo"><h2><i class="fas fa-shield-alt"></i> Soul Guard</h2></div>
            <div class="nav-links">
                <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
                <a href="compliance-scoring.php?view=dashboard" class="active"><i class="fas fa-chart-line"></i> Compliance</a>
                <a href="compliance-scoring.php?view=reports"><i class="fas fa-file-alt"></i> Reports</a>
                <a href="compliance-scoring.php?view=data"><i class="fas fa-database"></i> My Data</a>
                <a href="organization.php"><i class="fas fa-building"></i> Organization</a>
                <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
                <div class="theme-toggle" onclick="toggleTheme()"><?php echo $theme === 'dark' ? '☀️' : '🌙'; ?></div>
            </div>
        </div>
    </nav>
    
    <div class="container">
        <?php if ($message): ?>
        <div class="message message-<?php echo $messageType; ?>">
            <i class="fas <?php echo $messageType === 'success' ? 'fa-check-circle' : ($messageType === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle'); ?>"></i>
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>
        
        <!-- Quick Action Buttons -->
        <div class="action-buttons">
            <a href="?view=form&form=dpo" class="action-btn"><i class="fas fa-user-tie"></i> Add DPO</a>
            <a href="?view=form&form=processor" class="action-btn"><i class="fas fa-microchip"></i> Add Processor</a>
            <a href="?view=form&form=dpia" class="action-btn"><i class="fas fa-clipboard-list"></i> Complete DPIA</a>
            <a href="?view=form&form=breach" class="action-btn"><i class="fas fa-bug"></i> Report Breach</a>
            <a href="?view=form&form=dsar" class="action-btn"><i class="fas fa-envelope"></i> Log DSAR</a>
            <a href="?view=form&form=security" class="action-btn"><i class="fas fa-lock"></i> Security Measures</a>
            <a href="?view=form&form=registration" class="action-btn"><i class="fas fa-registered"></i> ODPC Registration</a>
            <a href="?view=upload" class="action-btn"><i class="fas fa-file-upload"></i> Upload File</a>
        </div>
        
        <?php if ($activeView === 'dashboard' && !$activeForm): ?>
        <!-- DASHBOARD VIEW -->
        <div class="compliance-header">
            <h1><i class="fas fa-chart-line"></i> DPA 2019 Compliance Dashboard</h1>
            <p>Based on Kenya Data Protection Act, 2019 and ODPC guidelines</p>
            <div class="score-container">
                <div class="score-circle">
                    <div class="score-number"><?php echo $overallScore; ?>%</div>
                    <div class="score-label">Compliance Score</div>
                </div>
                <div class="score-details">
                    <span class="risk-badge risk-<?php echo strtolower($riskLevel); ?>">
                        <?php echo $riskLevel; ?> Risk Level
                    </span>
                    <p style="margin-top: 12px;">
                        <i class="fas fa-info-circle"></i> 
                        Score calculated from 7 compliance factors. 
                        <a href="?view=reports" style="color: white; text-decoration: underline;">View full report →</a>
                    </p>
                </div>
            </div>
        </div>
        
        <div class="factors-grid">
            <?php foreach ($complianceFactors as $key => $factor): 
                $fillColor = $factor['score'] >= 70 ? '#10b981' : ($factor['score'] >= 40 ? '#f59e0b' : '#ef4444');
            ?>
            <div class="factor-card">
                <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                    <strong><?php echo htmlspecialchars($factor['label']); ?></strong>
                    <span style="font-size: 20px; font-weight: 700; color: <?php echo $fillColor; ?>"><?php echo $factor['score']; ?>%</span>
                </div>
                <div class="progress-bar">
                    <div class="progress-fill" style="width: <?php echo $factor['score']; ?>%; background: <?php echo $fillColor; ?>"></div>
                </div>
                <div class="factor-weight" style="font-size: 11px; color: #64748b; margin-top: 8px;">
                    Weight: <?php echo $factor['weight']; ?>%
                </div>
                <?php if (!empty($factor['details'])): ?>
                <div style="font-size: 11px; margin-top: 12px; padding-top: 12px; border-top: 1px solid #e2e8f0; color: #64748b;">
                    <?php foreach ($factor['details'] as $dk => $dv): ?>
                        <?php if (is_bool($dv)): ?>
                            <div><i class="fas <?php echo $dv ? 'fa-check-circle' : 'fa-times-circle'; ?>" style="color: <?php echo $dv ? '#10b981' : '#ef4444'; ?>"></i> <?php echo ucfirst(str_replace('_', ' ', $dk)); ?></div>
                        <?php else: ?>
                            <div><i class="fas fa-chart-simple"></i> <?php echo ucfirst(str_replace('_', ' ', $dk)); ?>: <?php echo $dv; ?></div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Recent File Analyses Section -->
        <div class="form-card">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 10px;">
                <h3><i class="fas fa-shield-virus"></i> Recent PII Risk Analyses</h3>
                <a href="?view=upload" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> New Analysis</a>
            </div>
            
            <?php if (!empty($files)): ?>
            <div style="overflow-x: auto;">
                <table class="data-table">
                    <thead>
                        <tr><th>Filename</th><th>Risk Score</th><th>PII Detected</th><th>Status</th><th>Date</th><th></th>
                        </thead>
                    <tbody>
                        <?php foreach ($files as $file): 
                            $piiTypes = [];
                            if (!empty($file['detected_pii_types'])) {
                                $piiTypes = is_string($file['detected_pii_types']) ? json_decode($file['detected_pii_types'], true) : $file['detected_pii_types'];
                                if (!is_array($piiTypes)) $piiTypes = [];
                            }
                            $riskScore = isset($file['risk_score']) ? (int)$file['risk_score'] : 0;
                            $riskClass = $riskScore >= 60 ? 'risk-high' : ($riskScore >= 30 ? 'risk-medium' : 'risk-low');
                        ?>
                        <tr>
                            <td><?php echo htmlspecialchars(substr($file['original_filename'], 0, 45)); ?><?php echo strlen($file['original_filename']) > 45 ? '...' : ''; ?></td>
                            <td class="<?php echo $riskClass; ?>"><?php echo $riskScore; ?>%</td>
                            <td>
                                <?php if (!empty($piiTypes)): ?>
                                    <?php foreach (array_slice($piiTypes, 0, 2) as $type): ?>
                                        <span class="badge badge-info"><?php echo ucfirst(str_replace('_', ' ', $type)); ?></span>
                                    <?php endforeach; ?>
                                    <?php if (count($piiTypes) > 2): ?>+<?php echo count($piiTypes) - 2; ?><?php endif; ?>
                                <?php else: ?>—<?php endif; ?>
                            </td>
                            <td><span class="badge badge-<?php echo ($file['status'] ?? 'analyzed') == 'anonymized' ? 'success' : 'info'; ?>">
                                <?php echo ucfirst($file['status'] ?? 'analyzed'); ?>
                            </span></td>
                            <td><?php echo date('M j, H:i', strtotime($file['created_at'] ?? 'now')); ?></td>
                            <td>
                                <?php if (($file['status'] ?? '') == 'anonymized' && !empty($file['anonymized_filepath'])): ?>
                                    <a href="download-anonymized.php?id=<?php echo $file['id']; ?>" class="btn btn-outline" style="padding: 4px 12px; font-size: 12px;">
                                        <i class="fas fa-download"></i> Download
                                    </a>
                                <?php elseif (($file['status'] ?? '') == 'analyzed'): ?>
                                    <span class="badge badge-info">Ready</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php else: ?>
            <p style="text-align: center; padding: 40px; color: #64748b;">
                <i class="fas fa-cloud-upload-alt" style="font-size: 48px; margin-bottom: 16px; display: block;"></i>
                No files analyzed yet. Click "New Analysis" to upload and scan your first file.
            </p>
            <?php endif; ?>
        </div>
        
        <!-- Missing Data Alert -->
        <?php if ($overallScore < 50): ?>
        <div class="form-card" style="background: rgba(239,68,68,0.05); border-color: #ef4444;">
            <h3><i class="fas fa-exclamation-triangle"></i> Compliance Gaps Detected</h3>
            <p>Your score is low because we're missing critical information. Complete these tasks to improve:</p>
            <ul style="margin-top: 12px; margin-left: 20px;">
                <?php if (!$dpoData): ?><li><a href="?view=form&form=dpo">Appoint a Data Protection Officer</a> (+15 points)</li><?php endif; ?>
                <?php if (empty($orgData['odpc_registration_number'])): ?><li><a href="?view=form&form=registration">Register with ODPC</a> (+12 points)</li><?php endif; ?>
                <?php if (empty($processors)): ?><li><a href="?view=form&form=processor">Register your data processors</a> (+10 points)</li><?php endif; ?>
                <?php if (empty($dpiaRecords)): ?><li><a href="?view=form&form=dpia">Complete a DPIA for high-risk processing</a> (+10 points)</li><?php endif; ?>
                <?php if (!$securityMeasures || !$securityMeasures['has_encryption']): ?><li><a href="?view=form&form=security">Document your security measures</a> (+8 points)</li><?php endif; ?>
            </ul>
        </div>
        <?php endif; ?>
        
        <?php elseif ($activeView === 'form' && $activeForm): ?>
        <!-- DATA ENTRY FORMS - Same as before -->
        <?php if ($activeForm === 'dpo'): ?>
        <div class="form-card">
            <h2><i class="fas fa-user-tie"></i> Appoint Data Protection Officer</h2>
            <p style="margin-bottom: 20px; color: #64748b;">Required by DPA 2019 Section 24. The DPO must be appointed and their contact details published.</p>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="add_dpo">
                <div class="form-group">
                    <label>DPO Full Name *</label>
                    <input type="text" name="dpo_name" required>
                </div>
                <div class="form-group">
                    <label>Email Address *</label>
                    <input type="email" name="dpo_email" required>
                </div>
                <div class="form-group">
                    <label>Phone Number</label>
                    <input type="tel" name="dpo_phone">
                </div>
                <div class="form-group">
                    <label>Appointment Date</label>
                    <input type="date" name="appointment_date" value="<?php echo date('Y-m-d'); ?>">
                </div>
                <div class="form-group">
                    <label>DPO Type</label>
                    <select name="dpo_type">
                        <option value="internal">Internal Employee</option>
                        <option value="external">External Consultant</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Appointment Letter (PDF)</label>
                    <input type="file" name="appointment_letter" accept=".pdf">
                </div>
                <div class="checkbox-group">
                    <label><input type="checkbox" name="is_published" checked> Contact details published on website/privacy policy</label>
                </div>
                <div style="display: flex; gap: 12px; margin-top: 20px;">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save DPO</button>
                    <a href="?view=dashboard" class="btn btn-outline">Cancel</a>
                </div>
            </form>
        </div>
        <?php endif; ?>
        
        <?php if ($activeForm === 'processor'): ?>
        <div class="form-card">
            <h2><i class="fas fa-microchip"></i> Register Data Processor</h2>
            <form method="POST">
                <input type="hidden" name="action" value="add_processor">
                <div class="form-group">
                    <label>Processor Name *</label>
                    <input type="text" name="processor_name" required>
                </div>
                <div class="form-group">
                    <label>Service Provided</label>
                    <input type="text" name="service_type" placeholder="e.g., Cloud hosting">
                </div>
                <div class="form-group">
                    <label>Contract Period</label>
                    <div style="display: flex; gap: 10px;">
                        <input type="date" name="contract_start" style="flex:1">
                        <input type="date" name="contract_end" style="flex:1">
                    </div>
                </div>
                <div class="checkbox-group">
                    <label><input type="checkbox" name="data_leaves_kenya"> Data transferred outside Kenya</label>
                    <label><input type="checkbox" name="has_dpa_clauses"> Contract has DPA clauses</label>
                </div>
                <div style="display: flex; gap: 12px; margin-top: 20px;">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Processor</button>
                    <a href="?view=dashboard" class="btn btn-outline">Cancel</a>
                </div>
            </form>
        </div>
        <?php endif; ?>
        
        <?php if ($activeForm === 'dpia'): ?>
        <div class="form-card">
            <h2><i class="fas fa-clipboard-list"></i> Complete DPIA</h2>
            <form method="POST">
                <input type="hidden" name="action" value="add_dpia">
                <div class="form-group">
                    <label>Processing Activity Name *</label>
                    <input type="text" name="activity_name" required>
                </div>
                <div class="form-group">
                    <label>Risk Level</label>
                    <select name="risk_level">
                        <option value="low">Low Risk</option>
                        <option value="medium" selected>Medium Risk</option>
                        <option value="high">High Risk</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Risk Findings</label>
                    <textarea name="risk_findings" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label>Mitigations</label>
                    <textarea name="mitigations" rows="3"></textarea>
                </div>
                <div style="display: flex; gap: 12px; margin-top: 20px;">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save DPIA</button>
                    <a href="?view=dashboard" class="btn btn-outline">Cancel</a>
                </div>
            </form>
        </div>
        <?php endif; ?>
        
        <?php if ($activeForm === 'breach'): ?>
        <div class="form-card">
            <h2><i class="fas fa-bug"></i> Report Data Breach</h2>
            <form method="POST">
                <input type="hidden" name="action" value="report_breach">
                <div class="form-group">
                    <label>Description of Breach *</label>
                    <textarea name="description" rows="4" required></textarea>
                </div>
                <div class="form-group">
                    <label>Number Affected</label>
                    <input type="number" name="affected_count" value="0">
                </div>
                <div class="checkbox-group">
                    <label><input type="checkbox" name="notified_odpc"> Notified ODPC</label>
                    <label><input type="checkbox" name="notified_subjects"> Notified affected individuals</label>
                </div>
                <div style="display: flex; gap: 12px; margin-top: 20px;">
                    <button type="submit" class="btn btn-danger"><i class="fas fa-exclamation-triangle"></i> Submit Report</button>
                    <a href="?view=dashboard" class="btn btn-outline">Cancel</a>
                </div>
            </form>
        </div>
        <?php endif; ?>
        
        <?php if ($activeForm === 'dsar'): ?>
        <div class="form-card">
            <h2><i class="fas fa-envelope"></i> Log DSAR</h2>
            <form method="POST">
                <input type="hidden" name="action" value="add_dsar">
                <div class="form-group">
                    <label>Request Type</label>
                    <select name="request_type">
                        <option value="access">Access</option>
                        <option value="erasure">Erasure</option>
                        <option value="rectification">Rectification</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Requester Name *</label>
                    <input type="text" name="requester_name" required>
                </div>
                <div class="form-group">
                    <label>Requester Email *</label>
                    <input type="email" name="requester_email" required>
                </div>
                <div style="display: flex; gap: 12px; margin-top: 20px;">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Log Request</button>
                    <a href="?view=dashboard" class="btn btn-outline">Cancel</a>
                </div>
            </form>
        </div>
        <?php endif; ?>
        
        <?php if ($activeForm === 'security'): ?>
        <div class="form-card">
            <h2><i class="fas fa-lock"></i> Security Measures</h2>
            <form method="POST">
                <input type="hidden" name="action" value="update_security">
                <div class="checkbox-group">
                    <label><input type="checkbox" name="has_encryption"> Data encryption</label>
                    <label><input type="checkbox" name="has_mfa"> Multi-factor authentication</label>
                    <label><input type="checkbox" name="has_backup"> Regular backups</label>
                    <label><input type="checkbox" name="has_access_control"> Access control</label>
                </div>
                <div style="display: flex; gap: 12px; margin-top: 20px;">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
                    <a href="?view=dashboard" class="btn btn-outline">Cancel</a>
                </div>
            </form>
        </div>
        <?php endif; ?>
        
        <?php if ($activeForm === 'registration'): ?>
        <div class="form-card">
            <h2><i class="fas fa-registered"></i> ODPC Registration</h2>
            <form method="POST">
                <input type="hidden" name="action" value="update_registration">
                <div class="form-group">
                    <label>ODPC Registration Number</label>
                    <input type="text" name="odpc_reg_number" value="<?php echo htmlspecialchars($orgData['odpc_registration_number'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>Privacy Policy URL</label>
                    <input type="url" name="privacy_policy_url" value="<?php echo htmlspecialchars($orgData['privacy_policy_url'] ?? ''); ?>">
                </div>
                <div style="display: flex; gap: 12px; margin-top: 20px;">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
                    <a href="?view=dashboard" class="btn btn-outline">Cancel</a>
                </div>
            </form>
        </div>
        <?php endif; ?>
        
        <?php elseif ($activeView === 'reports'): ?>
        <!-- REPORTS VIEW -->
        <div class="compliance-header" style="print: break-inside: avoid;">
            <h1><i class="fas fa-file-alt"></i> Compliance Report</h1>
            <p>Generated: <?php echo date('F j, Y g:i A'); ?></p>
            <div class="score-container">
                <div class="score-circle">
                    <div class="score-number"><?php echo $overallScore; ?>%</div>
                </div>
                <div>
                    <span class="risk-badge risk-<?php echo strtolower($riskLevel); ?>"><?php echo $riskLevel; ?> Risk</span>
                    <p style="margin-top: 12px;">Organization: <?php echo htmlspecialchars($org['name'] ?? 'N/A'); ?></p>
                </div>
            </div>
        </div>
        
        <div class="form-card">
            <h3>Compliance Summary</h3>
            <table class="data-table">
                <thead><tr><th>Factor</th><th>Score</th><th>Status</th></tr></thead>
                <tbody>
                    <?php foreach ($complianceFactors as $factor): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($factor['label']); ?></td>
                        <td><?php echo $factor['score']; ?>%</td>
                        <td>
                            <?php if ($factor['score'] >= 70): ?>
                            <span class="badge badge-success">Compliant</span>
                            <?php elseif ($factor['score'] >= 40): ?>
                            <span class="badge badge-warning">Partial</span>
                            <?php else: ?>
                            <span class="badge badge-danger">Non-compliant</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <div class="form-card">
            <h3>Files Analyzed (<?php echo count($files); ?>)</h3>
            <?php if (!empty($files)): ?>
            <table class="data-table">
                <thead><tr><th>Filename</th><th>Risk Score</th><th>Status</th><th>Date</th></tr></thead>
                <tbody>
                    <?php foreach ($files as $file): ?>
                    <tr>
                        <td><?php echo htmlspecialchars(substr($file['original_filename'], 0, 40)); ?></td>
                        <td><?php echo $file['risk_score'] ?? 0; ?>%</td>
                        <td><?php echo ucfirst($file['status'] ?? 'analyzed'); ?></td>
                        <td><?php echo date('M j, Y', strtotime($file['created_at'] ?? 'now')); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <p>No files analyzed yet.</p>
            <?php endif; ?>
        </div>
        
        <div style="display: flex; gap: 12px; justify-content: center; margin-top: 20px;">
            <button onclick="window.print()" class="btn btn-primary"><i class="fas fa-print"></i> Print Report</button>
            <a href="?view=dashboard" class="btn btn-outline">Back to Dashboard</a>
        </div>
        
        <?php elseif ($activeView === 'data'): ?>
        <!-- MY DATA VIEW -->
        <div class="form-card">
            <h2><i class="fas fa-user-tie"></i> Data Protection Officer</h2>
            <?php if ($dpoData): ?>
            <table class="data-table">
                <tr><th>Name:</th><td><?php echo htmlspecialchars($dpoData['name']); ?></td></tr>
                <tr><th>Email:</th><td><?php echo htmlspecialchars($dpoData['email']); ?></td></tr>
                <tr><th>Appointed:</th><td><?php echo date('M j, Y', strtotime($dpoData['appointment_date'])); ?></td></tr>
            </table>
            <?php else: ?>
            <p>No DPO appointed. <a href="?view=form&form=dpo">Add DPO →</a></p>
            <?php endif; ?>
        </div>
        
        <div class="form-card">
            <h2><i class="fas fa-microchip"></i> Data Processors (<?php echo count($processors); ?>)</h2>
            <?php if (!empty($processors)): ?>
            <table class="data-table">
                <thead><tr><th>Processor</th><th>Service</th><th>Data Leaves KE</th></tr></thead>
                <tbody>
                    <?php foreach ($processors as $p): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($p['processor_name']); ?></td>
                        <td><?php echo htmlspecialchars($p['service_type']); ?></td>
                        <td><?php echo $p['data_leaves_kenya'] ? 'Yes' : 'No'; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <p>No processors registered. <a href="?view=form&form=processor">Add Processor →</a></p>
            <?php endif; ?>
        </div>
        
        <div class="form-card">
            <h2><i class="fas fa-clipboard-list"></i> DPIAs (<?php echo count($dpiaRecords); ?>)</h2>
            <?php if (!empty($dpiaRecords)): ?>
            <table class="data-table">
                <thead><tr><th>Activity</th><th>Risk Level</th><th>Date</th></tr></thead>
                <tbody>
                    <?php foreach ($dpiaRecords as $d): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($d['activity_name']); ?></td>
                        <td><?php echo ucfirst($d['risk_level']); ?></td>
                        <td><?php echo date('M j, Y', strtotime($d['assessment_date'])); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <p>No DPIAs completed. <a href="?view=form&form=dpia">Complete DPIA →</a></p>
            <?php endif; ?>
        </div>
        
        <?php elseif ($activeView === 'upload'): ?>
        <!-- FILE UPLOAD -->
        <div class="form-card">
            <h2><i class="fas fa-shield-virus"></i> Scan File for PII Risks</h2>
            <p style="margin-bottom: 20px;">Upload a file to detect personal information and calculate PII risk score.</p>
            <form method="POST" action="analyze-file-risk.php" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Select File</label>
                    <input type="file" name="file" accept=".pdf,.docx,.xlsx,.csv,.txt" required>
                    <small style="color: #64748b;">Supported: PDF, DOCX, XLSX, CSV, TXT (Max 10MB)</small>
                </div>
                <button type="submit" class="btn btn-primary"><i class="fas fa-chart-line"></i> Analyze File</button>
                <a href="?view=dashboard" class="btn btn-outline">Cancel</a>
            </form>
        </div>
        <?php endif; ?>
        
    </div>
    
    <script>
        function toggleTheme() {
            const body = document.body;
            const isDark = body.classList.contains('dark');
            const newTheme = isDark ? 'light' : 'dark';
            body.classList.remove('dark', 'light');
            body.classList.add(newTheme);
            document.cookie = `soulguard_theme=${newTheme}; path=/; max-age=31536000`;
            setTimeout(() => location.reload(), 100);
        }
    </script>
</body>
</html>