<?php
// member/chatbot-api.php — Soul Guard DPA Compliance Chatbot (FREE - No External API)
// Uses keyword matching against a local knowledge base stored in your database.
require_once '../config.php';
requireLogin();

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'reply' => 'Invalid request method.']);
    exit;
}

$body    = json_decode(file_get_contents('php://input'), true);
$message = strtolower(trim($body['message'] ?? ''));
$context = $body['context'] ?? [];

if (empty($message)) {
    echo json_encode(['success' => false, 'reply' => 'Empty message.']);
    exit;
}

$pdo = getDBConnection();

// =============================================
// ENSURE KNOWLEDGE BASE TABLE EXISTS & IS SEEDED
// =============================================
ensureKnowledgeBase($pdo);

// =============================================
// LIVE CONTEXT FROM DATABASE (personalised answers)
// =============================================
$userId          = $_SESSION['user_id'];
$orgId           = $context['org_id'] ?? 0;
$complianceScore = (int)($context['compliance_score'] ?? 0);
$riskLevel       = $context['risk_level'] ?? 'Unknown';
$openBreaches    = (int)($context['open_breaches'] ?? 0);
$totalDpias      = (int)($context['total_dpias'] ?? 0);
$pendingTasks    = (int)($context['pending_tasks'] ?? 0);
$orgName         = $context['org_name'] ?? 'your organization';

// =============================================
// HANDLE CONTEXTUAL SHORTCUTS FIRST
// (questions about the user's own data)
// =============================================
$contextualReply = handleContextualQuery($message, [
    'compliance_score' => $complianceScore,
    'risk_level'       => $riskLevel,
    'open_breaches'    => $openBreaches,
    'total_dpias'      => $totalDpias,
    'pending_tasks'    => $pendingTasks,
    'org_name'         => $orgName,
], $pdo, $orgId);

if ($contextualReply) {
    logChat($pdo, $userId, $message, $contextualReply);
    echo json_encode(['success' => true, 'reply' => $contextualReply]);
    exit;
}

// =============================================
// KNOWLEDGE BASE SEARCH
// =============================================
$reply = searchKnowledgeBase($pdo, $message);

logChat($pdo, $userId, $message, $reply);
echo json_encode(['success' => true, 'reply' => $reply]);
exit;


// =============================================
// FUNCTIONS
// =============================================

/**
 * Handle questions about the user's own compliance data
 */
function handleContextualQuery(string $msg, array $ctx, $pdo, int $orgId): ?string {
    $score  = $ctx['compliance_score'];
    $risk   = $ctx['risk_level'];
    $org    = $ctx['org_name'] ?: 'your organization';
    $breaches = $ctx['open_breaches'];
    $dpias  = $ctx['total_dpias'];
    $tasks  = $ctx['pending_tasks'];

    // Score questions
    if (matchesAny($msg, ['my score','my compliance','how am i doing','current score','our score','compliance status'])) {
        $advice = $score >= 80
            ? "Great work! Keep maintaining your controls and schedule quarterly reviews."
            : ($score >= 60
                ? "You're on the right track. Focus on completing pending tasks and resolving any open breaches."
                : ($score >= 40
                    ? "There are significant gaps to address. Start with resolving open breaches and completing a full DPIA."
                    : "Immediate action is needed. Complete your DPA Assessment first to identify all gaps."));

        return "📊 **{$org}'s Compliance Score: {$score}% ({$risk} Risk)**\n\n{$advice}\n\n" .
               "• Open Breaches: **{$breaches}** " . ($breaches > 0 ? "⚠️ (each costs you up to 5 points)" : "✅") . "\n" .
               "• Completed DPIAs: **{$dpias}**\n" .
               "• Pending Tasks: **{$tasks}**\n\n" .
               "💡 Type **\"how to improve score\"** for a personalised action plan.";
    }

    // Improve score
    if (matchesAny($msg, ['improve score','increase score','boost score','how to improve','raise my score','get better score'])) {
        $tips = [];
        if ($breaches > 0)  $tips[] = "🔴 **Resolve {$breaches} open breach(es)** — this alone can recover up to " . min(25, $breaches * 5) . " points";
        if ($dpias == 0)    $tips[] = "🟡 **Complete at least one DPIA** — adds up to 10 points";
        $tips[] = "🟡 **Enable encryption** — adds 10 points to your Data Protection score";
        $tips[] = "🟡 **Enable MFA** — adds 6 points";
        $tips[] = "🟢 **Complete ODPC compliance tasks** — improves your ODPC Alignment score (up to 15 pts)";
        $tips[] = "🟢 **Add your ODPC registration number** — adds 10 points";

        return "🎯 **Action Plan to Improve Your Score ({$score}%)**\n\n" . implode("\n", $tips) .
               "\n\n👉 Start with the red items — they have the biggest impact.";
    }

    // Breach questions
    if (matchesAny($msg, ['my breach','open breach','my breaches','breach status','how many breach'])) {
        if ($breaches === 0) {
            return "✅ **No open breaches** — great news! Your breach readiness score is at full points.\n\nRemember to keep your incident response plan updated and conduct regular security drills.";
        }
        return "⚠️ **You have {$breaches} open breach(es)** currently reducing your score by " . min(25, $breaches * 5) . " points.\n\n" .
               "**Required actions:**\n" .
               "• Notify ODPC within **72 hours** of discovery (DPA Section 43)\n" .
               "• Document the nature of breach, data affected, and remediation steps\n" .
               "• Notify affected data subjects if there is high risk to their rights\n\n" .
               "👉 Go to **Breach Management** to resolve these now.";
    }

    // DPIA questions about their own record
    if (matchesAny($msg, ['my dpia','how many dpia','dpia status','our dpias'])) {
        if ($dpias === 0) {
            return "📋 **You have not completed any DPIAs yet.**\n\nDPIAs are mandatory for high-risk processing under **DPA Section 41(5)**. Not having one when required can result in ODPC enforcement action.\n\n👉 Go to **DPIA Automation** to generate your first one — it takes about 15 minutes.";
        }
        return "✅ **{$dpias} DPIA(s) completed** for {$org}.\n\nGood work! Make sure to:\n• Review DPIAs annually or when processing activities change\n• Cover all high-risk processing activities\n• Document outcomes and mitigation measures\n\n👉 Visit **DPIA Records** to review them.";
    }

    // Tasks
    if (matchesAny($msg, ['my tasks','pending tasks','outstanding tasks','tasks remaining'])) {
        if ($tasks === 0) {
            return "✅ **No pending compliance tasks!** You're all caught up.\n\nConsider scheduling a proactive review in the next 30 days to stay ahead.";
        }
        return "📋 **{$tasks} pending compliance task(s)** need your attention.\n\nCompleting these tasks improves your **ODPC Alignment** score. Prioritise any tasks marked as mandatory ODPC requirements.\n\n👉 Visit the **Tasks** section to action them.";
    }

    return null; // No contextual match — fall through to knowledge base
}

