<?php
// member/compliance-assessment.php - Dynamic DPA Compliance Self-Assessment with Website Scanner
require_once '../config.php';
requireLogin();

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

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

// Create tables if not exists
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS compliance_responses (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        organization_id INTEGER NOT NULL,
        user_id INTEGER NOT NULL,
        question_id INTEGER NOT NULL,
        response TEXT NOT NULL,
        response_score INTEGER DEFAULT 0,
        assessment_date TEXT NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");
    
    $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
    )");
} catch (Exception $e) {}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $orgId = $org['id'] ?? 0;
        $today = date('Y-m-d');
        
        // Get all questions
        $stmt = $pdo->query("SELECT * FROM dpa_questions ORDER BY sort_order, id");
        $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $categoryScores = [];
        $totalScore = 0;
        $maxScore = 0;
        $answeredCount = 0;
        
        // Delete previous responses for today
        $stmt = $pdo->prepare("DELETE FROM compliance_responses WHERE organization_id = ? AND assessment_date = ?");
        $stmt->execute([$orgId, $today]);
        
        // Process each question
        foreach ($questions as $question) {
            $qId = $question['id'];
            $category = $question['category'];
            $weight = $question['weight'] ?? 1;
            $responseValue = $_POST['q_' . $qId] ?? 'not_answered';
            
            if ($responseValue === 'not_answered') continue;
            $answeredCount++;
            
            // Calculate score
            $score = 0;
            switch ($responseValue) {
                case 'yes': $score = round(100 * $weight); break;
                case 'partially': $score = round(60 * $weight); break;
                case 'in_progress': $score = round(35 * $weight); break;
                case 'no': $score = 0; break;
                case 'not_applicable': $score = round(100 * $weight); break;
            }
            
            // Save response
            $stmt = $pdo->prepare("INSERT INTO compliance_responses 
                (organization_id, user_id, question_id, response, response_score, assessment_date)
                VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$orgId, $userId, $qId, $responseValue, $score, $today]);
            
            // Track category scores
            if (!isset($categoryScores[$category])) {
                $categoryScores[$category] = ['earned' => 0, 'max' => 0, 'answered' => 0, 'total' => 0];
            }
            $categoryScores[$category]['earned'] += $score;
            $categoryScores[$category]['max'] += (100 * $weight);
            $categoryScores[$category]['answered']++;
            $categoryScores[$category]['total']++;
            $totalScore += $score;
            $maxScore += (100 * $weight);
        }
        
        // Count total questions per category
        foreach ($questions as $question) {
            $cat = $question['category'];
            if (isset($categoryScores[$cat])) {
                $categoryScores[$cat]['total']++;
            }
        }
        
        // Calculate overall percentage
        $overallScore = $maxScore > 0 ? round(($totalScore / $maxScore) * 100) : 0;
        
        // Category breakdown
        $categoryBreakdown = [];
        foreach ($categoryScores as $cat => $scores) {
            $categoryBreakdown[$cat] = [
                'score' => $scores['max'] > 0 ? round(($scores['earned'] / $scores['max']) * 100) : 0,
                'answered' => $scores['answered'],
                'total' => $scores['total']
            ];
        }
        
        // Map to compliance_scores format
        $legalBasis = $categoryBreakdown['Legal Basis & Lawful Processing']['score'] ?? 0;
        $rights = $categoryBreakdown['Data Subject Rights']['score'] ?? 0;
        $transparency = $categoryBreakdown['Privacy Notices & Transparency']['score'] ?? 0;
        $retention = $categoryBreakdown['Data Minimisation & Retention']['score'] ?? 0;
        $security = $categoryBreakdown['Data Security & Technical Measures']['score'] ?? 0;
        $processor = $categoryBreakdown['Data Processors & Third Parties']['score'] ?? 0;
        $crossBorder = $categoryBreakdown['Cross-Border Data Transfers']['score'] ?? 0;
        $odpc = $categoryBreakdown['ODPC Registration & Governance']['score'] ?? 0;
        $training = $categoryBreakdown['Staff Training & Awareness']['score'] ?? 0;
        $website = $categoryBreakdown['Website & Digital Compliance']['score'] ?? 0;
        
        $dpiaEq = min(25, round(($legalBasis + $transparency + $website) / 300 * 25));
        $breachEq = min(25, round($security / 100 * 25));
        $processorEq = min(25, round(($processor + $crossBorder) / 200 * 25));
        $odpcEq = min(25, round(($odpc + $rights) / 200 * 25));
        $dataEq = min(25, round(($retention + $training) / 200 * 25));
        $mappedScore = $dpiaEq + $breachEq + $processorEq + $odpcEq + $dataEq;
        
        // Risk level
        $riskLevel = 'Critical';
        if ($overallScore >= 80) $riskLevel = 'Low';
        elseif ($overallScore >= 60) $riskLevel = 'Medium';
        elseif ($overallScore >= 40) $riskLevel = 'High';
        
        // Recommendations
        $recommendations = [];
        foreach ($categoryBreakdown as $cat => $data) {
            $s = $data['score'];
            if ($s < 30) $recommendations[] = "CRITICAL: {$cat} - Score: {$s}% - Immediate action required";
            elseif ($s < 50) $recommendations[] = "HIGH: {$cat} - Score: {$s}% - Significant improvements needed";
            elseif ($s < 70) $recommendations[] = "MEDIUM: {$cat} - Score: {$s}% - Continue improving";
        }
        
        if (empty($recommendations)) {
            $recommendations[] = "Your organization shows good compliance. Maintain and review regularly.";
        }
        
        // Save to compliance_scores
        $stmt = $pdo->prepare("DELETE FROM compliance_scores WHERE organization_id = ? AND assessment_date = ?");
        $stmt->execute([$orgId, $today]);
        
        $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, recommendations, assessed_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, date('now'), date('now', '+3 months'), ?, ?)");
        $stmt->execute([
            $orgId, $overallScore, $dpiaEq, $breachEq,
            $processorEq, $odpcEq, $dataEq,
            $riskLevel, implode("\n", $recommendations), $userId
        ]);
        
        // Log activity
        try {
            $pdo->exec("CREATE TABLE IF NOT EXISTS user_activity (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER, action TEXT, details TEXT, ip_address TEXT,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )");
            $stmt = $pdo->prepare("INSERT INTO user_activity (user_id, action, details, ip_address, created_at) 
                                   VALUES (?, 'compliance_assessment', ?, ?, datetime('now'))");
            $stmt->execute([$userId, "DPA Assessment: {$overallScore}% ({$riskLevel} Risk)", $_SERVER['REMOTE_ADDR'] ?? '']);
        } catch (Exception $e) {}
        
        $message = "✅ Assessment completed! Score: {$overallScore}% | Risk: {$riskLevel} | {$answeredCount} questions answered";
        $messageType = 'success';
        
    } catch (Exception $e) {
        $message = "❌ Error: " . $e->getMessage();
        $messageType = 'error';
    }
}

