<?php
// member/dashboard.php - Soul Guard Professional Data Protection Dashboard
require_once '../config.php';
requireLogin();

$userId = $_SESSION['user_id'];
$user = getUserById($userId);
$org = getUserOrganization($userId);
$pdo = getDBConnection();

// Update last login
try {
    $stmt = $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
    $stmt->execute([$userId]);
} catch (Exception $e) {}

// =============================================
// PROFILE BANNER: Only show if basic org info missing
// =============================================
$needsOrgUpdate = !$org || empty($org['name']) || empty($org['registration_number']);

// =============================================
// AUTO-CALCULATE COMPLIANCE SCORES (always recalculate on load)
// =============================================
function calculateAndSaveComplianceScore($pdo, $orgId, $userId) {
    global $org;
    try {
        // DPIA Score (0–10)
        $dpiaScore = 0;
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM dpia_records WHERE organization_id = ?");
        $stmt->execute([$orgId]);
        $dpiaCount = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        if ($dpiaCount >= 3) $dpiaScore = 10;
        elseif ($dpiaCount >= 1) $dpiaScore = 6;

        // Breach Readiness (0–25): deduct for open/unresolved breaches
        $breachScore = 25;
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM breach_reports WHERE organization_id = ? AND status NOT IN ('resolved', 'closed')");
        $stmt->execute([$orgId]);
        $openBreachCount = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        $breachScore -= min(25, $openBreachCount * 5); // -5 per open breach (was -3, now harsher)
        $breachScore = max(0, $breachScore);

        // Processor Management (0–20)
        $processorScore = 15;
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM processor_assessments WHERE organization_id = ?");
        $stmt->execute([$orgId]);
        if ($stmt->fetch(PDO::FETCH_ASSOC)['total'] > 0) $processorScore = 20;

        // ODPC Alignment (0–25)
        $odpcScore = 0;
        if (!empty($org['registration_number'])) $odpcScore += 10;
        $stmt = $pdo->prepare("SELECT COUNT(*) as total, SUM(CASE WHEN is_completed = 1 THEN 1 ELSE 0 END) as completed FROM odpc_compliance_tasks WHERE organization_id = ?");
        $stmt->execute([$orgId]);
        $taskData = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($taskData['total'] > 0) {
            $odpcScore += round(($taskData['completed'] / $taskData['total']) * 15);
        }

        // Data Protection (0–20): encryption, MFA, access control
        $dataProtectionScore = 0;
        $stmt = $pdo->prepare("SELECT * FROM security_measures WHERE organization_id = ? ORDER BY assessment_date DESC LIMIT 1");
        $stmt->execute([$orgId]);
        $security = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($security) {
            if (!empty($security['has_encryption']))    $dataProtectionScore += 10;
            if (!empty($security['has_mfa']))           $dataProtectionScore += 6;
            if (!empty($security['has_access_control'])) $dataProtectionScore += 4;
        }

        // DSR Responsiveness bonus/penalty
        $dsrPenalty = 0;
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) as overdue FROM data_subject_requests WHERE organization_id = ? AND status NOT IN ('completed','closed') AND DATEDIFF(NOW(), created_at) > 30");
            $stmt->execute([$orgId]);
            $overdue = $stmt->fetch(PDO::FETCH_ASSOC)['overdue'];
            $dsrPenalty = min(10, $overdue * 2);
        } catch (Exception $e) {}

        $overallScore = max(0, min(100, round(
            $dpiaScore + $breachScore + $processorScore + $odpcScore + $dataProtectionScore - $dsrPenalty
        )));

        $riskLevel = 'Critical';
        if ($overallScore >= 80) $riskLevel = 'Low';
        elseif ($overallScore >= 60) $riskLevel = 'Medium';
        elseif ($overallScore >= 40) $riskLevel = 'High';

        // Ensure table exists
        $pdo->exec("CREATE TABLE IF NOT EXISTS compliance_scores (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            organization_id INTEGER NOT NULL,
            overall_score INTEGER DEFAULT 0,
            dpia_score INTEGER DEFAULT 0,
            breach_readiness_score INTEGER DEFAULT 0,
            processor_management_score INTEGER DEFAULT 0,
            odpc_alignment_score INTEGER DEFAULT 0,
            data_protection_score INTEGER DEFAULT 0,
            risk_level TEXT DEFAULT 'Medium',
            assessment_date TEXT NOT NULL,
            next_assessment_date TEXT,
            recommendations TEXT,
            assessed_by INTEGER,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )");

        $stmt = $pdo->prepare("SELECT id FROM compliance_scores WHERE organization_id = ? AND assessment_date = date('now')");
        $stmt->execute([$orgId]);

        if ($stmt->fetch()) {
            $stmt = $pdo->prepare("UPDATE compliance_scores SET overall_score=?, dpia_score=?, breach_readiness_score=?, processor_management_score=?, odpc_alignment_score=?, data_protection_score=?, risk_level=?, assessed_by=? WHERE organization_id=? AND assessment_date=date('now')");
            $stmt->execute([$overallScore, $dpiaScore, $breachScore, $processorScore, $odpcScore, $dataProtectionScore, $riskLevel, $userId, $orgId]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO compliance_scores (organization_id, overall_score, dpia_score, breach_readiness_score, processor_management_score, odpc_alignment_score, data_protection_score, risk_level, assessment_date, next_assessment_date, assessed_by) VALUES (?,?,?,?,?,?,?,?, date('now'), date('now','+3 months'), ?)");
            $stmt->execute([$orgId, $overallScore, $dpiaScore, $breachScore, $processorScore, $odpcScore, $dataProtectionScore, $riskLevel, $userId]);
        }

        return [
            'overall_score'  => $overallScore,
            'risk_level'     => $riskLevel,
            'dpia_score'     => $dpiaScore,
            'breach_score'   => $breachScore,
            'processor_score'=> $processorScore,
            'odpc_score'     => $odpcScore,
            'dp_score'       => $dataProtectionScore,
        ];
    } catch (Exception $e) {
        return null;
    }
}

// =============================================
// FETCH ALL METRICS
// =============================================
$complianceScore = 0;
$complianceLevel = 'Not Assessed';
$hasReport       = false;
$scoreBreakdown  = [];

try {
    // Always recalculate if org exists
    if ($org) {
        $calculated = calculateAndSaveComplianceScore($pdo, $org['id'], $userId);
        if ($calculated) {
            $complianceScore  = $calculated['overall_score'];
            $complianceLevel  = $calculated['risk_level'];
            $scoreBreakdown   = $calculated;
        }
    }

    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM compliance_responses WHERE organization_id = ? AND assessment_date = date('now')");
    $stmt->execute([$org['id'] ?? 0]);
    $hasReport = ($stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0) > 0;
} catch (Exception $e) {}

// Counts
$totalDpias = $openBreaches = $totalProcessors = $pendingTasks = $completedTasks = $pendingDSRs = 0;
$recentFiles = $upcomingReminders = $riskTrends = $recentActivities = [];

// High-risk processes needing DPIA
$highRiskProcessesWithoutDpia = 0;
try {
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM processing_activities WHERE organization_id = ? AND risk_level = 'high' AND id NOT IN (SELECT processing_activity_id FROM dpia_records WHERE organization_id = ? AND processing_activity_id IS NOT NULL)");
    $stmt->execute([$org['id'] ?? 0, $org['id'] ?? 0]);
    $highRiskProcessesWithoutDpia = $stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
} catch (Exception $e) {}