/**
 * Search the knowledge base using keyword scoring
 */
function searchKnowledgeBase($pdo, string $msg): string {
    // Load all KB entries
    $stmt = $pdo->query("SELECT * FROM chatbot_knowledge ORDER BY priority DESC");
    $entries = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($entries)) {
        return getFallbackResponse($msg);
    }

    // Tokenise the user message
    $words = tokenise($msg);

    $bestScore = 0;
    $bestEntry = null;

    foreach ($entries as $entry) {
        $score = 0;
        $keywords = json_decode($entry['keywords'], true) ?: [];
        $phrases  = json_decode($entry['phrases'],  true) ?: [];

        // Exact phrase match (highest weight)
        foreach ($phrases as $phrase) {
            if (str_contains($msg, strtolower($phrase))) {
                $score += 15;
            }
        }

        // Keyword match
        foreach ($keywords as $kw) {
            if (in_array(strtolower($kw), $words)) {
                $score += 3;
            }
            // Partial match for compound words
            foreach ($words as $w) {
                if (strlen($w) > 3 && str_contains(strtolower($kw), $w)) {
                    $score += 1;
                }
            }
        }

        // Category boost
        $categoryWords = tokenise($entry['category']);
        foreach ($categoryWords as $cw) {
            if (in_array($cw, $words)) $score += 2;
        }

        if ($score > $bestScore) {
            $bestScore = $score;
            $bestEntry = $entry;
        }
    }

    // Minimum threshold to return a match
    if ($bestScore >= 3 && $bestEntry) {
        // Track usage
        try {
            $pdo->prepare("UPDATE chatbot_knowledge SET hit_count = hit_count + 1 WHERE id = ?")
                ->execute([$bestEntry['id']]);
        } catch (Exception $e) {}

        return $bestEntry['answer'];
    }

    return getFallbackResponse($msg);
}

/**
 * Fallback when no KB match found
 */
function getFallbackResponse(string $msg): string {
    $fallbacks = [
        "I don't have a specific answer for that yet, but here's what I can help with:\n\n• **DPIA** — when and how to conduct one\n• **Breach notification** — 72-hour ODPC rule\n• **ODPC registration** — steps and requirements\n• **Data subject rights** — access, erasure, objection\n• **DPO requirements** — when you need one\n• **My compliance score** — personalised analysis\n\nTry rephrasing your question or type one of the topics above.",
        "That's a great question! I'm still learning. For now, try asking about:\n\n• **\"What is a DPIA?\"**\n• **\"How do I register with ODPC?\"**\n• **\"72-hour breach rule\"**\n• **\"Data subject rights\"**\n• **\"My compliance score\"**",
        "I'm not sure about that specific topic. For complex legal matters, consult a certified DPA practitioner. For platform questions, contact Soul Guard support.\n\nI can answer questions on Kenya DPA 2019, breach management, DPIAs, and your compliance dashboard.",
    ];
    return $fallbacks[array_rand($fallbacks)];
}