// Fetch questions from database
$questionsByCategory = [];
$totalQuestionCount = 0;
try {
    $stmt = $pdo->query("SELECT * FROM dpa_questions ORDER BY sort_order, id");
    $allQuestions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $totalQuestionCount = count($allQuestions);
    foreach ($allQuestions as $q) {
        $questionsByCategory[$q['category']][] = $q;
    }
} catch (Exception $e) {
    $allQuestions = [];
    $message = "Could not load questions: " . $e->getMessage();
    $messageType = 'error';
}

// Get previous responses for today
$previousResponses = [];
try {
    $stmt = $pdo->prepare("SELECT question_id, response FROM compliance_responses 
                           WHERE organization_id = ? AND assessment_date = date('now')");
    $stmt->execute([$org['id'] ?? 0]);
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $previousResponses[$row['question_id']] = $row['response'];
    }
} catch (Exception $e) {}

$theme = getTheme();

// Category config with icons and colors
$categoryConfig = [
    'Consent & Lawful Processing' => ['icon' => 'handshake', 'color' => '#3b82f6', 'points' => 'Weight: 3-3.5'],
    'ODPC Registration & Governance' => ['icon' => 'file-signature', 'color' => '#f97316', 'points' => 'Weight: 3-4'],
    'Data Subject Rights' => ['icon' => 'users', 'color' => '#8b5cf6', 'points' => 'Weight: 2.5-3'],
    'Privacy Notices & Transparency' => ['icon' => 'eye', 'color' => '#10b981', 'points' => 'Weight: 2.5-3.5'],
    'Data Minimisation & Retention' => ['icon' => 'clock', 'color' => '#f59e0b', 'points' => 'Weight: 2-3'],
    'Data Security & Technical Measures' => ['icon' => 'shield-alt', 'color' => '#ef4444', 'points' => 'Weight: 2.5-3.5'],
    'Breach Management' => ['icon' => 'bug', 'color' => '#dc2626', 'points' => 'Weight: 2.5-3.5'],
    'Data Processors & Third Parties' => ['icon' => 'building', 'color' => '#06b6d4', 'points' => 'Weight: 2.5-3.5'],
    'Cross-Border Data Transfers' => ['icon' => 'globe-africa', 'color' => '#84cc16', 'points' => 'Weight: 3-3.5'],
    'Staff Training & Awareness' => ['icon' => 'graduation-cap', 'color' => '#ec4899', 'points' => 'Weight: 2.5-3'],
    'Website & Digital Compliance' => ['icon' => 'laptop', 'color' => '#6366f1', 'points' => 'Weight: 3-3.5'],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DPA Compliance Assessment - 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>
        :root {
            --primary: #0f3b5c; --primary-dark: #082c44; --secondary: #2c7da0;
            --success: #10b981; --warning: #f59e0b; --danger: #ef4444; --info: #3b82f6;
            --dark: #1e293b; --light: #f8fafc; --gray: #64748b; --border-radius: 12px;
        }
        * { 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 {
            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);
        }
        .nav-container {
            max-width: 1200px; margin: 0 auto; display: flex;
            justify-content: space-between; align-items: center; min-height: 56px;
        }
        .logo { color: white; font-weight: 700; font-size: 18px; text-decoration: none; }
        .logo i { margin-right: 8px; }
        .nav-links a {
            color: rgba(255,255,255,0.8); text-decoration: none; padding: 6px 14px;
            border-radius: 8px; font-size: 13px; font-weight: 500; transition: all 0.2s;
        }
        .nav-links a:hover { background: rgba(255,255,255,0.15); color: white; }
        
        .container { max-width: 1000px; margin: 0 auto; padding: 24px 16px; }
        
        .card {
            background: white; border-radius: 14px; padding: 28px;
            margin-bottom: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            border: 1px solid #e2e8f0;
        }
        body.dark .card { background: #1e293b; border-color: #334155; }
        
        .page-header { margin-bottom: 24px; }
        .page-header h1 { font-size: 24px; font-weight: 700; }
        .page-header p { color: var(--gray); font-size: 13px; margin-top: 4px; }
        
        /* Website Scanner Card */
        .scanner-card {
            background: linear-gradient(135deg, #1a3a4a, #0f3b5c);
            color: white; margin-bottom: 24px; padding: 24px; border-radius: 14px;
        }
        .scanner-card h3 { margin-bottom: 4px; font-size: 18px; }
        .scanner-card p { font-size: 13px; opacity: 0.9; margin-bottom: 16px; }
        .scanner-input-group { display: flex; gap: 10px; flex-wrap: wrap; }
        .scanner-input {
            flex: 1; min-width: 250px; padding: 12px 16px;
            border: 2px solid rgba(255,255,255,0.3); border-radius: 10px;
            background: rgba(255,255,255,0.1); color: white; font-size: 14px;
            font-family: inherit; outline: none; transition: border-color 0.2s;
        }
        .scanner-input:focus { border-color: rgba(255,255,255,0.6); }
        .scanner-input::placeholder { color: rgba(255,255,255,0.5); }
        
        .scan-result-item {
            display: flex; align-items: center; gap: 10px; padding: 10px 14px;
            background: rgba(255,255,255,0.08); border-radius: 8px;
            margin-bottom: 6px; font-size: 13px;
        }
        .scan-result-item.pass { border-left: 3px solid #10b981; }
        .scan-result-item.warning { border-left: 3px solid #f59e0b; }
        .scan-result-item.fail { border-left: 3px solid #ef4444; }
        .scan-result-item .result-icon { font-size: 18px; width: 24px; text-align: center; }
        .scan-result-item.pass .result-icon { color: #10b981; }
        .scan-result-item.warning .result-icon { color: #f59e0b; }
        .scan-result-item.fail .result-icon { color: #ef4444; }
        
        .auto-answered-badge {
            display: inline-block; background: rgba(16,185,129,0.2); color: #10b981;
            padding: 2px 8px; border-radius: 10px; font-size: 10px; font-weight: 600;
            margin-left: 6px; animation: fadeIn 0.3s ease;
        }
        @keyframes fadeIn { from { opacity: 0; transform: scale(0.9); } to { opacity: 1; transform: scale(1); } }
        
        .progress-container { margin-bottom: 24px; }
        .progress-bar {
            background: #e2e8f0; height: 8px; border-radius: 4px; overflow: hidden;
        }
        body.dark .progress-bar { background: #334155; }
        .progress-fill {
            background: linear-gradient(90deg, var(--secondary), var(--success));
            height: 100%; border-radius: 4px; transition: width 0.4s ease;
        }
        .progress-text {
            display: flex; justify-content: space-between; font-size: 12px;
            color: var(--gray); margin-top: 6px;
        }
        
        .category-section {
            border: 2px solid #e2e8f0; border-radius: 12px; margin-bottom: 20px;
            overflow: hidden; transition: border-color 0.2s;
        }
        .category-section:hover { border-color: var(--secondary); }
        body.dark .category-section { border-color: #334155; }
        
        .category-header {
            padding: 16px 20px; display: flex; align-items: center; gap: 12px;
            cursor: pointer; transition: background 0.2s; user-select: none;
        }
        .category-header:hover { background: rgba(44,125,160,0.03); }
        .category-header .cat-icon {
            width: 42px; height: 42px; border-radius: 10px; display: flex;
            align-items: center; justify-content: center; font-size: 18px; color: white;
            flex-shrink: 0;
        }
        .category-header .cat-info { flex: 1; }
        .category-header .cat-title { font-weight: 600; font-size: 15px; }
        .category-header .cat-meta { font-size: 11px; color: var(--gray); }
        .category-header .cat-toggle { color: var(--gray); transition: transform 0.3s; }
        .category-header .cat-toggle.open { transform: rotate(180deg); }
        
        .category-body { padding: 0 20px 20px; display: none; }
        .category-body.open { display: block; }
        
        .question-item {
            padding: 16px 0; border-bottom: 1px solid #f1f5f9;
            transition: background 0.2s;
        }
        .question-item.auto-answered-highlight { background: rgba(16,185,129,0.03); border-radius: 8px; padding: 16px 12px; }
        body.dark .question-item { border-bottom-color: #334155; }
        .question-item:last-child { border-bottom: none; }
        
        .question-text { font-weight: 500; font-size: 14px; margin-bottom: 4px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
        .question-guidance { font-size: 11px; color: var(--gray); margin-bottom: 10px; }
        .question-reference {
            display: inline-block; font-size: 10px; background: rgba(44,125,160,0.1);
            color: var(--secondary); padding: 2px 8px; border-radius: 10px;
            margin-bottom: 10px;
        }
        
        .response-options {
            display: flex; gap: 8px; flex-wrap: wrap;
        }
        .response-option {
            display: flex; align-items: center; gap: 5px; padding: 8px 14px;
            border: 2px solid #e2e8f0; border-radius: 8px; cursor: pointer;
            transition: all 0.2s; font-size: 12px; font-weight: 500;
        }
        body.dark .response-option { border-color: #334155; }
        .response-option:hover { border-color: var(--secondary); background: rgba(44,125,160,0.04); }
        .response-option:has(input:checked) {
            border-color: var(--secondary); background: rgba(44,125,160,0.08);
            font-weight: 600;
        }
        .response-option input[type="radio"] { accent-color: var(--secondary); cursor: pointer; }
        
        .btn {
            display: inline-flex; align-items: center; gap: 8px;
            padding: 10px 22px; border: none; border-radius: 10px;
            font-weight: 600; font-size: 14px; cursor: pointer; transition: all 0.2s;
            font-family: inherit; text-decoration: none; white-space: nowrap;
        }
        .btn-primary { background: var(--primary); color: white; }
        .btn-success { background: var(--success); color: white; }
        .btn-white { background: rgba(255,255,255,0.2); color: white; }
        .btn-white:hover { background: rgba(255,255,255,0.3); }
        .btn-lg { padding: 16px 36px; font-size: 16px; }
        .btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,0.15); }
        .btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
        
        .alert {
            padding: 16px 20px; border-radius: 10px; margin-bottom: 20px;
            font-weight: 500; font-size: 14px;
        }
        .alert-success { background: rgba(16,185,129,0.1); color: #065f46; border: 1px solid rgba(16,185,129,0.3); }
        .alert-error { background: rgba(239,68,68,0.1); color: #991b1b; border: 1px solid rgba(239,68,68,0.3); }
        body.dark .alert-success { color: #6ee7b7; }
        body.dark .alert-error { color: #fca5a5; }
        .alert-info { background: rgba(59,130,246,0.1); color: #1e40af; border: 1px solid rgba(59,130,246,0.3); }
        body.dark .alert-info { color: #93c5fd; }
        
        .sticky-bottom {
            position: sticky; bottom: 20px; z-index: 10;
            background: white; padding: 16px 20px; border-radius: 12px;
            box-shadow: 0 -4px 20px rgba(0,0,0,0.1); margin-top: 20px;
            display: flex; justify-content: space-between; align-items: center;
            flex-wrap: wrap; gap: 12px;
        }
        body.dark .sticky-bottom { background: #1e293b; }
        
        .score-preview { text-align: center; }
        .score-preview .big-score { font-size: 36px; font-weight: 800; }
        
        @media (max-width: 768px) {
            .container { padding: 12px; }
            .card { padding: 16px; }
            .response-options { flex-direction: column; }
            .sticky-bottom { flex-direction: column; text-align: center; }
            .scanner-input-group { flex-direction: column; }
        }
    </style>
</head>
<body class="<?php echo $theme; ?>">
    <nav class="navbar">
        <div class="nav-container">
            <a href="dashboard.php" class="logo"><i class="fas fa-shield-alt"></i>Soul Guard</a>
            <div class="nav-links">
                <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</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>
        </div>
    </nav>
    
    <div class="container">
        <div class="card">
            <div class="page-header">
                <h1><i class="fas fa-clipboard-check" style="color: var(--secondary);"></i> DPA Compliance Self-Assessment</h1>
                <p>Answer all questions honestly based on your current practices. This assessment is based on the <strong>Kenya Data Protection Act, 2019</strong> and ODPC guidelines.</p>
            </div>
            
            <?php if ($message): ?>
                <div class="alert alert-<?php echo $messageType; ?>">
                    <i class="fas fa-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                    <?php echo $message; ?>
                </div>
            <?php endif; ?>
            
            <!-- WEBSITE AUTO-SCAN CARD -->
            <div class="scanner-card">
                <h3><i class="fas fa-magic"></i> Auto-Scan Your Website</h3>
                <p>Enter your website URL below. We'll automatically scan and answer the <strong>Website & Digital Compliance</strong> questions for you based on actual findings.</p>
                <div class="scanner-input-group">
                    <input type="url" id="websiteUrl" class="scanner-input" 
                           placeholder="https://your-website.com" 
                           value="<?php echo htmlspecialchars($org['website'] ?? ''); ?>">
                    <button type="button" class="btn btn-white" onclick="scanWebsite()" id="scanBtn">
                        <i class="fas fa-search"></i> Scan Website
                    </button>
                </div>
                <div id="scanLoading" style="margin-top: 16px; display: none; text-align: center;">
                    <i class="fas fa-spinner fa-spin" style="font-size: 20px;"></i>
                    <p style="margin-top: 6px; font-size: 12px; opacity: 0.8;">Scanning website... This may take up to 15 seconds.</p>
                </div>
                <div id="scanResults" style="margin-top: 16px; display: none;"></div>
            </div>
            
            <div class="progress-container">
                <div class="progress-bar">
                    <div class="progress-fill" id="progressBar" style="width: 0%;"></div>
                </div>
                <div class="progress-text">
                    <span id="progressLabel">0% complete</span>
                    <span id="answeredCount">0 of <?php echo $totalQuestionCount; ?> questions answered</span>
                </div>
            </div>
            
            <?php if (!empty($previousResponses)): ?>
                <div class="alert alert-info" style="font-size: 13px;">
                    <i class="fas fa-info-circle"></i>
                    You have a previous assessment from today. Your previous answers are pre-selected below.
                </div>
            <?php endif; ?>
            
            <form method="POST" id="assessmentForm">
                <?php 
                $catIndex = 0;
                foreach ($questionsByCategory as $category => $questions): 
                    $config = $categoryConfig[$category] ?? ['icon' => 'question', 'color' => '#64748b', 'points' => ''];
                    $catId = 'cat_' . preg_replace('/[^a-zA-Z0-9]/', '_', $category);
                    $catIndex++;
                ?>
                <div class="category-section" id="<?php echo $catId; ?>_section">
                    <div class="category-header" onclick="toggleCategory('<?php echo $catId; ?>')">
                        <div class="cat-icon" style="background: <?php echo $config['color']; ?>;">
                            <i class="fas fa-<?php echo $config['icon']; ?>"></i>
                        </div>
                        <div class="cat-info">
                            <div class="cat-title"><?php echo htmlspecialchars($category); ?></div>
                            <div class="cat-meta"><?php echo count($questions); ?> questions • <?php echo $config['points']; ?></div>
                        </div>
                        <i class="fas fa-chevron-down cat-toggle <?php echo $catIndex === 1 ? 'open' : ''; ?>" id="<?php echo $catId; ?>_toggle"></i>
                    </div>
                    <div class="category-body <?php echo $catIndex === 1 ? 'open' : ''; ?>" id="<?php echo $catId; ?>_body">
                        <?php foreach ($questions as $q): 
                            $qId = $q['id'];
                            $prevValue = $previousResponses[$qId] ?? '';
                            // Check if this is a website compliance question (IDs 47-50)
                            $isWebsiteQuestion = ($qId >= 47 && $qId <= 50);
                        ?>
                        <div class="question-item" id="question_<?php echo $qId; ?>">
                            <div class="question-text">
                                <?php echo htmlspecialchars($q['question']); ?>
                            </div>
                            <?php if (!empty($q['guidance'])): ?>
                                <div class="question-guidance">💡 <?php echo htmlspecialchars($q['guidance']); ?></div>
                            <?php endif; ?>
                            <?php if (!empty($q['kenya_dpa_reference'])): ?>
                                <div class="question-reference">📜 <?php echo htmlspecialchars($q['kenya_dpa_reference']); ?></div>
                            <?php endif; ?>
                            <div class="response-options">
                                <label class="response-option">
                                    <input type="radio" name="q_<?php echo $qId; ?>" value="yes" <?php echo $prevValue === 'yes' ? 'checked' : ''; ?> onchange="updateProgress()">
                                    <span>✅ Yes</span>
                                </label>
                                <label class="response-option">
                                    <input type="radio" name="q_<?php echo $qId; ?>" value="partially" <?php echo $prevValue === 'partially' ? 'checked' : ''; ?> onchange="updateProgress()">
                                    <span>🔶 Partially</span>
                                </label>
                                <label class="response-option">
                                    <input type="radio" name="q_<?php echo $qId; ?>" value="in_progress" <?php echo $prevValue === 'in_progress' ? 'checked' : ''; ?> onchange="updateProgress()">
                                    <span>🔄 In Progress</span>
                                </label>
                                <label class="response-option">
                                    <input type="radio" name="q_<?php echo $qId; ?>" value="no" <?php echo $prevValue === 'no' ? 'checked' : ''; ?> onchange="updateProgress()">
                                    <span>❌ No</span>
                                </label>
                                <label class="response-option">
                                    <input type="radio" name="q_<?php echo $qId; ?>" value="not_applicable" <?php echo $prevValue === 'not_applicable' ? 'checked' : ''; ?> onchange="updateProgress()">
                                    <span>N/A</span>
                                </label>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
                
                <div class="sticky-bottom">
                    <div class="score-preview">
                        <span style="font-size: 12px; color: var(--gray);">Estimated Score</span>
                        <div class="big-score" id="estimatedScore" style="color: var(--secondary);">--%</div>
                    </div>
                    <div style="display: flex; gap: 12px; flex-wrap: wrap;">
                        <button type="button" class="btn btn-primary btn-lg" onclick="window.scrollTo({top: 0, behavior: 'smooth'});" style="background: var(--primary);">
                            <i class="fas fa-arrow-up"></i> Top
                        </button>
                        <button type="submit" class="btn btn-success btn-lg">
                            <i class="fas fa-check-circle"></i> Submit Assessment & Calculate Score
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        // Toggle category sections
        function toggleCategory(catId) {
            const body = document.getElementById(catId + '_body');
            const toggle = document.getElementById(catId + '_toggle');
            if (body && toggle) {
                body.classList.toggle('open');
                toggle.classList.toggle('open');
            }
        }
        
        // =============================================
        // WEBSITE SCANNER
        // =============================================
        async function scanWebsite() {
            const urlInput = document.getElementById('websiteUrl');
            const url = urlInput.value.trim();
            
            if (!url) {
                alert('Please enter a website URL to scan');
                urlInput.focus();
                return;
            }
            
            const scanBtn = document.getElementById('scanBtn');
            const scanResults = document.getElementById('scanResults');
            const scanLoading = document.getElementById('scanLoading');
            
            // Show loading
            scanBtn.disabled = true;
            scanBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Scanning...';
            scanResults.style.display = 'none';
            scanLoading.style.display = 'block';
            
            try {
                const response = await fetch('api/scan-website.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'url=' + encodeURIComponent(url)
                });
                
                const data = await response.json();
                
                scanLoading.style.display = 'none';
                scanResults.style.display = 'block';
                
                if (data.success) {
                    // Build results HTML
                    let html = '<div style="margin-bottom: 12px; font-weight: 600; font-size: 14px;">';
                    const scoreColor = data.overall_website_score >= 80 ? '#10b981' : 
                                      (data.overall_website_score >= 50 ? '#f59e0b' : '#ef4444');
                    html += '📊 Website Compliance Score: <span style="color: ' + scoreColor + '; font-size: 18px;">' + 
                            data.overall_website_score + '%</span> - <span style="color: ' + scoreColor + ';">' + 
                            data.overall_status + '</span>';
                    html += '</div>';
                    
                    // Individual checks
                    const checkOrder = ['https', 'privacy_policy', 'cookie_consent', 'web_forms'];
                    const checkLabels = {
                        'https': 'HTTPS/TLS Encryption',
                        'privacy_policy': 'Privacy Policy',
                        'cookie_consent': 'Cookie Consent',
                        'web_forms': 'Web Form Security'
                    };
                    
                    for (const key of checkOrder) {
                        const check = data.checks[key];
                        if (!check) continue;
                        
                        const icon = check.status === 'pass' ? 'check-circle' : 
                                    (check.status === 'warning' ? 'exclamation-triangle' : 'times-circle');
                        
                        html += '<div class="scan-result-item ' + check.status + '">';
                        html += '<span class="result-icon"><i class="fas fa-' + icon + '"></i></span>';
                        html += '<div style="flex: 1;"><strong>' + check.label + '</strong><br><small style="opacity: 0.85;">' + check.finding + '</small></div>';
                        html += '<span style="font-weight: 700; font-size: 14px;">' + check.score + '%</span>';
                        html += '</div>';
                    }
                    
                    if (data.checks.https && data.checks.https.detail) {
                        html += '<div style="font-size: 11px; opacity: 0.7; margin-top: 8px;">' + data.checks.https.detail + '</div>';
                    }
                    
                    scanResults.innerHTML = html;
                    
                    // Auto-answer website compliance questions
                    autoAnswerWebsiteQuestions(data);
                    
                } else {
                    scanResults.innerHTML = '<div style="color: #fca5a5; padding: 10px;"><i class="fas fa-exclamation-circle"></i> ' + 
                        (data.message || 'Scan failed. Please check the URL and try again.') + '</div>';
                }
            } catch (error) {
                scanLoading.style.display = 'none';
                scanResults.style.display = 'block';
                scanResults.innerHTML = '<div style="color: #fca5a5; padding: 10px;"><i class="fas fa-times-circle"></i> Network error. Please check your connection and try again.</div>';
            } finally {
                scanBtn.disabled = false;
                scanBtn.innerHTML = '<i class="fas fa-search"></i> Scan Website';
            }
        }
        
        function autoAnswerWebsiteQuestions(scanData) {
            // Map scan results to question IDs (47-50 are Website & Digital Compliance)
            const questionMap = {
                47: 'https',           // HTTPS/TLS question
                48: 'privacy_policy',   // Privacy policy question
                49: 'cookie_consent',   // Cookie consent question
                50: 'web_forms'         // Web forms question
            };
            
            let answeredCount = 0;
            
            for (const [questionId, checkKey] of Object.entries(questionMap)) {
                const check = scanData.checks[checkKey];
                if (!check) continue;
                
                const score = check.score;
                let answer = 'no';
                
                if (score >= 80) answer = 'yes';
                else if (score >= 50) answer = 'partially';
                else if (score >= 20) answer = 'in_progress';
                else answer = 'no';
                
                // Find and select the radio button
                const radioName = 'q_' + questionId;
                const radio = document.querySelector('input[name="' + radioName + '"][value="' + answer + '"]');
                
                if (radio) {
                    radio.checked = true;
                    answeredCount++;
                    
                    // Highlight the question
                    const questionItem = document.getElementById('question_' + questionId);
                    if (questionItem) {
                        questionItem.classList.add('auto-answered-highlight');
                        
                        // Remove existing badge
                        const existingBadge = questionItem.querySelector('.auto-answered-badge');
                        if (existingBadge) existingBadge.remove();
                        
                        // Add auto-answered badge
                        const questionText = questionItem.querySelector('.question-text');
                        if (questionText) {
                            const badge = document.createElement('span');
                            badge.className = 'auto-answered-badge';
                            badge.innerHTML = '🤖 Auto-detected';
                            badge.title = 'Answer automatically set based on website scan results';
                            questionText.appendChild(badge);
                        }
                    }
                }
            }
            
            // Update progress after auto-answering
            updateProgress();
            
            // Scroll to Website section to show results
            const websiteSection = document.getElementById('cat_Website___Digital_Compliance_section');
            if (websiteSection) {
                setTimeout(() => {
                    websiteSection.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }, 300);
            }
            
            // Show notification
            if (answeredCount > 0) {
                const scanResults = document.getElementById('scanResults');
                const notice = document.createElement('div');
                notice.style.cssText = 'margin-top: 10px; padding: 8px 12px; background: rgba(16,185,129,0.2); border-radius: 8px; font-size: 12px;';
                notice.innerHTML = '✅ <strong>' + answeredCount + ' question(s)</strong> auto-answered based on scan results. Scroll down to Website & Digital Compliance section to review.';
                scanResults.appendChild(notice);
            }
        }
        
        // =============================================
        // PROGRESS TRACKING
        // =============================================
        const form = document.getElementById('assessmentForm');
        const totalQuestions = <?php echo $totalQuestionCount; ?>;
        
        function updateProgress() {
            const answered = new Set();
            form.querySelectorAll('input[type="radio"]:checked').forEach(input => {
                answered.add(input.name);
            });
            
            const count = answered.size;
            const progress = totalQuestions > 0 ? Math.round((count / totalQuestions) * 100) : 0;
            
            document.getElementById('progressBar').style.width = progress + '%';
            document.getElementById('progressLabel').textContent = progress + '% complete';
            document.getElementById('answeredCount').textContent = count + ' of ' + totalQuestions + ' questions answered';
            
            // Estimate score
            if (count > 0) {
                let estimatedScore = 0;
                let maxEstimate = 0;
                
                form.querySelectorAll('input[type="radio"]:checked').forEach(input => {
                    const value = input.value;
                    let score = 0;
                    switch(value) {
                        case 'yes': score = 100; break;
                        case 'partially': score = 60; break;
                        case 'in_progress': score = 35; break;
                        case 'no': score = 0; break;
                        case 'not_applicable': score = 100; break;
                    }
                    estimatedScore += score;
                    maxEstimate += 100;
                });
                
                const avgScore = maxEstimate > 0 ? Math.round((estimatedScore / maxEstimate) * 100) : 0;
                const scoreEl = document.getElementById('estimatedScore');
                scoreEl.textContent = avgScore + '%';
                
                if (avgScore >= 80) scoreEl.style.color = '#10b981';
                else if (avgScore >= 60) scoreEl.style.color = '#f59e0b';
                else if (avgScore >= 40) scoreEl.style.color = '#f97316';
                else scoreEl.style.color = '#ef4444';
            }
        }
        
        // Add onchange to all radios for progress tracking
        document.addEventListener('DOMContentLoaded', function() {
            form.querySelectorAll('input[type="radio"]').forEach(radio => {
                radio.addEventListener('change', updateProgress);
            });
            updateProgress();
        });
        
        // Allow pressing Enter in URL input to trigger scan
        document.getElementById('websiteUrl').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                scanWebsite();
            }
        });
    </script>
</body>
</html>