try { $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM dpia_records WHERE organization_id = ?"); $stmt->execute([$org['id'] ?? 0]); $totalDpias = $stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0; } catch (Exception $e) {}
try { $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM breach_reports WHERE organization_id = ? AND status NOT IN ('resolved', 'closed')"); $stmt->execute([$org['id'] ?? 0]); $openBreaches = $stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0; } catch (Exception $e) {}
try { $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM processor_assessments WHERE organization_id = ?"); $stmt->execute([$org['id'] ?? 0]); $totalProcessors = $stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0; } catch (Exception $e) {}
try { $stmt = $pdo->prepare("SELECT COUNT(*) as total, SUM(CASE WHEN is_completed=1 THEN 1 ELSE 0 END) as completed FROM odpc_compliance_tasks WHERE organization_id = ?"); $stmt->execute([$org['id'] ?? 0]); $taskData = $stmt->fetch(PDO::FETCH_ASSOC); $pendingTasks = ($taskData['total'] ?? 0) - ($taskData['completed'] ?? 0); $completedTasks = $taskData['completed'] ?? 0; } catch (Exception $e) {}
try { $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM data_subject_requests WHERE organization_id = ? AND status NOT IN ('completed', 'closed')"); $stmt->execute([$org['id'] ?? 0]); $pendingDSRs = $stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0; } catch (Exception $e) {}
try { $stmt = $pdo->prepare("SELECT * FROM file_risk_analyses WHERE user_id = ? ORDER BY created_at DESC LIMIT 5"); $stmt->execute([$userId]); $recentFiles = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) {}
try { $stmt = $pdo->prepare("SELECT * FROM registration_reminders WHERE organization_id = ? AND is_completed = 0 AND due_date >= date('now') ORDER BY due_date ASC LIMIT 5"); $stmt->execute([$org['id'] ?? 0]); $upcomingReminders = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) {}
try { $stmt = $pdo->prepare("SELECT strftime('%Y-%m', assessment_date) as month, AVG(overall_score) as avg_score FROM compliance_scores WHERE organization_id = ? AND assessment_date >= date('now', '-6 months') GROUP BY month ORDER BY month ASC"); $stmt->execute([$org['id'] ?? 0]); $riskTrends = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) {}
try { $stmt = $pdo->prepare("SELECT * FROM user_activity WHERE user_id = ? ORDER BY created_at DESC LIMIT 8"); $stmt->execute([$userId]); $recentActivities = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) {}

// Maturity score
$maturityScore = 0;
if ($complianceScore > 0) {
    $maturityScore = min(100, round(
        ($complianceScore * 0.4) +
        ($totalDpias > 0 ? 15 : 0) +
        ($totalProcessors > 0 ? 15 : 0) +
        ($openBreaches == 0 ? 20 : max(0, 20 - $openBreaches * 4)) +
        ($pendingTasks == 0 ? 10 : 5)
    ));
}

$dpoDetails = $securityMeasures = null;
try { $stmt = $pdo->prepare("SELECT * FROM organization_dpo WHERE organization_id = ? AND status = 'active' LIMIT 1"); $stmt->execute([$org['id'] ?? 0]); $dpoDetails = $stmt->fetch(PDO::FETCH_ASSOC); } catch (Exception $e) {}
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) {}

// =============================================
// INTELLIGENT COMPLIANCE TIPS
// =============================================
$complianceTips = [];

if ($complianceScore < 40) {
    $complianceTips[] = ['icon' => 'exclamation-triangle', 'color' => 'danger', 'title' => 'Critical: Complete DPA Assessment', 'message' => 'Your compliance score indicates significant gaps. Complete the full DPA assessment to identify specific areas needing attention.', 'action' => 'compliance-assessment.php', 'action_text' => 'Start Assessment'];
}
if ($totalDpias == 0) {
    $complianceTips[] = ['icon' => 'file-alt', 'color' => 'warning', 'title' => 'No DPIAs Conducted', 'message' => 'Conduct Data Protection Impact Assessments for high-risk processing activities as required by DPA Section 41(5).', 'action' => 'dpia-automation.php', 'action_text' => 'Start DPIA'];
} elseif ($highRiskProcessesWithoutDpia > 0) {
    $complianceTips[] = ['icon' => 'exclamation-circle', 'color' => 'warning', 'title' => "{$highRiskProcessesWithoutDpia} High-Risk Process(es) Need DPIA", 'message' => "You have high-risk processing activities without a completed DPIA. This is a DPA Section 41(5) requirement.", 'action' => 'dpia-automation.php', 'action_text' => 'Run DPIA Now'];
}
if ($openBreaches > 0) {
    $complianceTips[] = ['icon' => 'bug', 'color' => 'danger', 'title' => "{$openBreaches} Open Breach(es) — Score Impact: -" . min(25, $openBreaches * 5) . "pts", 'message' => 'Open breaches are actively lowering your compliance score. Resolve them and notify ODPC within 72 hours per DPA Section 43.', 'action' => 'breach-workflow.php', 'action_text' => 'Resolve Breaches'];
}
if ($pendingTasks > 5) {
    $complianceTips[] = ['icon' => 'tasks', 'color' => 'warning', 'title' => "{$pendingTasks} Pending Compliance Tasks", 'message' => 'Your compliance backlog is building. Completing these tasks will improve your ODPC Alignment score.', 'action' => 'odpc-guidance.php', 'action_text' => 'View Tasks'];
}
if (!$hasReport && $complianceScore > 0) {
    $complianceTips[] = ['icon' => 'file-pdf', 'color' => 'info', 'title' => 'Generate Compliance Report', 'message' => 'Your assessment is ready. Generate a professional DPA compliance report with findings and recommendations.', 'action' => 'compliance-report.php', 'action_text' => 'Generate Report'];
}
if (empty($securityMeasures) || !$securityMeasures['has_encryption']) {
    $complianceTips[] = ['icon' => 'shield-alt', 'color' => 'warning', 'title' => 'Encryption Not Implemented — Score Impact: -10pts', 'message' => 'Implement AES-256 encryption for data at rest and TLS 1.2+ for data in transit per DPA Section 41.', 'action' => 'security-scan.php', 'action_text' => 'Security Scan'];
}

// Fill defaults to minimum 3 tips
$defaults = [
    ['icon' => 'clipboard-list', 'color' => 'info', 'title' => 'Maintain Record of Processing Activities', 'message' => 'Keep comprehensive RoPA documenting all data processing purposes, categories, and retention periods as required by DPA.', 'action' => 'odpc-guidance.php', 'action_text' => 'Start RoPA'],
    ['icon' => 'users', 'color' => 'info', 'title' => 'Staff DPA Training Required', 'message' => 'All staff handling personal data must receive annual DPA training with documented completion records.', 'action' => 'odpc-guidance.php', 'action_text' => 'Training Guide'],
    ['icon' => 'clock', 'color' => 'info', 'title' => 'Schedule Data Retention Review', 'message' => 'Personal data must not be kept longer than necessary per DPA Section 25(e). Set up a quarterly retention audit.', 'action' => 'compliance-scoring.php', 'action_text' => 'Review'],
];
foreach ($defaults as $tip) {
    if (count($complianceTips) >= 4) break;
    if (!in_array($tip['title'], array_column($complianceTips, 'title'))) {
        $complianceTips[] = $tip;
    }
}

$theme    = getTheme();
$greeting = getTimeBasedGreeting();

$rank = 'Not Rated';
if ($complianceScore >= 90)     $rank = '🏆 Expert';
elseif ($complianceScore >= 75) $rank = '⭐ Advanced';
elseif ($complianceScore >= 60) $rank = '📈 Proficient';
elseif ($complianceScore >= 40) $rank = '📊 Developing';
elseif ($complianceScore > 0)   $rank = '🌱 Beginner';

// Score breakdown for chart
$breakdownLabels = json_encode(['DPIA', 'Breach Readiness', 'Processors', 'ODPC Alignment', 'Data Protection']);
$breakdownData   = json_encode([
    $scoreBreakdown['dpia_score']      ?? 0,
    $scoreBreakdown['breach_score']    ?? 0,
    $scoreBreakdown['processor_score'] ?? 0,
    $scoreBreakdown['odpc_score']      ?? 0,
    $scoreBreakdown['dp_score']        ?? 0,
]);
$breakdownMax = json_encode([10, 25, 20, 25, 20]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Soul Guard - Data Protection Dashboard</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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <style>
        :root {
            --primary: #0f3b5c; --primary-dark: #082c44; --secondary: #2c7da0;
            --success: #10b981; --warning: #f59e0b; --danger: #ef4444; --info: #3b82f6;
            --dark: #1e293b; --light: #f8fafc; --gray: #64748b;
            --border-radius: 16px; --card-shadow: 0 4px 6px -2px rgba(0,0,0,0.05), 0 10px 15px -3px rgba(0,0,0,0.1);
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Inter', -apple-system, sans-serif; background: #f1f5f9; color: var(--dark); line-height: 1.6; }
        body.dark { background: #0f172a; color: #e2e8f0; }

        /* Navbar */
        .navbar { background: linear-gradient(135deg, var(--primary-dark), var(--primary)); padding: 0 24px; position: sticky; top: 0; z-index: 100; box-shadow: 0 2px 20px rgba(0,0,0,0.2); }
        body.light .navbar { background: rgba(255,255,255,0.95); backdrop-filter: blur(10px); border-bottom: 1px solid #e2e8f0; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .nav-container { max-width: 1600px; margin: 0 auto; display: flex; justify-content: space-between; align-items: center; min-height: 60px; }
        .logo { color: white; font-weight: 800; font-size: 20px; text-decoration: none; letter-spacing: -0.5px; }
        .logo span { background: linear-gradient(135deg, #fff, #94a3b8); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        body.light .logo span { background: linear-gradient(135deg, var(--primary), var(--secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        .nav-links { display: flex; gap: 2px; align-items: center; flex-wrap: wrap; }
        .nav-links a { color: rgba(255,255,255,0.85); text-decoration: none; padding: 8px 14px; border-radius: 8px; font-weight: 500; font-size: 12px; transition: var(--transition); white-space: nowrap; }
        body.light .nav-links a { color: var(--dark); }
        .nav-links a:hover, .nav-links a.active { background: rgba(255,255,255,0.2); color: white; }
        body.light .nav-links a:hover, body.light .nav-links a.active { background: var(--primary); color: white; }
        .theme-toggle { background: rgba(255,255,255,0.2); border: 2px solid rgba(255,255,255,0.3); border-radius: 50%; width: 38px; height: 38px; cursor: pointer; font-size: 16px; display: flex; align-items: center; justify-content: center; transition: var(--transition); color: white; }
        body.light .theme-toggle { background: #f1f5f9; border-color: #e2e8f0; color: var(--dark); }

        /* Container */
        .container { max-width: 1600px; margin: 0 auto; padding: 24px; }

        /* Welcome */
        .welcome-header { margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px; }
        .welcome-header h1 { font-size: 24px; font-weight: 700; }
        .welcome-header p { color: var(--gray); font-size: 12px; }
        .live-indicator { display: inline-flex; align-items: center; gap: 6px; font-size: 11px; color: var(--success); font-weight: 600; }
        .live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--success); animation: blink 1.5s infinite; }
        @keyframes blink { 0%,100%{opacity:1} 50%{opacity:0.3} }

        /* Banner — only shown when $needsOrgUpdate is true */
        .status-banner { padding: 12px 18px; border-radius: 10px; margin-bottom: 20px; display: flex; align-items: center; gap: 12px; font-size: 13px; }
        .status-banner.warning { background: rgba(245,158,11,0.1); border: 1px solid rgba(245,158,11,0.3); color: #92400e; }
        body.dark .status-banner.warning { color: #fbbf24; }

        /* DPIA Alert Banner */
        .dpia-alert { background: linear-gradient(135deg,rgba(239,68,68,0.08),rgba(245,158,11,0.08)); border: 1px solid rgba(239,68,68,0.25); border-radius: 10px; padding: 12px 18px; margin-bottom: 16px; display: flex; align-items: center; gap: 14px; font-size: 13px; }
        .dpia-alert strong { color: var(--danger); }

        /* Score Impact indicator */
        .score-impact { display: inline-block; padding: 2px 6px; border-radius: 4px; font-size: 9px; font-weight: 700; margin-left: 4px; }
        .score-impact.negative { background: rgba(239,68,68,0.15); color: var(--danger); }
        .score-impact.positive { background: rgba(16,185,129,0.15); color: var(--success); }

        /* Top Grid */
        .top-grid { display: grid; grid-template-columns: 1fr 2fr; gap: 16px; margin-bottom: 20px; }

        /* Compliance Card */
        .compliance-card { background: linear-gradient(135deg, var(--primary), var(--primary-dark)); border-radius: var(--border-radius); padding: 24px; color: white; box-shadow: 0 10px 40px rgba(15,59,92,0.3); display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; }
        .score-circle { width: 120px; height: 120px; border-radius: 50%; background: rgba(255,255,255,0.1); display: flex; align-items: center; justify-content: center; flex-direction: column; backdrop-filter: blur(10px); border: 3px solid rgba(255,255,255,0.2); margin-bottom: 10px; position: relative; }
        .score-number { font-size: 40px; font-weight: 800; }
        .score-label { font-size: 10px; opacity: 0.8; }
        .score-bar { background: rgba(255,255,255,0.2); height: 5px; border-radius: 3px; overflow: hidden; margin: 10px 0; width: 100%; }
        .score-bar-fill { background: var(--success); height: 100%; border-radius: 3px; transition: width 1.2s ease; }
        .score-breakdown-link { font-size: 10px; opacity: 0.75; cursor: pointer; text-decoration: underline; margin-top: 4px; }

        /* Quick Stats */
        .quick-stats-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
        .quick-stat { background: white; border-radius: 10px; padding: 14px; border: 1px solid #e2e8f0; cursor: pointer; transition: var(--transition); text-decoration: none; color: inherit; display: flex; align-items: center; gap: 10px; position: relative; }
        body.dark .quick-stat { background: #1e293b; border-color: #334155; }
        .quick-stat:hover { transform: translateY(-2px); box-shadow: var(--card-shadow); border-color: var(--secondary); }
        .quick-stat-icon { width: 40px; height: 40px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 18px; flex-shrink: 0; }
        .quick-stat-icon.blue { background: rgba(44,125,160,0.1); color: var(--secondary); }
        .quick-stat-icon.green { background: rgba(16,185,129,0.1); color: var(--success); }
        .quick-stat-icon.orange { background: rgba(245,158,11,0.1); color: var(--warning); }
        .quick-stat-icon.purple { background: rgba(139,92,246,0.1); color: #8b5cf6; }
        .quick-stat-icon.red { background: rgba(239,68,68,0.1); color: var(--danger); }
        .quick-stat-info { flex: 1; min-width: 0; }
        .quick-stat-value { font-size: 20px; font-weight: 700; }
        .quick-stat-label { font-size: 10px; color: var(--gray); }
        .stat-badge { position: absolute; top: 6px; right: 8px; font-size: 9px; font-weight: 700; padding: 1px 5px; border-radius: 8px; }
        .stat-badge.danger { background: rgba(239,68,68,0.15); color: var(--danger); }

        /* Stats Row */
        .stats-row { display: grid; grid-template-columns: repeat(6, 1fr); gap: 12px; margin-bottom: 20px; }
        .stat-card { background: white; border-radius: 12px; padding: 16px; text-align: center; border: 1px solid #e2e8f0; cursor: pointer; transition: var(--transition); text-decoration: none; color: inherit; display: block; }
        body.dark .stat-card { background: #1e293b; border-color: #334155; }
        .stat-card:hover { transform: translateY(-3px); box-shadow: var(--card-shadow); border-color: var(--secondary); }
        .stat-card i { font-size: 22px; margin-bottom: 6px; display: block; }
        .stat-card .stat-value { font-size: 22px; font-weight: 700; }
        .stat-card .stat-label { font-size: 10px; color: var(--gray); }

        /* Main Grid */
        .main-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 16px; margin-bottom: 20px; }

        /* Section */
        .section { background: white; border-radius: var(--border-radius); margin-bottom: 16px; border: 1px solid #e2e8f0; overflow: hidden; }
        body.dark .section { background: #1e293b; border-color: #334155; }
        .section-header { padding: 14px 18px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 8px; }
        body.dark .section-header { border-bottom-color: #334155; }
        .section-header h3 { font-size: 14px; font-weight: 600; display: flex; align-items: center; gap: 8px; }
        .section-header h3 i { color: var(--secondary); }
        .section-content { padding: 16px; }

        /* DPIA CTA Card */
        .dpia-cta { background: linear-gradient(135deg, #fff7ed, #fef3c7); border: 2px dashed #f59e0b; border-radius: 12px; padding: 20px; text-align: center; margin-bottom: 16px; }
        body.dark .dpia-cta { background: linear-gradient(135deg,rgba(245,158,11,0.1),rgba(239,68,68,0.08)); }
        .dpia-cta i { font-size: 32px; color: #f59e0b; margin-bottom: 8px; display: block; }
        .dpia-cta h4 { font-size: 14px; font-weight: 700; margin-bottom: 4px; }
        .dpia-cta p { font-size: 11px; color: var(--gray); margin-bottom: 12px; }

        /* Buttons */
        .btn { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; border-radius: 8px; font-weight: 500; font-size: 12px; border: none; cursor: pointer; transition: var(--transition); text-decoration: none; white-space: nowrap; font-family: inherit; }
        .btn:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.15); }
        .btn-primary { background: var(--primary); color: white; }
        .btn-success { background: var(--success); color: white; }
        .btn-warning { background: var(--warning); color: white; }
        .btn-danger { background: var(--danger); color: white; }
        .btn-outline { background: transparent; border: 2px solid var(--secondary); color: var(--secondary); }
        .btn-outline:hover { background: var(--secondary); color: white; }
        .btn-white { background: rgba(255,255,255,0.2); color: white; }
        .btn-white:hover { background: rgba(255,255,255,0.3); }
        .btn-sm { padding: 5px 10px; font-size: 11px; }
        .btn-lg { padding: 12px 24px; font-size: 14px; }
        .btn-report { background: linear-gradient(135deg, #dc2626, #991b1b); color: white; animation: pulse-btn 2s infinite; }
        @keyframes pulse-btn { 0%,100%{box-shadow:0 0 0 0 rgba(220,38,38,0.4)} 70%{box-shadow:0 0 0 10px rgba(220,38,38,0)} }

        /* Tables */
        .data-table { width: 100%; border-collapse: collapse; font-size: 12px; }
        .data-table th { text-align: left; padding: 8px 10px; font-weight: 600; font-size: 10px; color: var(--gray); text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid #e2e8f0; }
        .data-table td { padding: 8px 10px; border-bottom: 1px solid #f1f5f9; }
        body.dark .data-table td { border-bottom-color: #334155; }

        /* Badges */
        .badge { display: inline-block; padding: 3px 8px; border-radius: 20px; font-size: 10px; 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; }
        .badge-purple { background: rgba(139,92,246,0.12); color: #8b5cf6; }
        .risk-high { color: #ef4444; font-weight: 600; }
        .risk-medium { color: #f59e0b; font-weight: 600; }
        .risk-low { color: #10b981; font-weight: 600; }

        /* Tips */
        .tips-grid { display: grid; gap: 8px; }
        .tip-card { padding: 12px; border-radius: 8px; border: 1px solid; font-size: 11px; transition: var(--transition); }
        .tip-card:hover { transform: translateX(3px); }
        .tip-card .tip-header { display: flex; align-items: center; gap: 6px; margin-bottom: 4px; font-weight: 600; font-size: 12px; }
        .tip-card .tip-message { margin-bottom: 6px; line-height: 1.4; }
        .tip-card .tip-action { font-size: 10px; font-weight: 600; text-decoration: none; }

        /* Activity */
        .activity-feed { max-height: 300px; overflow-y: auto; }
        .activity-item { display: flex; gap: 8px; padding: 8px 0; border-bottom: 1px solid #f1f5f9; font-size: 11px; }
        body.dark .activity-item { border-bottom-color: #334155; }
        .activity-icon { width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 11px; flex-shrink: 0; }
        .activity-content .title { font-weight: 500; }
        .activity-content .time { font-size: 9px; color: var(--gray); }

        /* Services Grid */
        .services-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
        .service-card { background: white; border: 1px solid #e2e8f0; border-radius: 10px; padding: 18px; text-align: center; transition: var(--transition); text-decoration: none; color: inherit; display: block; }
        body.dark .service-card { background: #1e293b; border-color: #334155; }
        .service-card:hover { transform: translateY(-4px); box-shadow: var(--card-shadow); border-color: var(--secondary); }
        .service-card i { font-size: 30px; margin-bottom: 8px; display: block; }
        .service-card h4 { font-size: 13px; margin-bottom: 4px; }
        .service-card p { font-size: 10px; color: var(--gray); }

        /* Score Breakdown Modal */
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; justify-content: center; align-items: center; backdrop-filter: blur(5px); }
        .modal-content { background: white; border-radius: var(--border-radius); max-width: 550px; width: 90%; max-height: 85vh; overflow-y: auto; }
        body.dark .modal-content { background: #1e293b; }
        .modal-header { padding: 16px 20px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; background: linear-gradient(135deg, var(--primary), var(--primary-dark)); color: white; border-radius: var(--border-radius) var(--border-radius) 0 0; }
        .modal-body { padding: 20px; }
        .close { cursor: pointer; font-size: 24px; color: white; opacity: 0.8; }
        .upload-area { border: 3px dashed #cbd5e1; border-radius: 14px; padding: 36px; text-align: center; cursor: pointer; transition: var(--transition); }
        .upload-area:hover { border-color: var(--secondary); background: rgba(44,125,160,0.04); }
        .upload-area i { font-size: 36px; color: var(--gray); margin-bottom: 10px; display: block; }

        /* Score Breakdown bars */
        .breakdown-row { margin-bottom: 12px; }
        .breakdown-row label { display: flex; justify-content: space-between; font-size: 12px; margin-bottom: 4px; font-weight: 500; }
        .breakdown-track { background: #e2e8f0; border-radius: 6px; height: 10px; overflow: hidden; }
        body.dark .breakdown-track { background: #334155; }
        .breakdown-fill { height: 100%; border-radius: 6px; transition: width 1s ease; }

        /* =======================================
           CHATBOT WIDGET
        ======================================= */
        .chatbot-toggle {
            position: fixed; bottom: 24px; right: 24px; z-index: 9000;
            width: 56px; height: 56px; border-radius: 50%;
            background: linear-gradient(135deg, var(--secondary), var(--primary));
            color: white; border: none; cursor: pointer; font-size: 22px;
            display: flex; align-items: center; justify-content: center;
            box-shadow: 0 8px 30px rgba(15,59,92,0.4);
            transition: var(--transition);
        }
        .chatbot-toggle:hover { transform: scale(1.1); box-shadow: 0 12px 40px rgba(15,59,92,0.5); }
        .chatbot-toggle .chat-badge {
            position: absolute; top: -4px; right: -4px; background: var(--danger);
            color: white; border-radius: 50%; width: 18px; height: 18px; font-size: 10px;
            font-weight: 700; display: flex; align-items: center; justify-content: center;
        }

        .chatbot-panel {
            position: fixed; bottom: 92px; right: 24px; z-index: 9000;
            width: 360px; height: 500px; background: white; border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.2); display: none; flex-direction: column;
            overflow: hidden; border: 1px solid #e2e8f0;
            transition: var(--transition);
        }
        body.dark .chatbot-panel { background: #1e293b; border-color: #334155; }
        .chatbot-panel.open { display: flex; animation: slideUp 0.3s ease; }
        @keyframes slideUp { from{transform:translateY(20px);opacity:0} to{transform:translateY(0);opacity:1} }

        .chatbot-header {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            padding: 14px 16px; color: white; display: flex; align-items: center; gap: 10px;
        }
        .chatbot-avatar { width: 34px; height: 34px; border-radius: 50%; background: rgba(255,255,255,0.2); display: flex; align-items: center; justify-content: center; font-size: 16px; }
        .chatbot-title { font-weight: 600; font-size: 14px; }
        .chatbot-subtitle { font-size: 10px; opacity: 0.8; }
        .chatbot-close { margin-left: auto; cursor: pointer; font-size: 18px; opacity: 0.8; background: none; border: none; color: white; }

        .chatbot-messages { flex: 1; overflow-y: auto; padding: 14px; display: flex; flex-direction: column; gap: 10px; }
        .chat-msg { display: flex; gap: 8px; font-size: 12px; max-width: 100%; }
        .chat-msg.user { flex-direction: row-reverse; }
        .chat-bubble { padding: 10px 14px; border-radius: 14px; line-height: 1.5; max-width: 80%; word-wrap: break-word; }
        .chat-msg.bot .chat-bubble { background: #f1f5f9; color: var(--dark); border-radius: 4px 14px 14px 14px; }
        body.dark .chat-msg.bot .chat-bubble { background: #334155; color: #e2e8f0; }
        .chat-msg.user .chat-bubble { background: linear-gradient(135deg, var(--secondary), var(--primary)); color: white; border-radius: 14px 4px 14px 14px; }
        .chat-avatar { width: 26px; height: 26px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 11px; flex-shrink: 0; }
        .bot-avatar { background: linear-gradient(135deg, var(--secondary), var(--primary)); color: white; }
        .user-avatar { background: #e2e8f0; color: var(--gray); }

        .typing-indicator { display: flex; gap: 4px; align-items: center; padding: 10px 14px; background: #f1f5f9; border-radius: 14px; width: fit-content; }
        body.dark .typing-indicator { background: #334155; }
        .typing-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--gray); animation: typingBounce 1s infinite; }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }
        @keyframes typingBounce { 0%,80%,100%{transform:translateY(0)} 40%{transform:translateY(-6px)} }

        .chatbot-suggestions { padding: 8px 14px; display: flex; gap: 6px; flex-wrap: wrap; border-top: 1px solid #f1f5f9; }
        body.dark .chatbot-suggestions { border-top-color: #334155; }
        .chat-suggestion { padding: 4px 10px; border-radius: 20px; border: 1px solid var(--secondary); color: var(--secondary); font-size: 10px; cursor: pointer; transition: var(--transition); background: none; font-family: inherit; }
        .chat-suggestion:hover { background: var(--secondary); color: white; }

        .chatbot-input { padding: 12px 14px; border-top: 1px solid #e2e8f0; display: flex; gap: 8px; }
        body.dark .chatbot-input { border-top-color: #334155; }
        .chat-input-field { flex: 1; border: 1px solid #e2e8f0; border-radius: 20px; padding: 8px 14px; font-size: 12px; outline: none; background: #f8fafc; font-family: inherit; transition: var(--transition); }
        body.dark .chat-input-field { background: #334155; border-color: #475569; color: #e2e8f0; }
        .chat-input-field:focus { border-color: var(--secondary); background: white; }
        body.dark .chat-input-field:focus { background: #1e293b; }
        .chat-send-btn { width: 34px; height: 34px; border-radius: 50%; background: linear-gradient(135deg, var(--secondary), var(--primary)); color: white; border: none; cursor: pointer; font-size: 13px; display: flex; align-items: center; justify-content: center; transition: var(--transition); flex-shrink: 0; }
        .chat-send-btn:hover { transform: scale(1.1); }
        .chat-send-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }

        /* Toast */
        .toast-container { position: fixed; top: 80px; right: 20px; z-index: 10001; }
        .notification { padding: 12px 18px; border-radius: 8px; color: white; font-weight: 500; box-shadow: 0 8px 30px rgba(0,0,0,0.2); animation: slideInRight 0.4s ease; max-width: 320px; font-size: 12px; margin-bottom: 8px; }
        @keyframes slideInRight { from{transform:translateX(120%);opacity:0} to{transform:translateX(0);opacity:1} }

        /* Responsive */
        @media (max-width: 1200px) { .top-grid { grid-template-columns: 1fr; } .stats-row { grid-template-columns: repeat(3, 1fr); } .main-grid { grid-template-columns: 1fr; } .services-grid { grid-template-columns: repeat(2, 1fr); } }
        @media (max-width: 768px) { .container { padding: 12px; } .stats-row { grid-template-columns: repeat(2, 1fr); } .quick-stats-grid { grid-template-columns: 1fr; } .services-grid { grid-template-columns: 1fr; } .nav-links a { font-size: 10px; padding: 6px 8px; } .chatbot-panel { width: calc(100vw - 48px); } }
        @media (max-width: 480px) { .stats-row { grid-template-columns: 1fr; } }
    </style>
</head>
<body class="<?php echo $theme; ?>">
    <div class="toast-container" id="toastContainer"></div>

    <nav class="navbar">
        <div class="nav-container">
            <a href="dashboard.php" class="logo"><i class="fas fa-shield-alt"></i> <span>Soul Guard</span></a>
            <div class="nav-links">
                <a href="dashboard.php" class="active"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
                <a href="compliance-assessment.php"><i class="fas fa-clipboard-check"></i> Assessment</a>
                <a href="dpia-automation.php"><i class="fas fa-file-alt"></i> DPIA</a>
                <a href="compliance-report.php"><i class="fas fa-file-pdf"></i> Report</a>
                <a href="organization.php"><i class="fas fa-building"></i> Organization</a>
                <a href="profile.php"><i class="fas fa-user"></i> Profile</a>
                <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
                <button class="theme-toggle" onclick="toggleTheme()"><?php echo $theme === 'dark' ? '☀️' : '🌙'; ?></button>
            </div>
        </div>
    </nav>

    <div class="container">
        <!-- Welcome -->
        <div class="welcome-header">
            <div>
                <h1><?php echo $greeting['text']; ?>, <?php echo htmlspecialchars($user['full_name'] ?? $user['username']); ?>!</h1>
                <p><i class="fas fa-calendar-alt"></i> <?php echo date('l, F j, Y'); ?> • <span class="live-indicator"><span class="live-dot"></span> Live Scoring</span></p>
            </div>
            <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                <a href="compliance-assessment.php" class="btn btn-success btn-lg"><i class="fas fa-clipboard-check"></i> New Assessment</a>
                <a href="dpia-automation.php" class="btn btn-warning btn-lg"><i class="fas fa-file-alt"></i> Run DPIA</a>
                <?php if ($hasReport): ?>
                <a href="compliance-report.php" class="btn btn-report btn-lg"><i class="fas fa-file-pdf"></i> View Report</a>
                <?php endif; ?>
            </div>
        </div>

        <!-- Organization Banner — ONLY shown when org details are missing -->
        <?php if ($needsOrgUpdate): ?>
        <div class="status-banner warning">
            <i class="fas fa-info-circle"></i>
            <div style="flex: 1;"><strong>Complete Your Organization Profile</strong> — Add your organization name and registration number for accurate DPA compliance scoring.</div>
            <a href="organization.php?edit=1" class="btn btn-sm" style="background:#92400e;color:white;">Complete Now</a>
        </div>
        <?php endif; ?>

        <!-- DPIA Alert for high-risk processes -->
        <?php if ($highRiskProcessesWithoutDpia > 0): ?>
        <div class="dpia-alert">
            <i class="fas fa-exclamation-triangle" style="color:var(--danger);font-size:20px;flex-shrink:0;"></i>
            <div style="flex:1;">
                <strong><?php echo $highRiskProcessesWithoutDpia; ?> high-risk processing activit<?php echo $highRiskProcessesWithoutDpia > 1 ? 'ies require' : 'y requires'; ?> a DPIA</strong> — This is a legal requirement under DPA 2019 Section 41(5). Unassessed high-risk processes reduce your compliance score.
            </div>
            <a href="dpia-automation.php" class="btn btn-danger btn-sm"><i class="fas fa-file-alt"></i> Start DPIA</a>
        </div>
        <?php endif; ?>

        <!-- Breach Alert Banner -->
        <?php if ($openBreaches > 0): ?>
        <div class="dpia-alert" style="border-color:rgba(239,68,68,0.4);background:linear-gradient(135deg,rgba(239,68,68,0.08),rgba(239,68,68,0.04));">
            <i class="fas fa-bug" style="color:var(--danger);font-size:20px;flex-shrink:0;"></i>
            <div style="flex:1;">
                <strong><?php echo $openBreaches; ?> unresolved breach<?php echo $openBreaches > 1 ? 'es are' : ' is'; ?> reducing your score by <?php echo min(25, $openBreaches * 5); ?> points</strong> — Notify ODPC within 72 hours and resolve to restore your compliance rating.
            </div>
            <a href="breach-workflow.php" class="btn btn-danger btn-sm"><i class="fas fa-tools"></i> Resolve Now</a>
        </div>
        <?php endif; ?>

        <!-- Top Grid -->
        <div class="top-grid">
            <!-- Compliance Score -->
            <div class="compliance-card">
                <div class="score-circle">
                    <div class="score-number" id="complianceScoreDisplay"><?php echo $complianceScore; ?>%</div>
                    <div class="score-label">Compliance Score</div>
                </div>
                <span class="badge <?php echo $complianceLevel == 'Low' ? 'badge-success' : ($complianceLevel == 'Medium' ? 'badge-warning' : ($complianceLevel == 'High' ? 'badge-danger' : 'badge-danger')); ?>" style="font-size: 11px; margin-bottom: 6px;">
                    <?php echo $complianceLevel; ?> Risk • <?php echo $rank; ?>
                </span>
                <div class="score-bar"><div class="score-bar-fill" style="width: <?php echo $complianceScore; ?>%" id="complianceBar"></div></div>
                <div style="font-size:10px;opacity:0.7;margin-top:4px;">Auto-recalculates on changes</div>
                <div class="score-breakdown-link" onclick="document.getElementById('breakdownModal').style.display='flex'">
                    <i class="fas fa-chart-pie"></i> View score breakdown
                </div>
                <div style="display: flex; gap: 6px; margin-top: 12px; flex-wrap: wrap; justify-content: center;">
                    <button class="btn btn-white btn-sm" onclick="refreshDashboard()"><i class="fas fa-sync-alt"></i> Refresh</button>
                    <?php if ($hasReport): ?>
                    <a href="compliance-report.php" class="btn btn-white btn-sm"><i class="fas fa-file-pdf"></i> Report</a>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Quick Stats -->
            <div class="quick-stats-grid">
                <a href="compliance-assessment.php" class="quick-stat">
                    <div class="quick-stat-icon green"><i class="fas fa-clipboard-check"></i></div>
                    <div class="quick-stat-info"><div class="quick-stat-value"><?php echo $hasReport ? '✅' : '📋'; ?></div><div class="quick-stat-label">DPA Assessment</div></div>
                </a>
                <a href="dpia-records.php" class="quick-stat">
                    <div class="quick-stat-icon blue"><i class="fas fa-file-alt"></i></div>
                    <div class="quick-stat-info"><div class="quick-stat-value" id="dpiaCompleted"><?php echo $totalDpias; ?></div><div class="quick-stat-label">DPIAs Completed</div></div>
                    <?php if ($highRiskProcessesWithoutDpia > 0): ?><span class="stat-badge danger"><?php echo $highRiskProcessesWithoutDpia; ?> needed</span><?php endif; ?>
                </a>
                <a href="breach-reports.php" class="quick-stat">
                    <div class="quick-stat-icon <?php echo $openBreaches > 0 ? 'red' : 'orange'; ?>"><i class="fas fa-<?php echo $openBreaches > 0 ? 'bug' : 'shield-alt'; ?>"></i></div>
                    <div class="quick-stat-info"><div class="quick-stat-value" id="openBreaches"><?php echo $openBreaches; ?></div><div class="quick-stat-label">Open Breaches<?php echo $openBreaches > 0 ? ' <span class="score-impact negative">-'.min(25,$openBreaches*5).'pts</span>' : ''; ?></div></div>
                </a>
                <a href="processors.php" class="quick-stat">
                    <div class="quick-stat-icon purple"><i class="fas fa-building"></i></div>
                    <div class="quick-stat-info"><div class="quick-stat-value" id="totalProcessors"><?php echo $totalProcessors; ?></div><div class="quick-stat-label">Data Processors</div></div>
                </a>
                <a href="tasks.php" class="quick-stat">
                    <div class="quick-stat-icon blue"><i class="fas fa-tasks"></i></div>
                    <div class="quick-stat-info"><div class="quick-stat-value" id="pendingTasks"><?php echo $pendingTasks; ?></div><div class="quick-stat-label">Pending Tasks</div></div>
                </a>
                <a href="#" class="quick-stat" onclick="document.getElementById('fileUploadModal').style.display='flex'; return false;">
                    <div class="quick-stat-icon green"><i class="fas fa-cloud-upload-alt"></i></div>
                    <div class="quick-stat-info"><div class="quick-stat-value"><i class="fas fa-plus-circle"></i></div><div class="quick-stat-label">Upload & Analyze File</div></div>
                </a>
            </div>
        </div>

        <!-- Stats Row -->
        <div class="stats-row">
            <div class="stat-card"><i class="fas fa-star" style="color: #f59e0b;"></i><div class="stat-value" id="maturityScore"><?php echo $maturityScore; ?>%</div><div class="stat-label">Maturity</div></div>
            <div class="stat-card"><i class="fas fa-check-double" style="color: var(--success);"></i><div class="stat-value"><?php echo $completedTasks; ?></div><div class="stat-label">Completed Tasks</div></div>
            <div class="stat-card"><i class="fas fa-user-clock" style="color: var(--info);"></i><div class="stat-value"><?php echo $pendingDSRs; ?></div><div class="stat-label">Pending DSRs</div></div>
            <div class="stat-card"><i class="fas fa-shield-alt" style="color: <?php echo ($securityMeasures && $securityMeasures['has_encryption']) ? 'var(--success)' : 'var(--warning)'; ?>;"></i><div class="stat-value"><?php echo ($securityMeasures && $securityMeasures['has_encryption']) ? '✅' : '⚠️'; ?></div><div class="stat-label">Encryption</div></div>
            <div class="stat-card"><i class="fas fa-user-shield" style="color: <?php echo $dpoDetails ? 'var(--success)' : 'var(--warning)'; ?>;"></i><div class="stat-value"><?php echo $dpoDetails ? '✅' : '❌'; ?></div><div class="stat-label">DPO Status</div></div>
            <div class="stat-card" onclick="document.getElementById('fileUploadModal').style.display='flex'" style="cursor:pointer;"><i class="fas fa-plus-circle" style="color: var(--secondary);"></i><div class="stat-value"><small>Upload</small></div><div class="stat-label">Data Ingestion</div></div>
        </div>

        <!-- DPIA CTA — when no DPIAs at all -->
        <?php if ($totalDpias == 0): ?>
        <div class="dpia-cta">
            <i class="fas fa-file-search"></i>
            <h4>No Data Protection Impact Assessments Yet</h4>
            <p>DPIAs are mandatory for high-risk processing activities under DPA 2019 Section 41(5). Completing one will add <strong>+10 points</strong> to your compliance score.</p>
            <div style="display:flex;gap:8px;justify-content:center;flex-wrap:wrap;">
                <a href="dpia-automation.php" class="btn btn-warning"><i class="fas fa-magic"></i> Auto-Generate DPIA</a>
                <a href="dpia-records.php" class="btn btn-outline"><i class="fas fa-list"></i> View Templates</a>
            </div>
        </div>
        <?php endif; ?>

        <!-- Main Grid -->
        <div class="main-grid">
            <!-- Left Column -->
            <div>
                <!-- Compliance Trends -->
                <div class="section">
                    <div class="section-header">
                        <h3><i class="fas fa-chart-line"></i> Compliance Score Trends</h3>
                        <div style="display:flex;gap:6px;align-items:center;">
                            <span class="badge badge-info">Last 6 Months</span>
                            <button class="btn btn-sm btn-outline" onclick="refreshDashboard()"><i class="fas fa-sync-alt"></i></button>
                        </div>
                    </div>
                    <div class="section-content"><canvas id="trendsChart" height="160"></canvas></div>
                </div>

                <!-- Score Breakdown Chart -->
                <div class="section">
                    <div class="section-header"><h3><i class="fas fa-chart-radar"></i> Score Breakdown by Category</h3><button class="btn btn-sm btn-outline" onclick="document.getElementById('breakdownModal').style.display='flex'"><i class="fas fa-expand"></i> Details</button></div>
                    <div class="section-content"><canvas id="breakdownChart" height="200"></canvas></div>
                </div>

                <!-- File Analysis -->
                <div class="section">
                    <div class="section-header"><h3><i class="fas fa-database"></i> Data Ingestion & PII Analysis</h3><button class="btn btn-sm btn-primary" onclick="document.getElementById('fileUploadModal').style.display='flex'"><i class="fas fa-plus"></i> Upload File</button></div>
                    <div class="section-content" style="overflow-x:auto;">
                        <?php if (!empty($recentFiles)): ?>
                        <table class="data-table">
                            <thead><tr><th>Filename</th><th>Risk</th><th>PII Detected</th><th>Status</th><th>Date</th><th></th></tr></thead>
                            <tbody>
                                <?php foreach ($recentFiles as $file): $piiTypes = json_decode($file['detected_pii_types'], true) ?: []; ?>
                                <tr>
                                    <td><strong><?php echo htmlspecialchars(substr($file['original_filename'], 0, 30)); ?></strong></td>
                                    <td><span class="<?php echo $file['risk_score'] >= 60 ? 'risk-high' : ($file['risk_score'] >= 30 ? 'risk-medium' : 'risk-low'); ?>"><?php echo $file['risk_score']; ?>%</span></td>
                                    <td><?php if (!empty($piiTypes)): foreach (array_slice($piiTypes,0,2) as $t): ?><span class="badge badge-info"><?php echo ucfirst(str_replace('_',' ',$t)); ?></span><?php endforeach; if(count($piiTypes)>2): ?><span class="badge badge-purple">+<?php echo count($piiTypes)-2; ?></span><?php endif; else: ?><span class="badge badge-success">Clean</span><?php endif; ?></td>
                                    <td><span class="badge badge-<?php echo $file['status']=='anonymized'?'success':'info'; ?>"><?php echo ucfirst($file['status']); ?></span></td>
                                    <td><?php echo date('M j, H:i', strtotime($file['created_at'])); ?></td>
                                    <td><?php if($file['status']=='anonymized' && $file['anonymized_filepath']): ?><a href="download-anonymized.php?id=<?php echo $file['id']; ?>" class="btn btn-sm btn-success"><i class="fas fa-download"></i></a><?php elseif($file['status']=='analyzed'): ?><button class="btn btn-sm btn-primary" onclick="anonymizeFile(<?php echo $file['id']; ?>)"><i class="fas fa-mask"></i></button><?php else: ?><span class="badge badge-warning">Processing</span><?php endif; ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <?php else: ?>
                        <div style="text-align:center;padding:30px;color:var(--gray);"><i class="fas fa-cloud-upload-alt" style="font-size:36px;margin-bottom:10px;display:block;opacity:0.5;"></i><p><strong>No files analyzed</strong></p><p style="font-size:11px;">Upload files to detect PII, assess risk, and anonymize data</p><button class="btn btn-primary" style="margin-top:12px;" onclick="document.getElementById('fileUploadModal').style.display='flex'"><i class="fas fa-upload"></i> Upload File</button></div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Right Column -->
            <div>
                <!-- Compliance Tips -->
                <div class="section">
                    <div class="section-header"><h3><i class="fas fa-lightbulb"></i> Compliance Insights</h3><span class="badge badge-purple">AI-Powered</span></div>
                    <div class="section-content">
                        <div class="tips-grid">
                            <?php foreach ($complianceTips as $tip): ?>
                            <div class="tip-card" style="background:rgba(<?php echo $tip['color']=='danger'?'239,68,68':($tip['color']=='warning'?'245,158,11':'59,130,246'); ?>,0.05);border-color:rgba(<?php echo $tip['color']=='danger'?'239,68,68':($tip['color']=='warning'?'245,158,11':'59,130,246'); ?>,0.2);">
                                <div class="tip-header" style="color:var(--<?php echo $tip['color']; ?>);"><i class="fas fa-<?php echo $tip['icon']; ?>"></i> <?php echo $tip['title']; ?></div>
                                <div class="tip-message"><?php echo $tip['message']; ?></div>
                                <a href="<?php echo $tip['action']; ?>" class="tip-action" style="color:var(--<?php echo $tip['color']; ?>);"><?php echo $tip['action_text']; ?> <i class="fas fa-arrow-right"></i></a>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <!-- Activity Feed -->
                <div class="section">
                    <div class="section-header"><h3><i class="fas fa-history"></i> Recent Activity</h3><a href="activity-log.php" class="btn btn-sm btn-outline">All</a></div>
                    <div class="section-content">
                        <div class="activity-feed">
                            <?php if (!empty($recentActivities)): foreach ($recentActivities as $act): ?>
                            <div class="activity-item">
                                <div class="activity-icon" style="background:rgba(44,125,160,0.1);color:var(--secondary);"><i class="fas fa-<?php echo getActivityIcon($act['action']); ?>"></i></div>
                                <div class="activity-content"><div class="title"><?php echo htmlspecialchars($act['details'] ?? $act['action']); ?></div><div class="time"><?php echo timeAgo($act['created_at']); ?></div></div>
                            </div>
                            <?php endforeach; else: ?>
                            <div style="text-align:center;padding:20px;color:var(--gray);"><i class="fas fa-inbox" style="font-size:24px;margin-bottom:6px;display:block;"></i>No recent activity</div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Upcoming Deadlines -->
                <?php if (!empty($upcomingReminders)): ?>
                <div class="section">
                    <div class="section-header"><h3><i class="fas fa-calendar-alt"></i> Upcoming Deadlines</h3><a href="registration-reminders.php" class="btn btn-sm btn-outline">All</a></div>
                    <div class="section-content">
                        <?php foreach ($upcomingReminders as $rem): $daysUntil = ceil((strtotime($rem['due_date'])-time())/86400); $urg = $daysUntil<=7?'danger':($daysUntil<=30?'warning':'info'); ?>
                        <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f1f5f9;font-size:12px;"><div><strong><?php echo ucfirst(str_replace('_',' ',$rem['reminder_type'])); ?></strong><br><small style="color:var(--gray);">Due: <?php echo date('M j, Y',strtotime($rem['due_date'])); ?></small></div><span class="badge badge-<?php echo $urg; ?>"><?php echo $daysUntil; ?>d</span></div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Professional Services -->
        <div class="section">
            <div class="section-header"><h3><i class="fas fa-concierge-bell"></i> Professional Services</h3><a href="services.php" class="btn btn-sm btn-outline">All Services</a></div>
            <div class="section-content">
                <div class="services-grid">
                    <a href="compliance-assessment.php" class="service-card"><i class="fas fa-clipboard-check" style="color:var(--success);"></i><h4>DPA Assessment</h4><p>Full Kenya DPA 2019 compliance audit</p><span class="badge badge-success">Available</span></a>
                    <a href="security-scan.php" class="service-card"><i class="fas fa-shield-virus" style="color:var(--secondary);"></i><h4>Security Scan</h4><p>Infrastructure vulnerability assessment</p><span class="badge badge-success">Available</span></a>
                    <a href="data-audit.php" class="service-card"><i class="fas fa-database" style="color:var(--info);"></i><h4>Data Mapping</h4><p>Personal data flow documentation</p><span class="badge badge-info">Available</span></a>
                    <a href="training.php" class="service-card"><i class="fas fa-graduation-cap" style="color:#8b5cf6;"></i><h4>Staff Training</h4><p>DPA compliance training & certification</p><span class="badge badge-purple">Available</span></a>
                    <a href="service-request.php?type=dpo" class="service-card"><i class="fas fa-user-shield" style="color:var(--warning);"></i><h4>Outsourced DPO</h4><p>Certified Data Protection Officer</p><span class="badge badge-warning">Request</span></a>
                    <a href="service-request.php?type=registration" class="service-card"><i class="fas fa-file-signature" style="color:var(--danger);"></i><h4>ODPC Registration</h4><p>Expert registration assistance</p><span class="badge badge-danger">Request</span></a>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="section">
            <div class="section-header"><h3><i class="fas fa-bolt"></i> Quick Actions</h3></div>
            <div class="section-content">
                <div style="display:flex;gap:10px;flex-wrap:wrap;">
                    <a href="compliance-assessment.php" class="btn btn-success btn-lg"><i class="fas fa-clipboard-check"></i> DPA Assessment</a>
                    <a href="dpia-automation.php" class="btn btn-warning btn-lg"><i class="fas fa-file-alt"></i> Run DPIA</a>
                    <?php if ($hasReport): ?>
                    <a href="compliance-report.php" class="btn btn-report btn-lg"><i class="fas fa-file-pdf"></i> View Report</a>
                    <?php endif; ?>
                    <a href="security-scan.php" class="btn btn-primary btn-lg"><i class="fas fa-search"></i> Security Scan</a>
                    <a href="breach-workflow.php" class="btn btn-danger btn-lg"><i class="fas fa-bug"></i> Report Breach</a>
                    <button class="btn btn-outline btn-lg" onclick="window.print()"><i class="fas fa-download"></i> Export Dashboard</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Score Breakdown Modal -->
    <div id="breakdownModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-chart-bar"></i> Compliance Score Breakdown</h3>
                <span class="close" onclick="document.getElementById('breakdownModal').style.display='none'">&times;</span>
            </div>
            <div class="modal-body">
                <div style="text-align:center;margin-bottom:20px;">
                    <div style="font-size:48px;font-weight:800;color:var(--primary);"><?php echo $complianceScore; ?>%</div>
                    <div class="badge <?php echo $complianceLevel == 'Low' ? 'badge-success' : ($complianceLevel == 'Medium' ? 'badge-warning' : 'badge-danger'); ?>" style="font-size:13px;"><?php echo $complianceLevel; ?> Risk — <?php echo $rank; ?></div>
                </div>
                <?php
                $breakdownItems = [
                    ['label'=>'DPIA Completion','score'=>$scoreBreakdown['dpia_score']??0,'max'=>10,'color'=>'#3b82f6','desc'=>'Points for conducting required DPIAs'],
                    ['label'=>'Breach Readiness','score'=>$scoreBreakdown['breach_score']??0,'max'=>25,'color'=>'#10b981','desc'=>'Deducts for open/unresolved breaches (-5 each)'],
                    ['label'=>'Processor Management','score'=>$scoreBreakdown['processor_score']??0,'max'=>20,'color'=>'#8b5cf6','desc'=>'Points for assessed data processors'],
                    ['label'=>'ODPC Alignment','score'=>$scoreBreakdown['odpc_score']??0,'max'=>25,'color'=>'#f59e0b','desc'=>'Registration number + task completion rate'],
                    ['label'=>'Data Protection Measures','score'=>$scoreBreakdown['dp_score']??0,'max'=>20,'color'=>'#ef4444','desc'=>'Encryption (+10), MFA (+6), Access Control (+4)'],
                ];
                foreach ($breakdownItems as $item):
                    $pct = $item['max'] > 0 ? round(($item['score'] / $item['max']) * 100) : 0;
                ?>
                <div class="breakdown-row">
                    <label><span><?php echo $item['label']; ?></span><span style="font-weight:700;"><?php echo $item['score']; ?> / <?php echo $item['max']; ?> pts</span></label>
                    <div class="breakdown-track"><div class="breakdown-fill" style="width:<?php echo $pct; ?>%;background:<?php echo $item['color']; ?>;"></div></div>
                    <small style="color:var(--gray);font-size:10px;"><?php echo $item['desc']; ?></small>
                </div>
                <?php endforeach; ?>
                <div style="background:#f8fafc;border-radius:8px;padding:12px;margin-top:16px;font-size:12px;">
                    <strong><i class="fas fa-lightbulb" style="color:#f59e0b;"></i> How to improve your score:</strong><br>
                    • Resolve open breaches (biggest impact: up to 25 pts)<br>
                    • Complete ODPC compliance tasks<br>
                    • Enable encryption & MFA<br>
                    • Run DPIAs for all high-risk processes
                </div>
                <a href="compliance-assessment.php" class="btn btn-success" style="width:100%;justify-content:center;margin-top:12px;"><i class="fas fa-clipboard-check"></i> Full DPA Assessment</a>
            </div>
        </div>
    </div>

    <!-- File Upload Modal -->
    <div id="fileUploadModal" class="modal">
        <div class="modal-content">
            <div class="modal-header"><h3><i class="fas fa-shield-virus"></i> Analyze File for PII Risk</h3><span class="close" onclick="closeUploadModal()">&times;</span></div>
            <div class="modal-body">
                <div class="upload-area" id="uploadArea" onclick="document.getElementById('fileInput').click()"><i class="fas fa-cloud-upload-alt"></i><p><strong>Click to upload</strong> or drag and drop</p><small>PDF, DOCX, XLSX, CSV, TXT (Max 10MB)</small><input type="file" id="fileInput" style="display:none;" accept=".pdf,.docx,.xlsx,.csv,.txt"></div>
                <div id="uploadProgress" style="display:none;margin-top:16px;"><div class="score-bar"><div id="progressBar" style="width:0%;height:100%;background:var(--success);border-radius:4px;transition:width 0.3s;"></div></div><p id="progressText" style="text-align:center;margin-top:8px;font-size:12px;">Analyzing...</p></div>
                <div id="analysisResults" style="display:none;margin-top:16px;"><div id="resultsContent"></div><div style="display:flex;gap:8px;margin-top:12px;"><button class="btn btn-success" id="anonymizeBtn" style="display:none;"><i class="fas fa-mask"></i> Anonymize</button><button class="btn btn-outline" onclick="closeUploadModal()">Close</button></div></div>
            </div>
        </div>
    </div>

    <!-- ============================================
         AI COMPLIANCE CHATBOT WIDGET
         Powered by Claude via chatbot-api.php
    ============================================ -->
    <button class="chatbot-toggle" id="chatToggle" onclick="toggleChat()" title="Ask the DPA Compliance Assistant">
        <i class="fas fa-robot" id="chatIcon"></i>
        <span class="chat-badge" id="chatBadge" style="display:none;">1</span>
    </button>

    <div class="chatbot-panel" id="chatPanel">
        <div class="chatbot-header">
            <div class="chatbot-avatar"><i class="fas fa-shield-alt"></i></div>
            <div>
                <div class="chatbot-title">DPA Compliance Assistant</div>
                <div class="chatbot-subtitle">Powered by AI • Kenya DPA 2019 specialist</div>
            </div>
            <button class="chatbot-close" onclick="toggleChat()"><i class="fas fa-times"></i></button>
        </div>

        <div class="chatbot-messages" id="chatMessages">
            <!-- Welcome message injected by JS -->
        </div>

        <div class="chatbot-suggestions" id="chatSuggestions">
            <button class="chat-suggestion" onclick="sendSuggestion(this)">What is a DPIA?</button>
            <button class="chat-suggestion" onclick="sendSuggestion(this)">72-hour breach rule</button>
            <button class="chat-suggestion" onclick="sendSuggestion(this)">ODPC registration steps</button>
            <button class="chat-suggestion" onclick="sendSuggestion(this)">DPO requirements</button>
        </div>

        <div class="chatbot-input">
            <input type="text" class="chat-input-field" id="chatInput" placeholder="Ask about Kenya DPA compliance..." maxlength="500">
            <button class="chat-send-btn" id="chatSendBtn" onclick="sendChatMessage()"><i class="fas fa-paper-plane"></i></button>
        </div>
    </div>

    <script>
    // =============================================
    // DASHBOARD AUTO-UPDATE
    // =============================================
    let autoUpdateInterval;
    function startAutoUpdate() { autoUpdateInterval = setInterval(refreshDashboard, 30000); }
    function stopAutoUpdate() { if (autoUpdateInterval) clearInterval(autoUpdateInterval); }

    async function refreshDashboard() {
        try {
            const r = await fetch('api/get-dashboard-metrics.php');
            const d = await r.json();
            if (d.success) {
                document.getElementById('complianceScoreDisplay').textContent = (d.metrics.compliance_score||0) + '%';
                document.getElementById('complianceBar').style.width = (d.metrics.compliance_score||0) + '%';
                document.getElementById('dpiaCompleted').textContent = d.metrics.total_dpias||0;
                document.getElementById('openBreaches').textContent = d.metrics.open_breaches||0;
                document.getElementById('totalProcessors').textContent = d.metrics.total_processors||0;
                document.getElementById('pendingTasks').textContent = d.metrics.pending_tasks||0;
                document.getElementById('maturityScore').textContent = (d.metrics.maturity_score||0) + '%';
            }
        } catch(e) {}
    }

    // =============================================
    // CHARTS
    // =============================================
    function initTrendsChart() {
        const ctx = document.getElementById('trendsChart'); if (!ctx) return;
        const data = <?php echo json_encode($riskTrends); ?>;
        if (!data.length) {
            ctx.parentNode.innerHTML = '<div style="text-align:center;padding:20px;color:var(--gray);"><i class="fas fa-chart-line" style="font-size:30px;opacity:0.5;display:block;margin-bottom:8px;"></i><p style="font-size:11px;">Complete assessments to see trends</p></div>';
            return;
        }
        new Chart(ctx, { type: 'line', data: { labels: data.map(d=>d.month), datasets: [{ label: 'Compliance Score', data: data.map(d=>Math.round(d.avg_score)), borderColor: '#2c7da0', backgroundColor: 'rgba(44,125,160,0.1)', fill: true, tension: 0.4, borderWidth: 2.5, pointRadius: 5, pointBackgroundColor: '#fff', pointBorderColor: '#2c7da0', pointBorderWidth: 2 }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false }, tooltip: { callbacks: { label: ctx => ` Score: ${ctx.raw}%` } } }, scales: { y: { beginAtZero: true, max: 100, ticks: { callback: v => v+'%' } }, x: { grid: { display: false } } } } });
    }

    function initBreakdownChart() {
        const ctx = document.getElementById('breakdownChart'); if (!ctx) return;
        const labels = <?php echo $breakdownLabels; ?>;
        const data   = <?php echo $breakdownData; ?>;
        const maxes  = <?php echo $breakdownMax; ?>;
        const pcts   = data.map((v,i) => maxes[i] > 0 ? Math.round((v/maxes[i])*100) : 0);

        new Chart(ctx, {
            type: 'bar',
            data: {
                labels,
                datasets: [
                    { label: 'Achieved', data, backgroundColor: ['rgba(59,130,246,0.7)','rgba(16,185,129,0.7)','rgba(139,92,246,0.7)','rgba(245,158,11,0.7)','rgba(239,68,68,0.7)'], borderRadius: 6, borderSkipped: false },
                    { label: 'Max', data: maxes, backgroundColor: 'rgba(203,213,225,0.3)', borderRadius: 6, borderSkipped: false }
                ]
            },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false }, tooltip: { callbacks: { label: ctx => ctx.dataset.label === 'Achieved' ? ` ${ctx.raw} pts (${pcts[ctx.dataIndex]}%)` : ` Max: ${ctx.raw} pts` } } }, scales: { x: { stacked: false, grid: { display: false } }, y: { beginAtZero: true } } }
        });
    }

    function toggleTheme() {
        const body = document.body;
        body.classList.toggle('dark'); body.classList.toggle('light');
        document.cookie = `soulguard_theme=${body.classList.contains('dark')?'dark':'light'};path=/;max-age=31536000`;
        showToast('Theme updated', 'info');
    }

    // =============================================
    // FILE UPLOAD
    // =============================================
    function closeUploadModal() { document.getElementById('fileUploadModal').style.display = 'none'; resetUploadForm(); }
    function resetUploadForm() {
        document.getElementById('uploadArea').style.display = 'block';
        document.getElementById('uploadProgress').style.display = 'none';
        document.getElementById('analysisResults').style.display = 'none';
        document.getElementById('fileInput').value = '';
        const b = document.getElementById('anonymizeBtn'); if (b) b.style.display = 'none';
    }

    const fileInput = document.getElementById('fileInput');
    const uploadArea = document.getElementById('uploadArea');
    if (uploadArea) {
        uploadArea.addEventListener('click', e => { if (e.target !== fileInput) fileInput.click(); });
        fileInput.addEventListener('change', async e => { const f = e.target.files[0]; if (f) await uploadFile(f); });
        uploadArea.addEventListener('dragover', e => { e.preventDefault(); uploadArea.style.borderColor = '#10b981'; });
        uploadArea.addEventListener('dragleave', () => { uploadArea.style.borderColor = '#cbd5e1'; });
        uploadArea.addEventListener('drop', e => { e.preventDefault(); uploadArea.style.borderColor = '#cbd5e1'; const f = e.dataTransfer.files[0]; if (f) { fileInput.files = e.dataTransfer.files; fileInput.dispatchEvent(new Event('change')); } });
    }

    async function uploadFile(file) {
        const fd = new FormData(); fd.append('file', file);
        uploadArea.style.display = 'none'; document.getElementById('uploadProgress').style.display = 'block';
        simulateProgress();
        try {
            const r = await fetch('analyze-file-risk.php', { method: 'POST', body: fd });
            const d = await r.json();
            document.getElementById('uploadProgress').style.display = 'none';
            document.getElementById('analysisResults').style.display = 'block';
            if (d.success) { displayResults(d); showToast('✅ Analysis complete!', 'success'); refreshDashboard(); }
            else { document.getElementById('resultsContent').innerHTML = '<div style="text-align:center;padding:16px;color:#ef4444;"><i class="fas fa-exclamation-circle" style="font-size:30px;"></i><p>Analysis Failed</p><p style="font-size:11px;">'+d.message+'</p></div>'; }
        } catch(e) {
            document.getElementById('uploadProgress').style.display = 'none';
            document.getElementById('analysisResults').style.display = 'block';
            document.getElementById('resultsContent').innerHTML = '<div style="text-align:center;padding:16px;color:#ef4444;"><i class="fas fa-times-circle" style="font-size:30px;"></i><p>Upload Failed</p></div>';
        }
    }

    function simulateProgress() {
        const bar = document.getElementById('progressBar'), txt = document.getElementById('progressText');
        let w = 0;
        const i = setInterval(() => { if (w >= 90) { clearInterval(i); return; } w += Math.random()*15; if (w>90) w=90; bar.style.width = w+'%'; txt.textContent = 'Analyzing PII... '+Math.round(w)+'%'; }, 300);
    }

    function displayResults(r) {
        const bg = r.risk_score>=60?'#ef4444':(r.risk_score>=30?'#f59e0b':'#10b981');
        const pii = r.detected_pii&&r.detected_pii.length?r.detected_pii.map(t=>'<span class="badge badge-info">'+t.replace(/_/g,' ')+'</span>').join(' '):'<span class="badge badge-success">No PII</span>';
        document.getElementById('resultsContent').innerHTML = '<div style="background:'+bg+'15;border:1px solid '+bg+';border-radius:8px;padding:14px;margin-bottom:10px;"><div style="display:flex;justify-content:space-between;"><strong style="color:'+bg+';">Risk: '+r.risk_score+'%</strong><span class="badge '+(r.risk_score>=60?'badge-danger':(r.risk_score>=30?'badge-warning':'badge-success'))+'">'+r.risk_level+'</span></div><p style="margin-top:6px;font-size:12px;">'+r.message+'</p></div><div style="padding:10px;background:rgba(44,125,160,0.04);border-radius:8px;margin-bottom:10px;"><strong>PII Detected:</strong> '+pii+'</div><div style="padding:10px;background:rgba(139,92,246,0.04);border-radius:8px;"><strong>Summary:</strong> '+r.total_sensitive_fields+' sensitive fields</div>';
        if (r.risk_score>=25&&r.file_id) { const b=document.getElementById('anonymizeBtn'); b.style.display='inline-flex'; b.onclick=()=>anonymizeFile(r.file_id); }
    }

    async function anonymizeFile(fileId) {
        const b = document.getElementById('anonymizeBtn'); if(!b)return;
        const ot = b.innerHTML; b.disabled=true; b.innerHTML='<i class="fas fa-spinner fa-spin"></i>';
        try {
            const r = await fetch('anonymize-file.php', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({file_id:fileId}) });
            const d = await r.json();
            if(d.success){showToast('✅ '+d.message,'success');setTimeout(()=>{window.location.href=d.download_url;},1500);}
            else{showToast('❌ '+d.message,'error');b.disabled=false;b.innerHTML=ot;}
        }catch(e){showToast('❌ Failed','error');b.disabled=false;b.innerHTML=ot;}
    }

    // =============================================
    // TOAST
    // =============================================
    function showToast(msg, type='info') {
        const c = document.getElementById('toastContainer');
        const t = document.createElement('div');
        t.className = 'notification';
        t.style.background = type==='success'?'#10b981':(type==='error'?'#ef4444':'#3b82f6');
        t.innerHTML = msg; c.appendChild(t);
        setTimeout(()=>{t.style.opacity='0';t.style.transform='translateX(100%)';t.style.transition='all 0.3s';setTimeout(()=>t.remove(),300);},4000);
    }

    // =============================================
    // CHATBOT
    // =============================================
    let chatOpen = false;
    let chatHistory = [];
    let chatGreeted = false;

    function toggleChat() {
        chatOpen = !chatOpen;
        const panel = document.getElementById('chatPanel');
        const icon  = document.getElementById('chatIcon');
        const badge = document.getElementById('chatBadge');
        panel.classList.toggle('open', chatOpen);
        icon.className = chatOpen ? 'fas fa-times' : 'fas fa-robot';
        badge.style.display = 'none';

        if (chatOpen && !chatGreeted) {
            chatGreeted = true;
            addBotMessage(`👋 Hello, **<?php echo htmlspecialchars($user['full_name'] ?? $user['username']); ?>**!\n\nI'm your Kenya DPA 2019 Compliance Assistant. I can help you with:\n\n• DPIA guidance & high-risk process rules\n• ODPC registration requirements\n• Breach notification timelines\n• Data subject rights & DSR handling\n• Compliance score improvement tips\n\nWhat would you like to know?`);
        }
    }

    function addBotMessage(text, isTyping=false) {
        const msgs = document.getElementById('chatMessages');
        const div = document.createElement('div');
        div.className = 'chat-msg bot';
        const rendered = text.replace(/\*\*(.*?)\*\*/g,'<strong>$1</strong>').replace(/\n/g,'<br>').replace(/^• /gm,'&bull; ');
        div.innerHTML = `<div class="chat-avatar bot-avatar"><i class="fas fa-shield-alt"></i></div><div class="chat-bubble">${rendered}</div>`;
        msgs.appendChild(div);
        msgs.scrollTop = msgs.scrollHeight;
        return div;
    }

    function addUserMessage(text) {
        const msgs = document.getElementById('chatMessages');
        const div = document.createElement('div');
        div.className = 'chat-msg user';
        div.innerHTML = `<div class="chat-bubble">${text}</div><div class="chat-avatar user-avatar"><i class="fas fa-user"></i></div>`;
        msgs.appendChild(div);
        msgs.scrollTop = msgs.scrollHeight;
    }

    function addTypingIndicator() {
        const msgs = document.getElementById('chatMessages');
        const div = document.createElement('div');
        div.className = 'chat-msg bot'; div.id = 'typingIndicator';
        div.innerHTML = `<div class="chat-avatar bot-avatar"><i class="fas fa-shield-alt"></i></div><div class="typing-indicator"><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div></div>`;
        msgs.appendChild(div);
        msgs.scrollTop = msgs.scrollHeight;
        return div;
    }

    function removeTypingIndicator() {
        const el = document.getElementById('typingIndicator');
        if (el) el.remove();
    }

    function sendSuggestion(btn) {
        const text = btn.textContent;
        document.getElementById('chatSuggestions').style.display = 'none';
        sendChatMessage(text);
    }

    async function sendChatMessage(overrideText=null) {
        const input = document.getElementById('chatInput');
        const msg = overrideText || input.value.trim();
        if (!msg) return;

        input.value = '';
        document.getElementById('chatSendBtn').disabled = true;

        addUserMessage(msg);
        chatHistory.push({ role: 'user', content: msg });

        const typing = addTypingIndicator();

        try {
            const res = await fetch('chatbot-api.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    message: msg,
                    history: chatHistory.slice(-10), // last 10 turns
                    context: {
                        compliance_score: <?php echo $complianceScore; ?>,
                        open_breaches: <?php echo $openBreaches; ?>,
                        total_dpias: <?php echo $totalDpias; ?>,
                        pending_tasks: <?php echo $pendingTasks; ?>,
                        org_name: <?php echo json_encode($org['name'] ?? ''); ?>,
                        risk_level: <?php echo json_encode($complianceLevel); ?>
                    }
                })
            });

            const data = await res.json();
            removeTypingIndicator();

            if (data.success && data.reply) {
                addBotMessage(data.reply);
                chatHistory.push({ role: 'assistant', content: data.reply });
            } else {
                addBotMessage("I'm sorry, I couldn't process that. Please try again, or contact support.");
            }
        } catch (e) {
            removeTypingIndicator();
            addBotMessage("⚠️ Connection issue. Please check your connection and try again.");
        }

        document.getElementById('chatSendBtn').disabled = false;
        input.focus();
    }

    // Enter key to send
    document.getElementById('chatInput').addEventListener('keydown', e => {
        if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendChatMessage(); }
    });

    // =============================================
    // INIT & EVENT BINDINGS
    // =============================================
    window.onclick = function(e) {
        if (e.target === document.getElementById('fileUploadModal')) closeUploadModal();
        if (e.target === document.getElementById('breakdownModal')) document.getElementById('breakdownModal').style.display = 'none';
    };

    document.addEventListener('DOMContentLoaded', () => {
        initTrendsChart();
        initBreakdownChart();
        startAutoUpdate();

        // Show chat badge after 3s to draw attention
        setTimeout(() => {
            if (!chatOpen) document.getElementById('chatBadge').style.display = 'flex';
        }, 3000);
    });

    document.addEventListener('visibilitychange', () => {
        if (document.hidden) stopAutoUpdate();
        else { startAutoUpdate(); refreshDashboard(); }
    });

    document.addEventListener('keydown', e => {
        if (e.ctrlKey||e.metaKey) {
            if (e.key==='r') { e.preventDefault(); refreshDashboard(); showToast('🔄 Refreshed', 'info'); }
            if (e.key==='u') { e.preventDefault(); document.getElementById('fileUploadModal').style.display='flex'; }
            if (e.key==='k') { e.preventDefault(); toggleChat(); }
        }
    });
    </script>
</body>
</html>
<?php
function getTimeBasedGreeting() {
    $h = date('H');
    if ($h < 12) return ['text' => 'Good Morning', 'icon' => '🌅'];
    if ($h < 17) return ['text' => 'Good Afternoon', 'icon' => '☀️'];
    return ['text' => 'Good Evening', 'icon' => '🌙'];
}
function getActivityIcon($a) {
    $icons = ['file_upload'=>'upload','file_analysis'=>'search','dpia_created'=>'file-alt','breach_reported'=>'bug','compliance_check'=>'check-circle','processor_added'=>'building','login'=>'sign-in-alt','organization_update'=>'cog','compliance_assessment'=>'clipboard-check'];
    return $icons[$a] ?? 'circle';
}
function timeAgo($d) {
    $diff = time() - strtotime($d);
    if ($diff < 60) return 'Just now';
    if ($diff < 3600) return floor($diff/60).'m ago';
    if ($diff < 86400) return floor($diff/3600).'h ago';
    if ($diff < 604800) return floor($diff/86400).'d ago';
    return date('M j', strtotime($d));
}
?>