function matchesAny(string $msg, array $patterns): bool {
    foreach ($patterns as $p) {
        if (str_contains($msg, $p)) return true;
    }
    return false;
}

function tokenise(string $text): array {
    $text = strtolower($text);
    $text = preg_replace('/[^a-z0-9\s]/', ' ', $text);
    $words = explode(' ', $text);
    // Remove common stop words
    $stopWords = ['the','a','an','is','it','in','on','at','to','for','of','and','or','but','what','how','when','where','who','why','do','i','my','me','we','our','can','should','need','want','please','tell','about','does','are','am','this','that','these','those','with','has','have','had','be','been'];
    return array_values(array_filter($words, fn($w) => strlen($w) > 2 && !in_array($w, $stopWords)));
}

function logChat($pdo, int $userId, string $msg, string $reply): void {
    try {
        $pdo->exec("CREATE TABLE IF NOT EXISTS chatbot_logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            message TEXT NOT NULL,
            reply TEXT NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )");
        $pdo->prepare("INSERT INTO chatbot_logs (user_id, message, reply) VALUES (?,?,?)")
            ->execute([$userId, $msg, $reply]);
    } catch (Exception $e) {}
}

/**
 * Create and seed the knowledge base table
 */
function ensureKnowledgeBase($pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS chatbot_knowledge (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        category TEXT NOT NULL,
        topic TEXT NOT NULL,
        keywords TEXT NOT NULL,
        phrases TEXT NOT NULL,
        answer TEXT NOT NULL,
        priority INTEGER DEFAULT 1,
        hit_count INTEGER DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    // Only seed if empty
    $count = $pdo->query("SELECT COUNT(*) FROM chatbot_knowledge")->fetchColumn();
    if ($count > 0) return;

    $entries = getKnowledgeBaseEntries();
    $stmt = $pdo->prepare("INSERT INTO chatbot_knowledge (category, topic, keywords, phrases, answer, priority) VALUES (?,?,?,?,?,?)");
    foreach ($entries as $e) {
        $stmt->execute([
            $e['category'],
            $e['topic'],
            json_encode($e['keywords']),
            json_encode($e['phrases']),
            $e['answer'],
            $e['priority'] ?? 1,
        ]);
    }
}

/**
 * The full DPA 2019 knowledge base
 */
function getKnowledgeBaseEntries(): array {
    return [

        // ── DPIA ──────────────────────────────────────
        [
            'category' => 'DPIA',
            'topic'    => 'What is a DPIA',
            'keywords' => ['dpia','data','protection','impact','assessment','privacy','impact'],
            'phrases'  => ['what is a dpia','what is dpia','dpia mean','dpia stands','data protection impact'],
            'priority' => 3,
            'answer'   => "📋 **What is a DPIA (Data Protection Impact Assessment)?**\n\nA DPIA is a process to identify and minimise the data protection risks of a project or processing activity.\n\n**Under Kenya DPA 2019 (Section 41(5)), a DPIA is MANDATORY when processing is:**\n• Likely to result in high risk to individuals\n• Involves large-scale processing of sensitive data\n• Involves systematic monitoring of public areas\n• Uses new technologies\n• Involves automated decision-making or profiling\n\n**A DPIA must include:**\n1. Description of the processing and its purposes\n2. Assessment of the necessity and proportionality\n3. Assessment of risks to data subjects\n4. Measures to address those risks\n\n👉 Use Soul Guard's **DPIA Automation** tool to generate one in minutes.",
        ],
        [
            'category' => 'DPIA',
            'topic'    => 'When is a DPIA required',
            'keywords' => ['dpia','required','mandatory','need','when','must','high risk','obligation'],
            'phrases'  => ['when do i need a dpia','when is dpia required','do i need a dpia','dpia mandatory','dpia required for'],
            'priority' => 3,
            'answer'   => "⚖️ **When is a DPIA Required? (DPA Section 41(5))**\n\nYou **must** conduct a DPIA before starting any processing that is:\n\n🔴 **Always required:**\n• Systematic and extensive profiling with automated decisions\n• Large-scale processing of special category data (health, biometrics, finance)\n• Systematic monitoring of publicly accessible areas (CCTV)\n\n🟡 **Likely required if you:**\n• Process children's data at scale\n• Match or combine datasets from multiple sources\n• Process data in innovative ways using new technology\n• Transfer personal data outside Kenya (DPA Section 48)\n\n✅ **Good news:** Soul Guard's DPIA tool walks you through all of this step by step.\n\n**Penalty for skipping:** ODPC can impose fines and enforcement notices.",
        ],

        // ── BREACH NOTIFICATION ───────────────────────
        [
            'category' => 'Breach',
            'topic'    => '72-hour breach notification rule',
            'keywords' => ['breach','notification','72','hours','report','notify','odpc','incident','data breach'],
            'phrases'  => ['72 hour','breach notification','notify odpc','report breach','data breach rule','breach timeline'],
            'priority' => 3,
            'answer'   => "🚨 **Data Breach Notification Rules (DPA Section 43)**\n\n**To ODPC (Office of Data Protection Commissioner):**\n• Must notify within **72 hours** of becoming aware of the breach\n• If notification is delayed, you must explain why\n• Report even if investigation is not yet complete\n\n**To Affected Data Subjects:**\n• Required if the breach is likely to result in **high risk** to their rights and freedoms\n• Must be done **without undue delay**\n• Must clearly describe the breach and steps taken\n\n**What to include in your notification:**\n1. Nature of the breach\n2. Categories and approximate number of people affected\n3. Categories and volume of data records affected\n4. Name and contact of your DPO\n5. Likely consequences of the breach\n6. Measures taken or proposed to address it\n\n⚠️ **Failure to notify** ODPC can result in enforcement action and fines.\n\n👉 Use **Breach Workflow** in Soul Guard to manage this process.",
        ],
        [
            'category' => 'Breach',
            'topic'    => 'What counts as a data breach',
            'keywords' => ['breach','what','counts','definition','example','types','incident'],
            'phrases'  => ['what is a breach','what counts as breach','is this a breach','types of breach','data breach example'],
            'priority' => 2,
            'answer'   => "🔍 **What Counts as a Data Breach?**\n\nA personal data breach is any security incident leading to **accidental or unlawful:**\n\n• **Destruction** of personal data\n• **Loss** of personal data\n• **Alteration** of personal data\n• **Unauthorised disclosure** of personal data\n• **Unauthorised access** to personal data\n\n**Examples:**\n• Laptop with customer data stolen\n• Email sent to wrong recipient containing personal info\n• Ransomware encrypting your database\n• Employee accessing records without authorisation\n• Paper files left in a public place\n• Accidentally deleting records without backup\n\n**Not all breaches require ODPC notification** — only those likely to result in risk to individuals. Low-risk breaches should still be **documented internally**.\n\n👉 When in doubt, report it. It is better to over-report than miss the 72-hour window.",
        ],

        // ── ODPC REGISTRATION ─────────────────────────
        [
            'category' => 'ODPC',
            'topic'    => 'ODPC registration process',
            'keywords' => ['odpc','register','registration','certificate','data controller','data processor','application'],
            'phrases'  => ['how to register','odpc registration','register with odpc','registration process','how do i register','registration certificate'],
            'priority' => 3,
            'answer'   => "🏛️ **ODPC Registration — Step by Step**\n\nUnder **DPA Section 18**, all data controllers and processors processing personal data in Kenya must register with the ODPC.\n\n**Steps to register:**\n\n1️⃣ **Visit** odpc.go.ke and create an account\n2️⃣ **Complete** the online registration form:\n   - Organisation details\n   - Nature of data processing\n   - Categories of personal data processed\n   - Security measures in place\n   - DPO details (if applicable)\n3️⃣ **Pay** the registration fee (varies by organisation size)\n4️⃣ **Submit** and await approval (typically 2–4 weeks)\n5️⃣ **Receive** your Data Controller/Processor Certificate\n\n**Annual renewal** is required — Soul Guard's reminders will alert you before expiry.\n\n⚠️ **Operating without registration** is an offence under the DPA.\n\n💡 Soul Guard's **ODPC Registration** service can handle this entire process for you.",
        ],
        [
            'category' => 'ODPC',
            'topic'    => 'ODPC registration fees',
            'keywords' => ['fee','cost','price','pay','registration','odpc','how much','charges'],
            'phrases'  => ['registration fee','how much does it cost','odpc fee','cost of registration','registration charges'],
            'priority' => 2,
            'answer'   => "💰 **ODPC Registration Fees**\n\nFees are set by the ODPC and vary based on your organisation type. As a guide:\n\n• **Small organisations / startups:** Lower tier fee\n• **Medium organisations:** Mid-tier fee\n• **Large organisations / multinationals:** Higher tier fee\n\n⚠️ **Check the official ODPC website (odpc.go.ke)** for the current fee schedule, as these can change.\n\n**Payment is made online** during the registration process.\n\n💡 Contact Soul Guard's **ODPC Registration Service** — we can guide you through the exact fees for your organisation size and type.",
        ],

        // ── DPO ───────────────────────────────────────
        [
            'category' => 'DPO',
            'topic'    => 'DPO requirements',
            'keywords' => ['dpo','data protection officer','appoint','need','require','officer','designate'],
            'phrases'  => ['do i need a dpo','dpo required','data protection officer','appoint a dpo','when do i need dpo','dpo requirement'],
            'priority' => 3,
            'answer'   => "👤 **Data Protection Officer (DPO) Requirements (DPA Section 24)**\n\nYou **must appoint a DPO** if your organisation:\n\n🔴 **Mandatory cases:**\n• Processes personal data on a large scale\n• Carries out systematic monitoring of individuals\n• Processes special categories of data (health, biometrics, financial) at scale\n• Is a public authority or government body\n\n🟡 **Recommended (even if not mandatory):**\n• Any organisation regularly dealing with sensitive personal data\n\n**Your DPO's responsibilities:**\n• Advise on DPA compliance obligations\n• Monitor compliance with the DPA\n• Be the point of contact with the ODPC\n• Conduct or oversee DPIAs\n• Train staff on data protection\n\n**DPO must:**\n• Have expert knowledge of data protection law\n• Be independent — cannot be penalised for doing their job\n• Be accessible to data subjects\n\n💡 Don't have one? Soul Guard offers **Outsourced DPO services** — a cost-effective solution for SMEs.",
        ],

        // ── DATA SUBJECT RIGHTS ───────────────────────
        [
            'category' => 'Data Subject Rights',
            'topic'    => 'Data subject rights overview',
            'keywords' => ['rights','subject','access','erasure','delete','portability','object','rectify','correction','individual'],
            'phrases'  => ['data subject rights','rights of individuals','what rights do people have','right to access','right to erasure','right to delete'],
            'priority' => 3,
            'answer'   => "⚖️ **Data Subject Rights Under Kenya DPA 2019**\n\nIndividuals whose data you process have the following rights:\n\n1️⃣ **Right of Access (Section 26)** — Individuals can request a copy of their personal data. You must respond within **21 days**.\n\n2️⃣ **Right to Rectification (Section 27)** — Correct inaccurate or incomplete personal data.\n\n3️⃣ **Right to Erasure / Deletion (Section 28)** — Delete data when it is no longer necessary, or if consent is withdrawn.\n\n4️⃣ **Right to Data Portability (Section 29)** — Provide data in a structured, machine-readable format on request.\n\n5️⃣ **Right to Object (Section 30)** — Individuals can object to processing for direct marketing or profiling.\n\n6️⃣ **Right not to be subject to automated decisions (Section 34)** — Protect individuals from decisions made solely by algorithms.\n\n⏱️ **Response timeframe: 21 days** (extendable to 2 months for complex requests with notice)\n\n👉 Track all these requests in Soul Guard's **DSR Management** module.",
        ],
        [
            'category' => 'Data Subject Rights',
            'topic'    => 'DSR response timeline',
            'keywords' => ['dsr','deadline','response','days','21','time','how long','timeline','request'],
            'phrases'  => ['how long to respond','dsr timeline','response deadline','days to respond','data subject request time'],
            'priority' => 2,
            'answer'   => "⏱️ **DSR Response Deadlines (DPA Section 26)**\n\n• **Standard response:** Within **21 days** of receiving the request\n• **Complex requests:** Can be extended to **2 months** — but you MUST notify the person within the first 21 days, explaining the delay\n\n**The clock starts** from the day you receive the request — not when you start processing it.\n\n**If you miss the deadline:**\n• The data subject can complain to the ODPC\n• ODPC can issue enforcement notices\n• Repeated failures can result in fines\n\n**Tips to stay compliant:**\n• Log every DSR in Soul Guard the moment it arrives\n• Set automated reminders at day 10, 15, and 20\n• Have a template response process ready\n\n👉 Soul Guard's **DSR Management** module tracks all of this automatically.",
        ],

        // ── DATA RETENTION ────────────────────────────
        [
            'category' => 'Data Retention',
            'topic'    => 'Data retention rules',
            'keywords' => ['retention','keep','store','delete','period','how long','data','storage','dispose','archive'],
            'phrases'  => ['how long to keep data','data retention','retention period','how long store','when to delete data','retention policy'],
            'priority' => 2,
            'answer'   => "🗄️ **Data Retention Rules (DPA Section 25(e))**\n\nThe Kenya DPA requires that personal data must **not be kept longer than necessary** for the purpose it was collected.\n\n**What this means in practice:**\n• Define a clear retention period for each data category\n• Document it in your **Record of Processing Activities (RoPA)**\n• Delete or anonymise data when the period expires\n• Review retention schedules at least annually\n\n**Common retention periods (industry guidance):**\n• Employee records: 7 years after employment ends\n• Customer transaction data: 7 years (tax compliance)\n• CCTV footage: 30 days (unless needed for investigation)\n• Marketing consent records: Duration of relationship + 3 years\n• Job applications (unsuccessful): 6 months\n\n⚠️ **Keeping data too long** is a DPA violation, even if you collected it lawfully.\n\n💡 Set up a **data retention schedule** and use Soul Guard's compliance tasks to automate reminders.",
        ],

        // ── SECURITY MEASURES ─────────────────────────
        [
            'category' => 'Security',
            'topic'    => 'Required security measures',
            'keywords' => ['security','encryption','mfa','access','control','technical','measures','protect','safeguard','password'],
            'phrases'  => ['security measures','technical measures','how to secure data','data security','encryption required','mfa required'],
            'priority' => 2,
            'answer'   => "🔒 **Required Security Measures (DPA Section 41)**\n\nYou must implement **appropriate technical and organisational measures** to protect personal data.\n\n**Technical measures (add points to your compliance score):**\n\n🔐 **Encryption (+10 pts)**\n• Encrypt data at rest using AES-256\n• Encrypt data in transit using TLS 1.2+\n• Encrypt backups and portable devices\n\n🔑 **Multi-Factor Authentication / MFA (+6 pts)**\n• Enable MFA on all systems processing personal data\n• Especially critical for admin accounts and remote access\n\n🚪 **Access Control (+4 pts)**\n• Principle of least privilege — staff only access what they need\n• Regular access reviews\n• Terminate access immediately when staff leave\n\n**Organisational measures:**\n• Staff DPA training (mandatory, annual)\n• Data protection policies and procedures\n• Incident response plan\n• Regular security audits\n\n👉 Run Soul Guard's **Security Scan** to identify gaps.",
        ],

        // ── LAWFUL BASIS ──────────────────────────────
        [
            'category' => 'Lawful Basis',
            'topic'    => 'Lawful basis for processing',
            'keywords' => ['lawful','basis','consent','legitimate','contract','legal','obligation','process','grounds','permission'],
            'phrases'  => ['lawful basis','legal basis','basis for processing','can i process','grounds for processing','legitimate interest','do i need consent'],
            'priority' => 2,
            'answer'   => "⚖️ **Lawful Bases for Processing Personal Data (DPA Section 30)**\n\nYou must have a lawful basis BEFORE processing personal data. The six bases are:\n\n1️⃣ **Consent** — Freely given, specific, informed, and unambiguous. Must be easy to withdraw.\n\n2️⃣ **Contract** — Processing is necessary to perform a contract with the individual, or to take pre-contractual steps at their request.\n\n3️⃣ **Legal Obligation** — Processing is necessary to comply with a legal requirement (e.g., tax, employment law).\n\n4️⃣ **Vital Interests** — Processing is necessary to protect someone's life (emergency situations).\n\n5️⃣ **Public Task** — Processing is necessary for a task in the public interest (mainly public bodies).\n\n6️⃣ **Legitimate Interests** — Your interests (or a third party's) are balanced against the individual's interests. Requires a **Legitimate Interests Assessment (LIA)**.\n\n⚠️ **Consent is NOT always the best basis** — if another basis applies, use it. Consent can be withdrawn, which complicates things.\n\n💡 Document your lawful basis for each processing activity in your **RoPA**.",
        ],

        // ── SENSITIVE DATA ────────────────────────────
        [
            'category' => 'Sensitive Data',
            'topic'    => 'Special categories of sensitive data',
            'keywords' => ['sensitive','special','health','biometric','racial','ethnic','religion','political','sexual','criminal','financial'],
            'phrases'  => ['sensitive data','special categories','special category','health data','biometric data','sensitive personal data'],
            'priority' => 2,
            'answer'   => "🔴 **Special Categories of Sensitive Data (DPA Section 46)**\n\nThese categories get **extra protection** and stricter rules:\n\n• **Health and medical data**\n• **Biometric data** (fingerprints, facial recognition, iris scans)\n• **Genetic data**\n• **Racial or ethnic origin**\n• **Political opinions**\n• **Religious or philosophical beliefs**\n• **Trade union membership**\n• **Sexual orientation or sex life**\n• **Criminal convictions and offences**\n• **Financial information** (bank details, credit status)\n\n**Additional requirements for sensitive data:**\n1. You need a **lawful basis** (as normal) PLUS one of the **special category conditions**\n2. A DPIA is almost always required\n3. Extra security measures must be applied\n4. Consider whether you actually need this data at all (data minimisation)\n\n⚠️ Processing sensitive data without proper grounds is a serious DPA violation.",
        ],

        // ── CROSS-BORDER TRANSFERS ────────────────────
        [
            'category' => 'Cross-border Transfer',
            'topic'    => 'Transferring data outside Kenya',
            'keywords' => ['transfer','cross-border','outside','kenya','international','third country','abroad','overseas','foreign'],
            'phrases'  => ['transfer outside kenya','cross border transfer','international transfer','send data abroad','data outside kenya'],
            'priority' => 2,
            'answer'   => "🌍 **Cross-Border Data Transfers (DPA Section 48)**\n\nYou can only transfer personal data outside Kenya if **at least one** of these conditions is met:\n\n✅ **Adequate protection:** The destination country has been assessed as providing adequate data protection (the ODPC publishes this list)\n\n✅ **Appropriate safeguards:**\n• Binding corporate rules (for multinational groups)\n• Standard contractual clauses approved by the ODPC\n• Approved codes of conduct\n\n✅ **Explicit consent:** The data subject has given explicit, informed consent to the transfer\n\n✅ **Contract performance:** Transfer is necessary to perform a contract with the data subject\n\n✅ **Vital interests:** Necessary to protect someone's life\n\n✅ **Public interest:** Established by law\n\n⚠️ **Cloud services count** — if you use AWS, Google Cloud, Microsoft Azure with servers outside Kenya, you must ensure the transfer is lawful.\n\n💡 Add transfer details to your **RoPA** and document your legal basis.",
        ],

        // ── ROPA ──────────────────────────────────────
        [
            'category' => 'RoPA',
            'topic'    => 'Record of Processing Activities',
            'keywords' => ['ropa','record','processing','activities','register','inventory','document','mapping'],
            'phrases'  => ['record of processing','ropa','processing activities register','data inventory','what is ropa','do i need ropa'],
            'priority' => 2,
            'answer'   => "📒 **Record of Processing Activities (RoPA)**\n\nA RoPA is a document that records **all the ways your organisation processes personal data**. It is a core DPA compliance requirement.\n\n**Your RoPA must include (for each processing activity):**\n• Name and contact details of your organisation and DPO\n• **Purpose** of processing\n• **Categories of data subjects** (customers, employees, etc.)\n• **Categories of personal data** processed\n• **Lawful basis** for processing\n• **Retention period**\n• **Recipients** of data (including processors and third parties)\n• **Cross-border transfers** (if any)\n• **Security measures** in place\n\n**Who must have a RoPA?**\nAll organisations processing personal data — especially those with 250+ employees, though the ODPC recommends all controllers maintain one.\n\n**Review your RoPA:**\n• At least annually\n• Whenever a new processing activity starts\n• After any significant change to existing activities\n\n👉 Start your RoPA in Soul Guard's **ODPC Guidance** module.",
        ],

        // ── CONSENT ───────────────────────────────────
        [
            'category' => 'Consent',
            'topic'    => 'Valid consent requirements',
            'keywords' => ['consent','permission','agree','opt','tick','withdrawal','valid','obtain'],
            'phrases'  => ['how to get consent','valid consent','consent requirements','obtaining consent','withdraw consent','what is valid consent'],
            'priority' => 2,
            'answer'   => "✅ **Valid Consent Under Kenya DPA 2019**\n\nFor consent to be valid, it must be:\n\n**F - Freely given:** No penalty for refusing. Pre-ticked boxes are NOT valid.\n\n**S - Specific:** Separate consent for each distinct purpose. Bundled consent is not valid.\n\n**I - Informed:** Individuals must know exactly what they're consenting to, who will process their data, and why.\n\n**U - Unambiguous:** A clear, positive action (checking a box, clicking a button). Silence or inactivity does NOT count.\n\n**Additional rules:**\n• Consent must be as easy to **withdraw** as it is to give\n• Keep clear records of when and how consent was obtained\n• For children under 18, you need **parental/guardian consent**\n• Review and refresh consent regularly\n\n⚠️ **Pre-ticked boxes, bundled T&Cs consent, and implied consent are all invalid** under the DPA.\n\n💡 If you're relying on consent, make sure your consent forms and records are up to date.",
        ],

        // ── PENALTIES ─────────────────────────────────
        [
            'category' => 'Penalties',
            'topic'    => 'DPA fines and penalties',
            'keywords' => ['fine','penalty','punishment','sanction','enforcement','offence','violation','consequences','jail'],
            'phrases'  => ['dpa fines','what are the penalties','consequences of non-compliance','odpc fines','penalty for breach','enforcement action'],
            'priority' => 2,
            'answer'   => "⚠️ **DPA 2019 Penalties & Enforcement**\n\nThe Kenya DPA has serious consequences for non-compliance:\n\n**ODPC Enforcement Powers:**\n• Issue **compliance notices** requiring corrective action\n• Issue **enforcement notices** stopping processing\n• Issue **assessment notices** to audit your data practices\n• **Prosecute** for criminal offences\n\n**Criminal offences and penalties include:**\n• Failure to register with ODPC — Fine up to KES 3 million or 2 years imprisonment\n• Unlawful processing — Fine up to KES 5 million or 10 years imprisonment\n• Failure to notify breach — Fine up to KES 5 million or 3 years imprisonment\n• Obstruction of ODPC — Fine up to KES 1 million\n\n**Civil liability:**\n• Data subjects can seek compensation in court for damage suffered from DPA violations\n\n💡 **Prevention is far cheaper than penalties.** Your Soul Guard compliance score is your best early warning system.",
        ],

        // ── PROCESSORS ────────────────────────────────
        [
            'category' => 'Processors',
            'topic'    => 'Managing data processors',
            'keywords' => ['processor','vendor','supplier','third party','contract','dpa','agreement','outsource'],
            'phrases'  => ['data processor','processor agreement','managing processors','third party data','vendor management','processor contract','data processing agreement'],
            'priority' => 2,
            'answer'   => "🏢 **Managing Data Processors (DPA Section 38-40)**\n\nA **data processor** is any third party that processes personal data on your behalf (e.g., cloud providers, payroll services, marketing agencies).\n\n**Your obligations as a data controller:**\n\n1️⃣ **Only use processors with sufficient guarantees** — they must demonstrate adequate technical and organisational measures\n\n2️⃣ **Have a written Data Processing Agreement (DPA/DPA)** covering:\n   • Subject matter and duration of processing\n   • Nature and purpose of processing\n   • Type of personal data and data subjects\n   • Your obligations and rights as controller\n   • Processor's obligations (security, confidentiality, sub-processor rules)\n\n3️⃣ **Processors must not sub-contract** without your authorisation\n\n4️⃣ **Audit your processors** regularly to verify compliance\n\n5️⃣ **Processors must notify you immediately** of any breach\n\n⚠️ **You remain responsible** for your processors' compliance with the DPA.\n\n👉 Use Soul Guard's **Processor Assessments** module to manage and document all your processors.",
        ],

        // ── CHILDREN'S DATA ───────────────────────────
        [
            'category' => 'Children',
            'topic'    => 'Processing children\'s data',
            'keywords' => ['children','child','minor','under 18','age','parental','guardian','young','student'],
            'phrases'  => ['children data','child data','processing children','minor data','under 18','parental consent'],
            'priority' => 2,
            'answer'   => "👶 **Processing Children's Personal Data (DPA Section 46 & Section 51)**\n\nChildren's data gets **extra protection** under the Kenya DPA.\n\n**Key rules:**\n\n• **Age threshold:** A child is anyone under **18 years** in Kenya\n• **Parental consent required:** For processing a child's data, you must obtain consent from a parent or guardian\n• **Best interests of the child:** Always the primary consideration\n• **Marketing to children** is heavily restricted\n• **Profiling children** for behavioural advertising is prohibited\n• Children have the right to have data collected in their youth **erased** when they reach adulthood\n\n**If your service might be accessed by children:**\n• Implement age verification\n• Have clear, child-friendly privacy notices\n• Conduct a DPIA specifically for the child-facing elements\n• Apply extra security measures\n\n⚠️ **Serious penalties apply** for mishandling children's data — this is treated as a priority area by the ODPC.",
        ],

        // ── GREETINGS / GENERAL ───────────────────────
        [
            'category' => 'General',
            'topic'    => 'Hello greeting',
            'keywords' => ['hello','hi','hey','greetings','good morning','good afternoon','good evening','howdy'],
            'phrases'  => ['hello','hi there','hey there','good morning','good afternoon'],
            'priority' => 1,
            'answer'   => "👋 **Hello!** I'm your Soul Guard DPA Compliance Assistant.\n\nI can help you with:\n• 📋 **DPIAs** — when and how to conduct them\n• 🚨 **Breach notification** — 72-hour ODPC rule\n• 🏛️ **ODPC registration** — steps and requirements\n• ⚖️ **Data subject rights** — access, erasure, portability\n• 👤 **DPO requirements** — when you need one\n• 📊 **My compliance score** — personalised analysis\n• 🔒 **Security measures** — what the DPA requires\n• 📒 **RoPA** — record of processing activities\n\nWhat would you like to know?",
        ],
        [
            'category' => 'General',
            'topic'    => 'Thank you response',
            'keywords' => ['thank','thanks','thank you','appreciate','helpful','great','perfect'],
            'phrases'  => ['thank you','thanks','thank you so much','that was helpful','great help'],
            'priority' => 1,
            'answer'   => "😊 You're welcome! Staying compliant with the Kenya DPA 2019 is important work — glad I could help.\n\nFeel free to ask any other compliance questions. You can also:\n• Type **\"my compliance score\"** for a personalised overview\n• Type **\"how to improve score\"** for your action plan\n• Visit **ODPC Guidance** for more detailed guidance\n\nStay compliant! 🛡️",
        ],
        [
            'category' => 'General',
            'topic'    => 'What can you do',
            'keywords' => ['what','can','you','do','help','topics','cover','know','about'],
            'phrases'  => ['what can you do','what can you help with','what do you know','what topics','what can you tell me'],
            'priority' => 1,
            'answer'   => "🤖 **I'm your Kenya DPA 2019 Compliance Assistant!**\n\nHere's what I can help with:\n\n📋 **Compliance Fundamentals**\n• Data Protection Impact Assessments (DPIAs)\n• Lawful basis for processing\n• Special categories of sensitive data\n• Record of Processing Activities (RoPA)\n\n🏛️ **ODPC Requirements**\n• Registration process and fees\n• Compliance obligations\n• Enforcement and penalties\n\n🚨 **Breach Management**\n• 72-hour notification rule\n• What counts as a breach\n• Notification to data subjects\n\n⚖️ **Data Subject Rights**\n• Access, erasure, portability, objection\n• DSR response timelines (21 days)\n\n👤 **DPO & Governance**\n• When a DPO is required\n• DPO responsibilities\n\n📊 **Your Dashboard**\n• \"My compliance score\"\n• \"How to improve score\"\n• \"My open breaches\"\n• \"My pending tasks\"\n\nJust ask!",
        ],
    ];
}