<?php
// dpa.php - Professional Data Protection Act (Kenya) Compliance Assessment
// Copyright © 2026 Christopher Khayere. All rights reserved.
// Christopher Khayere - Certified Data Protection Officer | AI Security Platform
require_once 'config.php';
requireLogin();

try {
    $pdo = getDBConnection();

    // === SCHEMA CREATION ===
    $pdo->exec("CREATE TABLE IF NOT EXISTS dpa_assessments (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        company_name TEXT NOT NULL,
        company_website TEXT,
        company_industry TEXT,
        company_size TEXT,
        assessment_date DATETIME DEFAULT CURRENT_TIMESTAMP,
        risk_score REAL,
        risk_level TEXT,
        compliance_percent REAL,
        total_questions INTEGER,
        answered_questions INTEGER,
        responses TEXT,
        recommendations TEXT,
        category_scores TEXT,
        report_ref TEXT UNIQUE,
        report_html TEXT,
        website_scan TEXT,
        completed INTEGER DEFAULT 0
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS dpa_questions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        category TEXT NOT NULL,
        question TEXT NOT NULL,
        guidance TEXT,
        weight REAL DEFAULT 1.0,
        kenya_dpa_reference TEXT,
        sort_order INTEGER
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS dpa_recommendations (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        risk_level TEXT,
        category TEXT,
        priority TEXT,
        recommendation TEXT NOT NULL,
        timeframe TEXT,
        legal_reference TEXT,
        penalty_risk TEXT
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS website_scan_cache (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        domain TEXT UNIQUE,
        scan_data TEXT,
        scan_date DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    $count = $pdo->query("SELECT COUNT(*) FROM dpa_questions")->fetchColumn();
    if ($count == 0) insertDefaultQuestions($pdo);

    $count = $pdo->query("SELECT COUNT(*) FROM dpa_recommendations")->fetchColumn();
    if ($count == 0) insertDefaultRecommendations($pdo);

} catch(Exception $e) {
    die("Database error: " . $e->getMessage());
}

// ============================================================
// DEFAULT QUESTIONS
// ============================================================
function insertDefaultQuestions($pdo) {
    $questions = [
        // 1. Legal Basis & Lawful Processing
        ['Legal Basis & Lawful Processing', 'Has your organization identified and documented a lawful basis for every personal data processing activity?', 'DPA requires at least one of: consent, contract, legal obligation, vital interests, public task, or legitimate interests.', 3.0, 'Section 30, Kenya DPA 2019', 1],
        ['Legal Basis & Lawful Processing', 'Do you obtain explicit, informed, and freely given consent from data subjects before processing their personal data?', 'Consent must be specific, informed, and unambiguous. Pre-ticked boxes are not valid consent.', 3.0, 'Section 32, Kenya DPA 2019', 2],
        ['Legal Basis & Lawful Processing', 'Can data subjects withdraw consent at any time, and is withdrawal as easy as giving consent?', 'Withdrawal of consent must not affect the lawfulness of processing done before withdrawal.', 2.5, 'Section 32(5), Kenya DPA 2019', 3],
        ['Legal Basis & Lawful Processing', 'Do you process special categories of data (health, biometric, racial/ethnic origin, religion, etc.)?', 'Special category data requires explicit consent or specific legal grounds under Section 31.', 3.5, 'Section 31, Kenya DPA 2019', 4],
        ['Legal Basis & Lawful Processing', 'Is processing of children\'s personal data done with verifiable parental/guardian consent?', 'Children under 18 require guardian consent. Age verification mechanisms must be in place.', 3.5, 'Section 33, Kenya DPA 2019', 5],

        // 2. Data Subject Rights
        ['Data Subject Rights', 'Do data subjects have a clear mechanism to access their personal data held by your organization?', 'Right of access must be fulfilled within 21 days of request. Provide data in a commonly used format.', 3.0, 'Section 26, Kenya DPA 2019', 6],
        ['Data Subject Rights', 'Can data subjects request rectification of inaccurate or incomplete personal data?', 'Corrections must be made promptly and third parties notified where data has been shared.', 2.5, 'Section 27, Kenya DPA 2019', 7],
        ['Data Subject Rights', 'Do you have a procedure for handling erasure (right to be forgotten) requests?', 'Erasure applies when data is no longer necessary, consent withdrawn, or data unlawfully processed.', 2.5, 'Section 28, Kenya DPA 2019', 8],
        ['Data Subject Rights', 'Can data subjects object to automated decision-making or profiling that significantly affects them?', 'Organizations must offer human review of automated decisions that have legal or similarly significant effects.', 2.5, 'Section 34, Kenya DPA 2019', 9],
        ['Data Subject Rights', 'Do you provide data portability — allowing subjects to receive their data in machine-readable format?', 'Data portability applies where processing is based on consent or contract, done by automated means.', 2.0, 'Section 35, Kenya DPA 2019', 10],

        // 3. Privacy Notices & Transparency
        ['Privacy Notices & Transparency', 'Do you have a clear, accessible privacy notice/policy published and made available to data subjects?', 'Privacy notice must be concise, transparent, intelligible and in plain language (Section 29).', 3.0, 'Section 29, Kenya DPA 2019', 11],
        ['Privacy Notices & Transparency', 'Does your privacy notice include: data categories collected, purpose, legal basis, retention period, and third-party sharing?', 'All mandatory disclosures per Section 29 must be present in privacy notices.', 3.0, 'Section 29, Kenya DPA 2019', 12],
        ['Privacy Notices & Transparency', 'Are data subjects informed at the point of collection about how their data will be used?', 'Notification must happen at the time of data collection, not after.', 2.5, 'Section 29, Kenya DPA 2019', 13],
        ['Privacy Notices & Transparency', 'Is your privacy notice regularly reviewed and updated to reflect actual processing activities?', 'Privacy notices must be kept current and version-controlled with dates.', 2.0, 'Section 29, Kenya DPA 2019', 14],

        // 4. Data Minimisation & Retention
        ['Data Minimisation & Retention', 'Do you only collect data that is adequate, relevant, and limited to what is necessary for the stated purpose?', 'Data minimisation is a core DPA principle. Avoid collecting "just in case" data.', 2.5, 'Section 25(b), Kenya DPA 2019', 15],
        ['Data Minimisation & Retention', 'Do you have a documented data retention schedule with defined retention periods for each data category?', 'Retention periods must be justified, documented, and communicated to data subjects.', 2.5, 'Section 25(e), Kenya DPA 2019', 16],
        ['Data Minimisation & Retention', 'Is there a process for secure deletion/destruction of personal data when retention period expires?', 'Expired data must be securely disposed — shredding physical records, cryptographic erasure for digital.', 2.5, 'Section 25(e), Kenya DPA 2019', 17],
        ['Data Minimisation & Retention', 'Do you conduct periodic data audits to identify and remove unnecessary personal data?', 'Regular audits help maintain data minimisation and reduce breach exposure.', 2.0, 'Section 25, Kenya DPA 2019', 18],

        // 5. Data Security & Technical Measures
        ['Data Security & Technical Measures', 'Do you have documented technical and organisational security measures to protect personal data?', 'Security measures must be appropriate to the risk. Document them in a security policy.', 3.0, 'Section 41, Kenya DPA 2019', 19],
        ['Data Security & Technical Measures', 'Is personal data encrypted at rest and in transit using industry-standard encryption?', 'AES-256 for data at rest; TLS 1.2+ for data in transit. Encryption keys must be securely managed.', 3.0, 'Section 41, Kenya DPA 2019', 20],
        ['Data Security & Technical Measures', 'Do you conduct regular security risk assessments and vulnerability testing on systems holding personal data?', 'Penetration testing, vulnerability scanning, and DPIA for high-risk processing are required.', 3.0, 'Section 41, Kenya DPA 2019', 21],
        ['Data Security & Technical Measures', 'Are access controls implemented ensuring only authorised personnel can access personal data (least privilege)?', 'Role-based access control, MFA, and regular access reviews are best practice.', 3.0, 'Section 41, Kenya DPA 2019', 22],
        ['Data Security & Technical Measures', 'Do you have a documented, tested Data Breach Response Plan?', 'Breaches must be reported to ODPC within 72 hours and affected data subjects without undue delay.', 3.5, 'Section 43, Kenya DPA 2019', 23],
        ['Data Security & Technical Measures', 'Have you conducted a Data Protection Impact Assessment (DPIA) for high-risk processing activities?', 'DPIAs are mandatory for large-scale processing of special categories, systematic monitoring, or novel technologies.', 3.0, 'Section 41(5), Kenya DPA 2019', 24],

        // 6. Data Processors & Third Parties
        ['Data Processors & Third Parties', 'Do you have Data Processing Agreements (DPAs) with all third-party processors handling personal data on your behalf?', 'Written contracts with processors are mandatory. They must only act on documented instructions.', 3.0, 'Section 46, Kenya DPA 2019', 25],
        ['Data Processors & Third Parties', 'Do you conduct due diligence and security assessments on all third-party data processors before engagement?', 'Controllers are responsible for processor compliance. Assess before and monitor during engagement.', 2.5, 'Section 46, Kenya DPA 2019', 26],
        ['Data Processors & Third Parties', 'Do you have an up-to-date register/inventory of all data processors and the personal data they handle?', 'A processor register supports accountability and helps in breach management.', 2.5, 'Section 46, Kenya DPA 2019', 27],

        // 7. Cross-Border Data Transfers
        ['Cross-Border Data Transfers', 'Do you transfer personal data outside Kenya? If yes, have you ensured adequate safeguards are in place?', 'International transfers require adequacy decision or appropriate safeguards (SCCs, BCRs, or explicit consent).', 3.0, 'Section 48, Kenya DPA 2019', 28],
        ['Cross-Border Data Transfers', 'Have you obtained ODPC authorisation where required for cross-border data transfers?', 'Transfers to countries without adequate protection may require ODPC approval.', 3.0, 'Section 48-49, Kenya DPA 2019', 29],

        // 8. ODPC Registration & Governance
        ['ODPC Registration & Governance', 'Is your organisation registered as a Data Controller/Processor with the Office of the Data Protection Commissioner (ODPC)?', 'Registration is mandatory under DPA Section 18. Failure attracts KES 1,000,000 fine.', 4.0, 'Section 18, Kenya DPA 2019', 30],
        ['ODPC Registration & Governance', 'Have you appointed a Data Protection Officer (DPO) if required under the DPA?', 'Public bodies and organisations processing large-scale or special category data must appoint a DPO.', 3.0, 'Section 24, Kenya DPA 2019', 31],
        ['ODPC Registration & Governance', 'Is the DPO adequately qualified, resourced, and independent to perform their duties?', 'DPO must have expert knowledge of data protection law and be able to perform duties without conflict of interest.', 3.0, 'Section 24, Kenya DPA 2019', 32],
        ['ODPC Registration & Governance', 'Do you maintain a Record of Processing Activities (RoPA) as required by the DPA?', 'RoPA must document purposes, categories, recipients, transfers, retention periods, and security measures.', 3.0, 'Section 25, Kenya DPA 2019', 33],

        // 9. Staff Training & Awareness
        ['Staff Training & Awareness', 'Do all staff who handle personal data receive regular data protection training?', 'Training must be role-specific and repeated at least annually or when significant changes occur.', 2.5, 'Section 25, Kenya DPA 2019', 34],
        ['Staff Training & Awareness', 'Are staff aware of their obligations when handling personal data and the penalties for violations?', 'Awareness of KES 5M fines and imprisonment creates accountability and reduces insider risk.', 2.5, 'Section 64-65, Kenya DPA 2019', 35],
        ['Staff Training & Awareness', 'Do you have data protection clauses in employment contracts and NDAs for staff handling personal data?', 'Contractual obligations bind staff to data protection requirements and create enforceable accountability.', 2.0, 'Section 41, Kenya DPA 2019', 36],

        // 10. Website & Digital Compliance
        ['Website & Digital Compliance', 'Does your website use HTTPS/TLS encryption for all pages handling personal data?', 'Unencrypted data transmission is a DPA Section 41 violation. All pages should use HTTPS.', 3.0, 'Section 41, Kenya DPA 2019', 37],
        ['Website & Digital Compliance', 'Does your website display a comprehensive, DPA-compliant privacy policy?', 'Privacy policy must be prominently displayed and cover all Section 29 requirements.', 3.0, 'Section 29, Kenya DPA 2019', 38],
        ['Website & Digital Compliance', 'Does your website have a functional cookie consent mechanism with granular opt-in controls?', 'Tracking cookies require explicit opt-in consent. Pre-consent cookies limited to essential only.', 2.5, 'Section 32, Kenya DPA 2019', 39],
        ['Website & Digital Compliance', 'Are web forms collecting personal data secured and accompanied by a relevant privacy notice?', 'Every data collection point must explain purpose, legal basis, and data subject rights.', 2.5, 'Section 29, Kenya DPA 2019', 40],
    ];

    $stmt = $pdo->prepare("INSERT INTO dpa_questions (category, question, guidance, weight, kenya_dpa_reference, sort_order) VALUES (?,?,?,?,?,?)");
    foreach ($questions as $q) $stmt->execute($q);
}

// ============================================================
// DEFAULT RECOMMENDATIONS
// ============================================================
function insertDefaultRecommendations($pdo) {
    $recs = [
        // Immediate - Critical
        ['critical,very-high,high', 'Legal Basis', 'immediate', 'Immediately document a lawful basis for every personal data processing activity in your Record of Processing Activities (RoPA). Without this, all processing is unlawful under DPA Section 30.', '30 days', 'Section 30, Kenya DPA 2019', 'Up to KES 5,000,000 fine or 1% annual turnover'],
        ['critical,very-high,high', 'ODPC Registration', 'immediate', 'Register as a Data Controller/Processor with the Office of the Data Protection Commissioner (ODPC) at odpc.go.ke. Non-registration carries a KES 1,000,000 mandatory fine.', '30 days', 'Section 18, Kenya DPA 2019', 'KES 1,000,000 fixed penalty'],
        ['critical,very-high,high', 'Data Breach Response', 'immediate', 'Establish and test a Data Breach Response Plan. Breaches must be reported to ODPC within 72 hours. Failure to report carries a KES 5,000,000 fine.', '30 days', 'Section 43, Kenya DPA 2019', 'KES 5,000,000 fine'],
        ['critical,very-high', 'Data Security', 'immediate', 'Implement encryption (AES-256 at rest, TLS 1.2+ in transit) immediately. Unencrypted personal data is a critical DPA Section 41 violation with significant breach liability.', '14 days', 'Section 41, Kenya DPA 2019', 'Criminal liability + unlimited civil damages'],
        ['all', 'Privacy Notice', 'immediate', 'Publish a comprehensive privacy policy/notice accessible to all data subjects covering: identity of controller, purposes, legal basis, data categories, recipients, retention periods, and data subject rights.', '30 days', 'Section 29, Kenya DPA 2019', 'ODPC enforcement notice + KES 5,000,000'],

        // Short-term
        ['critical,very-high,high,moderate', 'Data Subject Rights', 'short-term', 'Implement a Data Subject Rights Management process: access requests (21-day SLA), rectification, erasure, portability, and objection handling with documented procedures.', '60 days', 'Section 26-35, Kenya DPA 2019', 'Individual complaints to ODPC + court-ordered damages'],
        ['critical,very-high,high,moderate', 'Consent Management', 'short-term', 'Deploy a Consent Management Platform (CMP) or process ensuring consent is freely given, specific, informed, unambiguous, and easily withdrawable. Purge unlawfully obtained data.', '60 days', 'Section 32, Kenya DPA 2019', 'KES 5,000,000 + data processing injunction'],
        ['critical,very-high,high,moderate', 'Data Processor Contracts', 'short-term', 'Execute Data Processing Agreements (DPAs) with all third-party vendors, cloud providers, and processors handling personal data. Template available from ODPC.', '60 days', 'Section 46, Kenya DPA 2019', 'Joint liability with processors'],
        ['critical,very-high,high,moderate', 'Access Controls', 'short-term', 'Implement Role-Based Access Control (RBAC), Multi-Factor Authentication (MFA), and privileged access management. Conduct immediate access rights audit and remove excessive privileges.', '60 days', 'Section 41, Kenya DPA 2019', 'Data breach liability'],
        ['all', 'Data Protection Officer', 'short-term', 'Appoint a qualified Data Protection Officer (DPO) or engage an external certified DPO. Register DPO details with ODPC. DPO must have adequate resources and independence.', '60 days', 'Section 24, Kenya DPA 2019', 'ODPC enforcement + reputational risk'],

        // Medium-term
        ['all', 'DPIA Programme', 'medium-term', 'Establish a Data Protection Impact Assessment (DPIA) programme for all high-risk processing. Conduct DPIAs before launching new products, systems, or processing activities involving personal data.', '3 months', 'Section 41(5), Kenya DPA 2019', 'Regulatory censure + processing suspension'],
        ['all', 'Staff Training', 'medium-term', 'Implement mandatory annual data protection training for all staff. Role-specific training for DPO, IT security, HR, and marketing. Document training completion records.', '3 months', 'Section 25, Kenya DPA 2019', 'Employee-caused breaches create employer liability'],
        ['all', 'Record of Processing Activities', 'medium-term', 'Create and maintain a comprehensive Record of Processing Activities (RoPA) covering all personal data processing. Must include purposes, categories, recipients, transfers, retention periods, and security measures.', '3 months', 'Section 25, Kenya DPA 2019', 'ODPC audit failure + KES 5,000,000'],
        ['all', 'Retention Policy', 'medium-term', 'Develop and implement a Data Retention and Disposal Policy with defined retention periods for each data category, automated deletion reminders, and secure disposal certificates.', '3 months', 'Section 25(e), Kenya DPA 2019', 'Unlawful retention = processing violation'],

        // Long-term
        ['all', 'Privacy by Design', 'long-term', 'Embed Privacy by Design and Privacy by Default into all new systems, products, and processes. Establish a privacy governance committee and annual DPA compliance review cycle.', '6 months', 'Section 25, Kenya DPA 2019', 'Systemic non-compliance risk'],
        ['all', 'Cross-Border Transfers', 'long-term', 'Conduct an international data transfer audit. Implement Standard Contractual Clauses (SCCs) or obtain ODPC authorisation for all transfers to countries without adequate data protection.', '6 months', 'Section 48-49, Kenya DPA 2019', 'KES 5,000,000 fine per unlawful transfer'],
        ['all', 'Vendor Management', 'long-term', 'Establish an ongoing third-party data protection due diligence programme: pre-engagement assessments, contractual controls, periodic audits, and offboarding procedures for all data processors.', '6 months', 'Section 46, Kenya DPA 2019', 'Controller remains liable for processor failures'],
        ['all', 'Compliance Certification', 'long-term', 'Pursue ISO 27001 certification and DPA compliance certification as evidence of accountability to ODPC. Conduct annual third-party DPA compliance audits.', '12 months', 'Section 17, Kenya DPA 2019', 'Demonstrates good faith to ODPC in investigations'],
    ];

    $stmt = $pdo->prepare("INSERT INTO dpa_recommendations (risk_level, category, priority, recommendation, timeframe, legal_reference, penalty_risk) VALUES (?,?,?,?,?,?,?)");
    foreach ($recs as $r) $stmt->execute($r);
}

// ============================================================
// LOAD QUESTIONS
// ============================================================
$questions = $pdo->query("SELECT * FROM dpa_questions ORDER BY sort_order ASC")->fetchAll();
$categories = [];
foreach ($questions as $q) $categories[$q['category']][] = $q;

// ============================================================
// ANSWER OPTIONS
// ============================================================
$answerOptions   = ['Yes' => 0, 'Partially' => 1, 'No' => 2, "I Don't Know" => 3];
$answerEmoji     = ['Yes' => '✅ Yes – Compliant', 'Partially' => '⚠️ Partially Compliant', 'No' => '❌ No – Non-Compliant', "I Don't Know" => '❓ Unknown / Unsure'];
$answerRiskLabel = [0 => 'Compliant', 1 => 'Partial', 2 => 'Non-Compliant', 3 => 'Unknown'];
$answerColors    = [0 => '#22c55e', 1 => '#eab308', 2 => '#ef4444', 3 => '#dc2626'];

$industries = [
    'Financial Services / Banking'   => 'financial',
    'Healthcare / Medical'           => 'healthcare',
    'Education'                      => 'education',
    'Technology / IT Services'       => 'technology',
    'Government / Public Sector'     => 'government',
    'Retail / E-commerce'            => 'retail',
    'Manufacturing'                  => 'manufacturing',
    'Legal Services'                 => 'legal',
    'Hospitality / Tourism'          => 'hospitality',
    'Media / Telecommunications'     => 'media',
    'Real Estate'                    => 'realestate',
    'NGO / Non-Profit'               => 'ngo',
    'Transport / Logistics'          => 'transport',
    'Agriculture'                    => 'agriculture',
    'Other'                          => 'other'
];

$companySizes = [
    '1–10 (Micro)'          => 'micro',
    '11–50 (Small)'         => 'small',
    '51–250 (Medium)'       => 'medium',
    '251–1,000 (Large)'     => 'large',
    '1,000+ (Enterprise)'   => 'enterprise'
];

// ============================================================
// AJAX: WEBSITE SCAN
// ============================================================
if (isset($_POST['ajax_scan_website'])) {
    header('Content-Type: application/json');
    $domain = trim($_POST['domain'] ?? '');
    $domain = preg_replace('#^https?://#', '', $domain);
    $domain = rtrim($domain, '/');

    if (empty($domain)) { echo json_encode(['error' => 'No domain']); exit; }

    // Cache check (7 days)
    $stmt = $pdo->prepare("SELECT scan_data FROM website_scan_cache WHERE domain = ? AND scan_date > datetime('now','-7 days')");
    $stmt->execute([$domain]);
    $cached = $stmt->fetchColumn();
    if ($cached) { echo $cached; exit; }

    $result = performWebsiteScan($domain);
    $json   = json_encode($result);

    $stmt = $pdo->prepare("INSERT OR REPLACE INTO website_scan_cache (domain, scan_data, scan_date) VALUES (?,?,CURRENT_TIMESTAMP)");
    $stmt->execute([$domain, $json]);

    echo $json;
    exit;
}

// ============================================================
// WEBSITE SCAN FUNCTION
// ============================================================
function performWebsiteScan($domain) {
    $res = [
        'domain'       => $domain,
        'scan_time'    => date('Y-m-d H:i:s'),
        'reachable'    => false,
        'https'        => false,
        'ssl_valid'    => false,
        'ssl_issuer'   => '',
        'ssl_expiry'   => '',
        'sec_headers'  => [],
        'cookies'      => [],
        'cookie_count' => 0,
        'tracking_cookies' => [],
        'privacy'      => [
            'privacy_policy'  => false,
            'cookie_consent'  => false,
            'data_collection' => false,
            'gdpr_mention'    => false,
            'dpa_mention'     => false,
        ],
        'forms_count'  => 0,
        'findings'     => [],
        'positives'    => [],
        'web_risk_percent' => 0,
    ];

    $url = 'https://' . $domain;
    $ch  = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5,
        CURLOPT_TIMEOUT        => 12,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_HEADER         => true,
        CURLOPT_NOBODY         => false,
        CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; DPA-ComplianceBot/3.0)',
        CURLOPT_CERTINFO       => true,
    ]);

    $response  = curl_exec($ch);
    $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $sslResult = curl_getinfo($ch, CURLINFO_SSL_VERIFYRESULT);
    $certInfo  = curl_getinfo($ch, CURLINFO_CERTINFO);
    $errNo     = curl_errno($ch);

    if ($errNo === 0 && $response !== false && $httpCode > 0 && $httpCode < 500) {
        $res['reachable'] = true;
        $res['https']     = true;
        $res['ssl_valid'] = ($sslResult === 0);

        if (!empty($certInfo)) {
            foreach ($certInfo as $cert) {
                if (!empty($cert['Issuer'])) {
                    $res['ssl_issuer'] = $cert['Issuer'];
                    $res['ssl_expiry'] = $cert['Expire date'] ?? '';
                    break;
                }
            }
        }

        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers    = substr($response, 0, $headerSize);
        $body       = substr($response, $headerSize);

        // Security headers
        $secHeaders = [
            'Strict-Transport-Security' => ['desc' => 'Enforces HTTPS connections', 'ref' => 'Section 41'],
            'Content-Security-Policy'   => ['desc' => 'Prevents XSS & injection attacks', 'ref' => 'Section 41'],
            'X-Frame-Options'           => ['desc' => 'Prevents clickjacking attacks', 'ref' => 'Section 41'],
            'X-Content-Type-Options'    => ['desc' => 'Prevents MIME sniffing', 'ref' => 'Section 41'],
            'Referrer-Policy'           => ['desc' => 'Controls referrer data leakage', 'ref' => 'Section 41'],
            'Permissions-Policy'        => ['desc' => 'Controls browser feature access', 'ref' => 'Section 41'],
        ];

        foreach ($secHeaders as $hdr => $info) {
            $present = (stripos($headers, $hdr . ':') !== false);
            $res['sec_headers'][$hdr] = ['present' => $present, 'desc' => $info['desc'], 'ref' => $info['ref']];
            if (!$present) {
                $res['findings'][] = ['level' => 'medium', 'text' => "Missing '$hdr' header – increases attack surface ({$info['ref']})"];
            } else {
                $res['positives'][] = "$hdr header correctly implemented";
            }
        }

        // Cookies
        preg_match_all('/^Set-Cookie:\s*([^\r\n]+)/im', $headers, $cookieM);
        $res['cookie_count'] = count($cookieM[1]);
        $trackingKeywords    = ['_ga', '_gid', '_fbp', '_fbc', 'track', 'analytic', 'pixel', 'ads', 'utm', 'remarketing', 'doubleclick'];
        foreach ($cookieM[1] as $ck) {
            foreach ($trackingKeywords as $kw) {
                if (stripos($ck, $kw) !== false) {
                    $res['tracking_cookies'][] = strtok($ck, '=');
                    break;
                }
            }
        }
        if (!empty($res['tracking_cookies'])) {
            $res['findings'][] = ['level' => 'high', 'text' => 'Tracking/analytics cookies detected without verified consent mechanism (' . implode(', ', array_unique($res['tracking_cookies'])) . ') – Section 32 violation risk'];
        }

        // Privacy Policy
        $hasPP = preg_match('/privacy\s*(policy|notice|statement)/i', $body) ||
                 preg_match('/data\s*protection\s*(policy|notice|statement)/i', $body);
        $res['privacy']['privacy_policy'] = (bool)$hasPP;
        if ($hasPP) {
            $res['positives'][] = 'Privacy policy/notice detected on website';
        } else {
            $res['findings'][] = ['level' => 'critical', 'text' => 'No privacy policy/notice detected – mandatory disclosure requirement under Section 29 not met'];
        }

        // Cookie Consent
        $hasCookieConsent = preg_match('/cookie\s*(consent|banner|notice|policy|accept|preferences|settings)/i', $body) ||
                            preg_match('/(accept|reject)\s*(all\s*)?(cookie|tracking)/i', $body) ||
                            stripos($body, 'cookieyes') !== false ||
                            stripos($body, 'cookiebot') !== false ||
                            stripos($body, 'onetrust') !== false ||
                            stripos($body, 'cookie-script') !== false;
        $res['privacy']['cookie_consent'] = $hasCookieConsent;
        if ($hasCookieConsent) {
            $res['positives'][] = 'Cookie consent mechanism detected';
        } else {
            $res['findings'][] = ['level' => 'high', 'text' => 'No cookie consent mechanism detected – explicit consent required for non-essential cookies under Section 32'];
        }

        // GDPR/DPA mentions
        $res['privacy']['gdpr_mention'] = (bool)preg_match('/GDPR|General\s*Data\s*Protection\s*Regulation/i', $body);
        $res['privacy']['dpa_mention']  = (bool)preg_match('/Kenya\s*Data\s*Protection|DPA\s*2019|ODPC/i', $body);
        if ($res['privacy']['dpa_mention']) $res['positives'][] = 'Kenya DPA 2019 / ODPC reference found – demonstrates local compliance awareness';

        // Forms
        preg_match_all('/<form[^>]*>/i', $body, $forms);
        $res['forms_count'] = count($forms[0]);
        if ($res['forms_count'] > 0) {
            $res['privacy']['data_collection'] = true;
            preg_match_all('/<input[^>]*type=["\']?(email|tel|phone|name|text|number)["\']?/i', $body, $inputs);
            if (count($inputs[0]) > 0 && !$hasPP) {
                $res['findings'][] = ['level' => 'high', 'text' => "Forms collecting personal data detected ({$res['forms_count']} form(s)) without visible privacy notice at point of collection – Section 29 violation"];
            }
        }

        // SSL issues
        if (!$res['ssl_valid']) {
            $res['findings'][] = ['level' => 'critical', 'text' => 'Invalid or untrusted SSL certificate – personal data in transit is NOT encrypted (Section 41 critical violation)'];
        } else {
            $res['positives'][] = 'Valid SSL/TLS certificate – data in transit encrypted';
        }

        // Risk score
        $riskScore = 0; $riskMax = 0;
        if (!$res['ssl_valid'])                     { $riskScore += 4; } $riskMax += 4;
        if (!$res['privacy']['privacy_policy'])      { $riskScore += 5; } $riskMax += 5;
        if (!$res['privacy']['cookie_consent'])      { $riskScore += 3; } $riskMax += 3;
        if (!empty($res['tracking_cookies']))        { $riskScore += 3; } $riskMax += 3;
        foreach ($res['sec_headers'] as $h) {
            if (!$h['present']) { $riskScore += 1; } $riskMax += 1;
        }
        $res['web_risk_percent'] = $riskMax > 0 ? round(($riskScore / $riskMax) * 100) : 0;

    } else {
        // Try HTTP fallback
        curl_setopt($ch, CURLOPT_URL, 'http://' . $domain);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $fb   = curl_exec($ch);
        $fbHc = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($fb !== false && $fbHc > 0 && $fbHc < 500) {
            $res['reachable'] = true;
            $res['https']     = false;
            $res['findings'][] = ['level' => 'critical', 'text' => 'Website responds on HTTP (unencrypted) only – all personal data transmitted in plaintext. Critical Section 41 violation'];
            $res['web_risk_percent'] = 85;
        } else {
            $res['findings'][] = ['level' => 'info', 'text' => 'Website unreachable at time of scan – manual online compliance verification required'];
        }
    }
    curl_close($ch);
    return $res;
}

// ============================================================
// FORM PROCESSING
// ============================================================
$assessmentResult  = false;
$reportHTML        = '';
$reportRef         = '';
$riskPercent       = 0;
$riskLevel         = '';
$riskColor         = '';
$compliancePercent = 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_dpa'])) {
    $companyName     = trim($_POST['company_name'] ?? '');
    $companyWebsite  = trim($_POST['company_website'] ?? '');
    $companyWebsite  = preg_replace('#^https?://#', '', $companyWebsite);
    $companyWebsite  = rtrim($companyWebsite, '/');
    $companyIndustry = trim($_POST['company_industry'] ?? '');
    $companySize     = trim($_POST['company_size'] ?? '');
    $websiteScanRaw  = $_POST['website_scan_data'] ?? '';
    $websiteScan     = !empty($websiteScanRaw) ? json_decode($websiteScanRaw, true) : null;

    $totalScore    = 0;
    $maxScore      = 0;
    $responses     = [];
    $answeredCount = 0;
    $categoryScores = [];

    foreach ($questions as $q) {
        $key    = 'q_' . $q['id'];
        $answer = $_POST[$key] ?? null;
        if ($answer === null) continue;

        $score       = $answerOptions[$answer] ?? 0;
        $weighted    = $score * $q['weight'];
        $maxWeighted = 3 * $q['weight'];

        $totalScore += $weighted;
        $maxScore   += $maxWeighted;

        $cat = $q['category'];
        if (!isset($categoryScores[$cat])) $categoryScores[$cat] = ['score' => 0, 'max' => 0, 'count' => 0, 'questions' => []];
        $categoryScores[$cat]['score'] += $weighted;
        $categoryScores[$cat]['max']   += $maxWeighted;
        $categoryScores[$cat]['count']++;
        $categoryScores[$cat]['questions'][] = $q['id'];

        $responses[$q['id']] = [
            'question'  => $q['question'],
            'guidance'  => $q['guidance'],
            'category'  => $q['category'],
            'answer'    => $answer,
            'emoji'     => $answerEmoji[$answer] ?? $answer,
            'score'     => $score,
            'score_max' => 3,
            'weight'    => $q['weight'],
            'reference' => $q['kenya_dpa_reference'],
            'risk_label'=> $answerRiskLabel[$score] ?? 'Unknown',
            'color'     => $answerColors[$score] ?? '#888',
        ];
        $answeredCount++;
    }

    // Base risk
    $riskPercent = ($maxScore > 0) ? round(($totalScore / $maxScore) * 100) : 5;

    // Website scan contribution (15% weight)
    if ($websiteScan && isset($websiteScan['web_risk_percent'])) {
        $webAdj      = $websiteScan['web_risk_percent'] * 0.15;
        $riskPercent = min(100, round($riskPercent + $webAdj));
    }

    // Minimum 5% risk
    $riskPercent = max(5, $riskPercent);

    // Compliance % (inverse of risk, from questionnaire only)
    $compliancePercent = ($maxScore > 0) ? round((1 - ($totalScore / $maxScore)) * 100) : 95;

    // Risk level
    if      ($riskPercent <= 20) { $riskLevel = 'Low Risk';       $riskColor = '#22c55e'; $riskClass = 'low'; }
    elseif  ($riskPercent <= 40) { $riskLevel = 'Moderate Risk';  $riskColor = '#eab308'; $riskClass = 'moderate'; }
    elseif  ($riskPercent <= 60) { $riskLevel = 'High Risk';      $riskColor = '#f97316'; $riskClass = 'high'; }
    elseif  ($riskPercent <= 80) { $riskLevel = 'Very High Risk'; $riskColor = '#ef4444'; $riskClass = 'very-high'; }
    else                          { $riskLevel = 'Critical Risk';  $riskColor = '#dc2626'; $riskClass = 'critical'; }

    // Fetch recommendations (match multiple risk levels)
    $allRecs = $pdo->query("SELECT * FROM dpa_recommendations ORDER BY CASE priority WHEN 'immediate' THEN 1 WHEN 'short-term' THEN 2 WHEN 'medium-term' THEN 3 WHEN 'long-term' THEN 4 END")->fetchAll();
    $recommendations = [];
    foreach ($allRecs as $rec) {
        $levels = array_map('trim', explode(',', $rec['risk_level']));
        if (in_array($riskClass, $levels) || in_array('all', $levels)) {
            $recommendations[] = $rec;
        }
    }

    $reportRef = 'DPA-KE-' . strtoupper(substr(md5($companyName . time()), 0, 8));
    $assessmentDate = date('Y-m-d H:i:s');

    $reportHTML = generateDPAReport(
        compact('companyName','companyWebsite','companyIndustry','companySize',
                'riskPercent','riskLevel','riskColor',
                'responses','categoryScores','categories',
                'recommendations','reportRef','assessmentDate',
                'answeredCount','websiteScan','compliancePercent')
    );

    try {
        $stmt = $pdo->prepare("INSERT INTO dpa_assessments
            (company_name,company_website,company_industry,company_size,
             risk_score,risk_level,compliance_percent,
             total_questions,answered_questions,responses,
             recommendations,category_scores,report_ref,report_html,website_scan,completed)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1)");
        $stmt->execute([
            $companyName, $companyWebsite, $companyIndustry, $companySize,
            $riskPercent, $riskLevel, $compliancePercent,
            count($questions), $answeredCount,
            json_encode($responses), json_encode($recommendations),
            json_encode($categoryScores), $reportRef, $reportHTML, $websiteScanRaw
        ]);
    } catch(Exception $e) { /* non-fatal */ }

    $assessmentResult = true;
}

// ============================================================
// REPORT GENERATOR
// ============================================================
function generateDPAReport($d) {
    extract($d);

    $industryMap = array_flip([
        'financial'=>'Financial Services / Banking','healthcare'=>'Healthcare / Medical',
        'education'=>'Education','technology'=>'Technology / IT Services',
        'government'=>'Government / Public Sector','retail'=>'Retail / E-commerce',
        'manufacturing'=>'Manufacturing','legal'=>'Legal Services',
        'hospitality'=>'Hospitality / Tourism','media'=>'Media / Telecommunications',
        'realestate'=>'Real Estate','ngo'=>'NGO / Non-Profit',
        'transport'=>'Transport / Logistics','agriculture'=>'Agriculture','other'=>'Other'
    ]);
    $sizeMap = array_flip([
        'micro'=>'1–10 (Micro)','small'=>'11–50 (Small)','medium'=>'51–250 (Medium)',
        'large'=>'251–1,000 (Large)','enterprise'=>'1,000+ (Enterprise)'
    ]);

    $industryName = $industryMap[$companyIndustry] ?? $companyIndustry;
    $sizeName     = $sizeMap[$companySize] ?? $companySize;
    $dateF = date('jS F Y', strtotime($assessmentDate));
    $timeF = date('H:i T', strtotime($assessmentDate));

    // Risk icons
    $riskIcons = ['Low Risk'=>'✅','Moderate Risk'=>'⚠️','High Risk'=>'🔶','Very High Risk'=>'🚨','Critical Risk'=>'⛔'];
    $riskIcon  = $riskIcons[$riskLevel] ?? '⚠️';

    // Compliance bar colour
    $compColor = $compliancePercent >= 80 ? '#22c55e' : ($compliancePercent >= 60 ? '#eab308' : ($compliancePercent >= 40 ? '#f97316' : '#ef4444'));

    // Single QR code
    $verifyUrl = 'https://sttpx.top/member/verify.php?ref=' . urlencode($reportRef);
    $qrPayload = urlencode(json_encode([
        'ref'           => $reportRef,
        'company'       => $companyName,
        'assessor'      => 'Christopher Khayere',
        'designation'   => 'Certified Data Protection Officer',
        'platform'      => 'AI Security Platform',
        'date'          => $dateF,
        'risk'          => $riskLevel . ' (' . $riskPercent . '%)',
        'compliance'    => $compliancePercent . '%',
        'verify'        => $verifyUrl,
    ]));
    $qrUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' . $qrPayload;

    // Priority groups for recommendations
    $pGroups = ['immediate' => [], 'short-term' => [], 'medium-term' => [], 'long-term' => []];
    foreach ($recommendations as $rec) {
        $p = strtolower($rec['priority'] ?? 'medium-term');
        $pGroups[array_key_exists($p, $pGroups) ? $p : 'medium-term'][] = $rec;
    }

    // Count answers by status
    $statusCount = [0 => 0, 1 => 0, 2 => 0, 3 => 0];
    foreach ($responses as $r) $statusCount[$r['score']]++;

    ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DPA Compliance Report – <?= htmlspecialchars($companyName) ?></title>
<style>
  @page { size: A4; margin: 18mm 15mm; }
  *  { box-sizing: border-box; }
  body { font-family: 'Segoe UI', Arial, sans-serif; color: #1a1a2e; font-size: 10.5pt; line-height: 1.65; background: #fff; margin: 0; }

  /* Cover */
  .cover { page-break-after: always; text-align: center; padding: 50px 20px; }
  .cover h1 { font-size: 26pt; letter-spacing: 2px; margin: 0; color: #1a1a2e; }
  .cover h2 { font-size: 18pt; color: #374151; margin: 6px 0 30px; font-weight: 400; }
  .cover-badge { display: inline-block; width: 160px; height: 160px; border-radius: 50%;
    border: 6px solid <?= $riskColor ?>; background: #fafafa;
    line-height: 1.2; padding-top: 40px; margin: 20px auto; }
  .cover-badge .big { font-size: 36pt; font-weight: 900; color: <?= $riskColor ?>; display: block; }
  .cover-badge .sm  { font-size: 9pt; text-transform: uppercase; color: <?= $riskColor ?>; display: block; }
  .cover-risk { font-size: 20pt; font-weight: 700; color: <?= $riskColor ?>; margin: 10px 0; }
  .cover-org  { font-size: 16pt; font-weight: 700; margin: 20px 0 4px; }
  .cover-meta { display: inline-block; text-align: left; background: #f8fafc;
    border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px 24px; margin-top: 30px; min-width: 320px; }
  .cover-meta p { margin: 4px 0; font-size: 10pt; }

  /* Sections */
  .pb { page-break-before: always; }
  h2.sec { color: #1a1a2e; font-size: 14pt; border-bottom: 3px solid <?= $riskColor ?>;
    padding-bottom: 6px; margin: 28px 0 16px; }
  h3.sub { font-size: 11pt; color: #374151; margin: 16px 0 8px; background: #f8fafc;
    padding: 6px 12px; border-left: 4px solid <?= $riskColor ?>; }

  /* Tables */
  table { width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 9.5pt; }
  th    { background: #1a1a2e; color: #fff; padding: 9px 10px; text-align: left; }
  td    { padding: 8px 10px; border: 1px solid #e2e8f0; vertical-align: top; }
  tr:nth-child(even) { background: #f8fafc; }

  /* Status badges */
  .badge { display: inline-block; padding: 2px 9px; border-radius: 12px; font-size: 8.5pt; font-weight: 600; }
  .b-compliant  { background: #d1fae5; color: #065f46; }
  .b-partial    { background: #fef3c7; color: #92400e; }
  .b-noncompliant { background: #fee2e2; color: #991b1b; }
  .b-unknown    { background: #f3e8ff; color: #6b21a8; }
  .b-pass       { background: #d1fae5; color: #065f46; }
  .b-fail       { background: #fee2e2; color: #991b1b; }
  .b-warn       { background: #fef3c7; color: #92400e; }

  /* Summary cards */
  .summary-grid { display: flex; flex-wrap: wrap; gap: 12px; margin: 16px 0; }
  .s-card { flex: 1; min-width: 120px; border-radius: 8px; padding: 14px; text-align: center; border: 1px solid #e2e8f0; }
  .s-card .num { font-size: 26pt; font-weight: 800; display: block; }
  .s-card .lbl { font-size: 8.5pt; text-transform: uppercase; color: #6b7280; }

  /* Progress bar */
  .pbar-wrap { background: #f1f5f9; border-radius: 20px; height: 14px; overflow: hidden; margin: 4px 0; }
  .pbar-fill  { height: 100%; border-radius: 20px; }

  /* Verdict box */
  .verdict { border: 2px solid <?= $riskColor ?>; border-radius: 10px; padding: 18px 22px;
    text-align: center; margin: 16px 0;
    background: <?= $riskPercent > 60 ? '#fef2f2' : ($riskPercent > 40 ? '#fffbeb' : '#f0fdf4') ?>; }

  /* Recommendations */
  .rec-card { border-left: 4px solid <?= $riskColor ?>; padding: 10px 14px; margin: 8px 0;
    background: #f8fafc; border-radius: 0 6px 6px 0; }
  .rec-card strong { display: block; margin-bottom: 4px; font-size: 10pt; }
  .rec-card small  { color: #6b7280; font-size: 8.5pt; }
  .rec-card .pen   { color: #dc2626; font-size: 8.5pt; font-weight: 600; }
  .pri-badge { display: inline-block; padding: 2px 10px; border-radius: 10px; font-size: 8pt; font-weight: 700; margin-bottom: 6px; }
  .pri-immediate  { background: #fee2e2; color: #b91c1c; }
  .pri-short-term { background: #fef3c7; color: #b45309; }
  .pri-medium-term{ background: #dbeafe; color: #1d4ed8; }
  .pri-long-term  { background: #d1fae5; color: #065f46; }

  /* Question response rows */
  .q-row td.q-ans { font-weight: 600; font-size: 9pt; }
  .q-row td.q-guidance { font-size: 8.5pt; color: #3b82f6; font-style: italic; }

  /* Web findings */
  .web-finding { padding: 8px 12px; border-radius: 4px; margin: 5px 0; font-size: 9pt; border-left: 4px solid; }
  .wf-critical { background: #fef2f2; border-color: #dc2626; color: #7f1d1d; }
  .wf-high     { background: #fff7ed; border-color: #f97316; color: #7c2d12; }
  .wf-medium   { background: #fffbeb; border-color: #eab308; color: #78350f; }
  .wf-info     { background: #f0f9ff; border-color: #0ea5e9; color: #0c4a6e; }
  .wf-positive { background: #f0fdf4; border-color: #22c55e; color: #14532d; }

  /* Signature block */
  .sig-grid { display: flex; justify-content: space-between; gap: 20px; flex-wrap: wrap; margin-top: 30px; }
  .sig-box  { flex: 1; min-width: 220px; }
  .sig-line { border-top: 1.5px solid #374151; margin-top: 55px; padding-top: 8px; font-size: 9pt; color: #6b7280; }

  /* QR / verification */
  .qr-section { text-align: center; margin-top: 40px; padding-top: 24px; border-top: 2px solid #e2e8f0; }

  /* Penalty box */
  .penalty-box { background: #fef2f2; border: 2px solid #fecaca; border-radius: 8px; padding: 16px 20px; margin: 18px 0; }
  .penalty-box h4 { color: #b91c1c; margin: 0 0 8px; }

  /* Footer */
  .footer { text-align: center; font-size: 8pt; color: #9ca3af; margin-top: 30px; padding-top: 12px; border-top: 1px solid #e2e8f0; }

  @media print {
    .no-print { display: none !important; }
    body { font-size: 9.5pt; }
  }
</style>
</head>
<body>

<!-- ===================== COVER PAGE ===================== -->
<div class="cover">
  <h1>DATA PROTECTION ACT</h1>
  <h2>Compliance Assessment Report – Kenya DPA No. 24 of 2019</h2>

  <div class="cover-badge">
    <span class="big"><?= $riskPercent ?>%</span>
    <span class="sm">Risk Score</span>
  </div>
  <div class="cover-risk"><?= $riskIcon ?> <?= $riskLevel ?></div>

  <p style="font-size:11pt;color:#6b7280;margin:6px 0">
    Compliance Level: <strong style="color:<?= $compColor ?>"><?= $compliancePercent ?>%</strong>
  </p>

  <p class="cover-org"><?= htmlspecialchars($companyName) ?></p>
  <?php if (!empty($companyWebsite)): ?>
  <p style="color:#3b82f6;font-size:11pt">🌐 <?= htmlspecialchars($companyWebsite) ?></p>
  <?php endif; ?>
  <p style="color:#6b7280"><?= $industryName ?> &nbsp;|&nbsp; <?= $sizeName ?></p>

  <div class="cover-meta">
    <p><strong>📄 Report Reference:</strong> <?= $reportRef ?></p>
    <p><strong>📅 Assessment Date:</strong> <?= $dateF ?> at <?= $timeF ?></p>
    <p><strong>⚖️ Legal Framework:</strong> Kenya Data Protection Act, No. 24 of 2019</p>
    <p><strong>🏛️ Regulator:</strong> Office of the Data Protection Commissioner (ODPC), Kenya</p>
    <p><strong>👤 Assessed By:</strong> Christopher Khayere</p>
    <p><strong>🎓 Designation:</strong> Certified Data Protection Officer</p>
    <p><strong>🏢 Platform:</strong> AI Security Platform</p>
  </div>

  <div class="qr-section" style="margin-top:30px;padding-top:20px;border-top:1px solid #e2e8f0">
    <img src="<?= $qrUrl ?>" alt="Verification QR Code" style="width:150px;height:150px;border:1px solid #e2e8f0;border-radius:8px">
    <p style="font-size:9pt;color:#6b7280;margin-top:8px">🔍 Scan to verify authenticity | <?= $reportRef ?></p>
    <p style="font-size:8.5pt;color:#3b82f6"><?= $verifyUrl ?></p>
  </div>
</div>

<!-- ===================== PAGE 2: EXECUTIVE SUMMARY ===================== -->
<div class="pb">
<h2 class="sec">📊 1. EXECUTIVE SUMMARY</h2>

<div class="verdict">
  <h3 style="margin:0 0 8px;color:<?= $riskColor ?>"><?= $riskIcon ?> Overall Risk Rating: <?= $riskLevel ?> (<?= $riskPercent ?>%)</h3>
  <p style="margin:0;font-size:10.5pt">
    Compliance Level: <strong style="color:<?= $compColor ?>"><?= $compliancePercent ?>%</strong> &nbsp;|&nbsp;
    <?= $answeredCount ?> indicators assessed across <?= count($categories) ?> compliance categories
  </p>
</div>

<p>This Data Protection Compliance Assessment was conducted for
<strong><?= htmlspecialchars($companyName) ?></strong>
<?php if (!empty($companyWebsite)): ?>(<em><?= htmlspecialchars($companyWebsite) ?></em>)<?php endif; ?>,
operating in the <strong><?= $industryName ?></strong> sector with <strong><?= $sizeName ?></strong> employees.
The assessment evaluated <strong><?= $answeredCount ?> compliance indicators</strong> against the
<strong>Kenya Data Protection Act No. 24 of 2019</strong> and the Data Protection (General) Regulations, 2021.</p>

<p>The organisation received a risk score of
<strong style="color:<?= $riskColor ?>"><?= $riskPercent ?>%</strong>,
indicating a <strong style="color:<?= $riskColor ?>"><?= $riskLevel ?></strong> posture with a
<strong style="color:<?= $compColor ?>"><?= $compliancePercent ?>% overall compliance level</strong>.
<?php if ($websiteScan && $websiteScan['reachable']): ?>
Website scanning of <em><?= htmlspecialchars($companyWebsite) ?></em> was also performed and findings have been
incorporated into this assessment.
<?php endif; ?></p>

<!-- Response summary cards -->
<div class="summary-grid">
  <div class="s-card" style="border-color:#22c55e">
    <span class="num" style="color:#22c55e"><?= $statusCount[0] ?></span>
    <span class="lbl">Compliant</span>
  </div>
  <div class="s-card" style="border-color:#eab308">
    <span class="num" style="color:#eab308"><?= $statusCount[1] ?></span>
    <span class="lbl">Partial</span>
  </div>
  <div class="s-card" style="border-color:#ef4444">
    <span class="num" style="color:#ef4444"><?= $statusCount[2] ?></span>
    <span class="lbl">Non-Compliant</span>
  </div>
  <div class="s-card" style="border-color:#a855f7">
    <span class="num" style="color:#a855f7"><?= $statusCount[3] ?></span>
    <span class="lbl">Unknown</span>
  </div>
  <div class="s-card" style="border-color:<?= $riskColor ?>">
    <span class="num" style="color:<?= $riskColor ?>"><?= $riskPercent ?>%</span>
    <span class="lbl">Risk Score</span>
  </div>
  <div class="s-card" style="border-color:<?= $compColor ?>">
    <span class="num" style="color:<?= $compColor ?>"><?= $compliancePercent ?>%</span>
    <span class="lbl">Compliance</span>
  </div>
</div>

<!-- Organisation info table -->
<table>
  <tr><th width="180">Detail</th><th>Information</th></tr>
  <tr><td><strong>🏢 Organisation</strong></td><td><?= htmlspecialchars($companyName) ?></td></tr>
  <?php if (!empty($companyWebsite)): ?>
  <tr><td><strong>🌐 Website</strong></td><td><?= htmlspecialchars($companyWebsite) ?></td></tr>
  <?php endif; ?>
  <tr><td><strong>🏭 Industry</strong></td><td><?= $industryName ?></td></tr>
  <tr><td><strong>👥 Organisation Size</strong></td><td><?= $sizeName ?></td></tr>
  <tr><td><strong>📅 Assessment Date</strong></td><td><?= $dateF ?> at <?= $timeF ?></td></tr>
  <tr><td><strong>📋 Report Reference</strong></td><td><?= $reportRef ?></td></tr>
  <tr><td><strong>⚠️ Risk Score</strong></td>
      <td style="color:<?= $riskColor ?>;font-weight:700"><?= $riskPercent ?>% – <?= $riskLevel ?></td></tr>
  <tr><td><strong>✅ Compliance Level</strong></td>
      <td style="color:<?= $compColor ?>;font-weight:700"><?= $compliancePercent ?>%</td></tr>
  <tr><td><strong>👤 Assessed By</strong></td><td>Christopher Khayere – Certified Data Protection Officer | AI Security Platform</td></tr>
  <tr><td><strong>⚖️ Framework</strong></td><td>Kenya Data Protection Act No. 24 of 2019 &amp; DPA (General) Regulations, 2021</td></tr>
</table>
</div>

<!-- ===================== PAGE 3: CATEGORY BREAKDOWN ===================== -->
<div class="pb">
<h2 class="sec">📈 2. COMPLIANCE BY CATEGORY</h2>
<p>The following table shows compliance performance across each of the <?= count($categories) ?> assessment categories.</p>

<table>
  <tr>
    <th>Category</th>
    <th width="70" style="text-align:center">Questions</th>
    <th width="140">Compliance Bar</th>
    <th width="80" style="text-align:center">Risk %</th>
    <th width="140" style="text-align:center">Status</th>
  </tr>
  <?php foreach ($categoryScores as $cat => $cs):
    $catRisk = ($cs['max'] > 0) ? round(($cs['score'] / $cs['max']) * 100) : 0;
    $catComp = 100 - $catRisk;
    if      ($catRisk <= 20) { $cStatus = '✅ Compliant';     $cBg = '#d1fae5'; $cColor = '#065f46'; $barColor = '#22c55e'; }
    elseif  ($catRisk <= 40) { $cStatus = '⚠️ Partial';       $cBg = '#fef3c7'; $cColor = '#92400e'; $barColor = '#eab308'; }
    elseif  ($catRisk <= 60) { $cStatus = '🔶 Non-Compliant'; $cBg = '#ffedd5'; $cColor = '#9a3412'; $barColor = '#f97316'; }
    elseif  ($catRisk <= 80) { $cStatus = '🚨 Very High Risk'; $cBg = '#fee2e2'; $cColor = '#991b1b'; $barColor = '#ef4444'; }
    else                      { $cStatus = '⛔ Critical';      $cBg = '#fecaca'; $cColor = '#7f1d1d'; $barColor = '#dc2626'; }
  ?>
  <tr style="background:<?= $cBg ?>">
    <td><strong><?= htmlspecialchars($cat) ?></strong></td>
    <td style="text-align:center"><?= $cs['count'] ?></td>
    <td>
      <div class="pbar-wrap">
        <div class="pbar-fill" style="width:<?= $catComp ?>%;background:<?= $barColor ?>"></div>
      </div>
      <small style="color:#6b7280"><?= $catComp ?>% compliant</small>
    </td>
    <td style="text-align:center;color:<?= $barColor ?>;font-weight:700"><?= $catRisk ?>%</td>
    <td style="text-align:center;color:<?= $cColor ?>;font-weight:600"><?= $cStatus ?></td>
  </tr>
  <?php endforeach; ?>
</table>

<!-- Overall compliance bar -->
<h3 class="sub">Overall Compliance Indicator</h3>
<div class="pbar-wrap" style="height:22px">
  <div class="pbar-fill" style="width:<?= $compliancePercent ?>%;background:<?= $compColor ?>"></div>
</div>
<p style="text-align:center;font-size:9.5pt;color:#6b7280;margin-top:6px">
  <?= $compliancePercent ?>% overall compliance with Kenya DPA 2019
</p>
</div>

<!-- ===================== PAGE 4+: DETAILED Q&A ===================== -->
<div class="pb">
<h2 class="sec">📝 3. DETAILED FINDINGS & RESPONSES</h2>
<p>The table below captures every assessment question, the organisation's recorded response, compliance status, risk rating, and the applicable Kenya DPA 2019 section reference.</p>

<?php foreach ($categories as $cat => $qs): ?>
<h3 class="sub"><?= htmlspecialchars($cat) ?></h3>
<table>
  <thead>
    <tr>
      <th width="32%">Assessment Question</th>
      <th width="14%">Response</th>
      <th width="10%">Risk</th>
      <th width="22%">Compliance Guidance</th>
      <th width="22%">DPA Reference</th>
    </tr>
  </thead>
  <tbody>
  <?php foreach ($qs as $q):
    $r = $responses[$q['id']] ?? null;
    if (!$r) continue;
    $badgeClass = ['Compliant'=>'b-compliant','Partial'=>'b-partial','Non-Compliant'=>'b-noncompliant','Unknown'=>'b-unknown'][$r['risk_label']] ?? 'b-unknown';
    $riskTxt = ['Compliant'=>'Low (0/3)','Partial'=>'Medium (1/3)','Non-Compliant'=>'High (2/3)','Unknown'=>'Critical (3/3)'][$r['risk_label']] ?? ($r['score'].'/3');
  ?>
  <tr class="q-row">
    <td style="font-size:9pt"><strong><?= htmlspecialchars($r['question']) ?></strong></td>
    <td class="q-ans" style="color:<?= $r['color'] ?>;text-align:center">
      <span class="badge <?= $badgeClass ?>"><?= $r['emoji'] ?></span>
    </td>
    <td style="color:<?= $r['color'] ?>;font-weight:700;text-align:center;font-size:9pt"><?= $riskTxt ?></td>
    <td class="q-guidance"><?= htmlspecialchars($r['guidance']) ?></td>
    <td style="font-size:8.5pt;color:#374151"><?= htmlspecialchars($r['reference']) ?></td>
  </tr>
  <?php endforeach; ?>
  </tbody>
</table>
<?php endforeach; ?>
</div>

<!-- ===================== WEBSITE SCAN SECTION ===================== -->
<?php if ($websiteScan): ?>
<div class="pb">
<h2 class="sec">🌐 4. WEBSITE COMPLIANCE SCAN – <?= htmlspecialchars($companyWebsite ?: 'N/A') ?></h2>
<p>An automated security and privacy compliance scan was performed on
<strong><?= htmlspecialchars($companyWebsite) ?></strong>
on <?= $dateF ?> at <?= $timeF ?>. The scan evaluates technical compliance indicators required under the Kenya DPA 2019.</p>

<?php if (!$websiteScan['reachable']): ?>
<div class="web-finding wf-high">
  <strong>⚠️ Website Unreachable:</strong> The domain <em><?= htmlspecialchars($companyWebsite) ?></em>
  could not be reached at the time of scanning. Online DPA compliance indicators could not be verified.
  Manual verification of website compliance is required.
</div>
<?php else: ?>

<!-- Overall website risk -->
<?php
$wr = $websiteScan['web_risk_percent'] ?? 0;
$wrColor = $wr <= 20 ? '#22c55e' : ($wr <= 50 ? '#eab308' : '#ef4444');
$wrLabel = $wr <= 20 ? '✅ Good' : ($wr <= 50 ? '⚠️ Needs Improvement' : '🔴 Critical Issues Found');
?>
<div class="verdict" style="margin-bottom:16px">
  <strong>Website DPA Risk Score: <span style="color:<?= $wrColor ?>"><?= $wr ?>% – <?= $wrLabel ?></span></strong><br>
  <small>HTTPS: <?= $websiteScan['https'] ? '✅ Yes' : '❌ No' ?> &nbsp;|&nbsp;
         SSL Valid: <?= $websiteScan['ssl_valid'] ? '✅ Yes' : '❌ No' ?> &nbsp;|&nbsp;
         Cookies Found: <?= $websiteScan['cookie_count'] ?> &nbsp;|&nbsp;
         Forms: <?= $websiteScan['forms_count'] ?></small>
</div>

<!-- Quick summary table -->
<h3 class="sub">Quick Compliance Checks</h3>
<table>
  <tr><th>Check</th><th>Status</th><th>Importance</th><th>DPA Section</th></tr>
  <tr>
    <td><strong>HTTPS / TLS Encryption</strong></td>
    <td><?= $websiteScan['https'] ? '<span class="badge b-pass">✅ Active</span>' : '<span class="badge b-fail">❌ Not Found</span>' ?></td>
    <td>Critical – all personal data must be encrypted in transit</td>
    <td>Section 41</td>
  </tr>
  <tr>
    <td><strong>Valid SSL Certificate</strong></td>
    <td><?= $websiteScan['ssl_valid'] ? '<span class="badge b-pass">✅ Valid</span>' : '<span class="badge b-fail">❌ Invalid/Expired</span>' ?></td>
    <td>Critical – invalid certificate exposes users to MITM attacks</td>
    <td>Section 41</td>
  </tr>
  <tr>
    <td><strong>Privacy Policy</strong></td>
    <td><?= $websiteScan['privacy']['privacy_policy'] ? '<span class="badge b-pass">✅ Detected</span>' : '<span class="badge b-fail">❌ Not Found</span>' ?></td>
    <td>Mandatory – must be prominently displayed</td>
    <td>Section 29</td>
  </tr>
  <tr>
    <td><strong>Cookie Consent Mechanism</strong></td>
    <td><?= $websiteScan['privacy']['cookie_consent'] ? '<span class="badge b-pass">✅ Implemented</span>' : '<span class="badge b-warn">⚠️ Not Detected</span>' ?></td>
    <td>Required for any non-essential or tracking cookies</td>
    <td>Section 32</td>
  </tr>
  <tr>
    <td><strong>Tracking Cookies Present</strong></td>
    <td><?= !empty($websiteScan['tracking_cookies']) ? '<span class="badge b-warn">⚠️ '.count($websiteScan['tracking_cookies']).' Found</span>' : '<span class="badge b-pass">✅ None Detected</span>' ?></td>
    <td>Require explicit opt-in consent if present</td>
    <td>Section 32</td>
  </tr>
  <tr>
    <td><strong>Data Collection Forms</strong></td>
    <td><?= $websiteScan['forms_count'] > 0 ? '<span class="badge b-warn">⚠️ '.$websiteScan['forms_count'].' Form(s)</span>' : '<span class="badge b-pass">✅ None</span>' ?></td>
    <td>Each form must have point-of-collection privacy notice</td>
    <td>Section 29</td>
  </tr>
  <tr>
    <td><strong>Kenya DPA / ODPC Reference</strong></td>
    <td><?= $websiteScan['privacy']['dpa_mention'] ? '<span class="badge b-pass">✅ Found</span>' : '<span class="badge b-warn">⚠️ Not Found</span>' ?></td>
    <td>Demonstrates local compliance awareness</td>
    <td>Section 29</td>
  </tr>
</table>

<!-- Security Headers -->
<h3 class="sub">🔒 HTTP Security Headers Analysis</h3>
<table>
  <tr><th>Header</th><th>Status</th><th>Purpose</th><th>DPA Link</th></tr>
  <?php foreach ($websiteScan['sec_headers'] as $hdr => $info): ?>
  <tr>
    <td><code><?= htmlspecialchars($hdr) ?></code></td>
    <td><?= $info['present'] ? '<span class="badge b-pass">✅ Present</span>' : '<span class="badge b-fail">❌ Missing</span>' ?></td>
    <td style="font-size:8.5pt"><?= htmlspecialchars($info['desc']) ?></td>
    <td><?= $info['ref'] ?></td>
  </tr>
  <?php endforeach; ?>
</table>

<!-- Findings -->
<?php if (!empty($websiteScan['findings'])): ?>
<h3 class="sub">⚠️ Website Compliance Issues Requiring Action</h3>
<?php foreach ($websiteScan['findings'] as $f):
  $lvl = is_array($f) ? ($f['level'] ?? 'info') : 'info';
  $txt = is_array($f) ? ($f['text'] ?? $f) : $f;
  $cls = ['critical'=>'wf-critical','high'=>'wf-high','medium'=>'wf-medium','info'=>'wf-info'][$lvl] ?? 'wf-info';
  $icon = ['critical'=>'🔴','high'=>'🟠','medium'=>'🟡','info'=>'🔵'][$lvl] ?? '🔵';
?>
<div class="web-finding <?= $cls ?>"><?= $icon ?> <?= htmlspecialchars($txt) ?></div>
<?php endforeach; ?>
<?php endif; ?>

<!-- Positives -->
<?php if (!empty($websiteScan['positives'])): ?>
<h3 class="sub">✅ Website Compliance Positives</h3>
<?php foreach ($websiteScan['positives'] as $pos): ?>
<div class="web-finding wf-positive">✅ <?= htmlspecialchars($pos) ?></div>
<?php endforeach; ?>
<?php endif; ?>

<?php if (!empty($websiteScan['ssl_issuer'])): ?>
<p style="font-size:8.5pt;color:#6b7280;margin-top:8px">
  <strong>SSL Certificate Issuer:</strong> <?= htmlspecialchars($websiteScan['ssl_issuer']) ?>
  <?php if (!empty($websiteScan['ssl_expiry'])): ?> | <strong>Expiry:</strong> <?= htmlspecialchars($websiteScan['ssl_expiry']) ?><?php endif; ?>
</p>
<?php endif; ?>

<?php endif; // reachable ?>
</div>
<?php endif; // websiteScan ?>

<!-- ===================== RECOMMENDATIONS ===================== -->
<div class="pb">
<h2 class="sec">🎯 5. PRIORITISED RECOMMENDATIONS</h2>
<p>The following action plan is based on assessment findings, prioritised by urgency and potential regulatory impact.
<strong>Failure to act exposes <?= htmlspecialchars($companyName) ?> to penalties up to KES 5,000,000 under the Kenya DPA 2019.</strong></p>

<?php
$pConfig = [
  'immediate'   => ['label' => '🔴 IMMEDIATE – Within 30 Days',  'cls' => 'pri-immediate'],
  'short-term'  => ['label' => '🟠 SHORT-TERM – 30 to 90 Days',  'cls' => 'pri-short-term'],
  'medium-term' => ['label' => '🔵 MEDIUM-TERM – 3 to 6 Months', 'cls' => 'pri-medium-term'],
  'long-term'   => ['label' => '🟢 LONG-TERM – 6 to 12 Months', 'cls' => 'pri-long-term'],
];
foreach ($pConfig as $pKey => $pCfg):
  if (empty($pGroups[$pKey])) continue;
?>
<h3 class="sub"><?= $pCfg['label'] ?></h3>
<?php foreach ($pGroups[$pKey] as $rec): ?>
<div class="rec-card">
  <span class="pri-badge <?= $pCfg['cls'] ?>"><?= strtoupper(str_replace('-',' ',$pKey)) ?></span>
  <?php if (!empty($rec['category'])): ?>
  <span style="font-size:8pt;color:#6b7280;margin-left:8px">[<?= htmlspecialchars($rec['category']) ?>]</span>
  <?php endif; ?>
  <strong><?= htmlspecialchars($rec['recommendation']) ?></strong>
  <?php if (!empty($rec['legal_reference'])): ?>
  <small>📜 Legal Basis: <?= htmlspecialchars($rec['legal_reference']) ?></small><br>
  <?php endif; ?>
  <?php if (!empty($rec['timeframe'])): ?>
  <small>⏱️ Target Timeframe: <?= htmlspecialchars($rec['timeframe']) ?></small><br>
  <?php endif; ?>
  <?php if (!empty($rec['penalty_risk'])): ?>
  <span class="pen">⚠️ Penalty Exposure: <?= htmlspecialchars($rec['penalty_risk']) ?></span>
  <?php endif; ?>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
</div>

<!-- ===================== LEGAL PENALTIES ===================== -->
<div class="pb">
<h2 class="sec">⚖️ 6. LEGAL PENALTIES – KENYA DATA PROTECTION ACT 2019</h2>
<p>Non-compliance with the Kenya DPA 2019 carries significant financial and criminal penalties enforced by the ODPC:</p>

<table>
  <tr><th>Offence</th><th>Penalty</th><th>Section</th><th>Type</th></tr>
  <tr><td>General DPA violations (data protection principles)</td>
      <td style="color:#b91c1c;font-weight:700">KES 5,000,000 or 1% annual turnover</td>
      <td>Section 64</td><td>Civil / Administrative</td></tr>
  <tr><td>Unlawful processing of personal data</td>
      <td style="color:#b91c1c;font-weight:700">KES 3,000,000 fine + up to 10 years imprisonment</td>
      <td>Section 65</td><td>Criminal</td></tr>
  <tr><td>Failure to register as Data Controller/Processor with ODPC</td>
      <td style="color:#b91c1c;font-weight:700">KES 1,000,000 mandatory fine</td>
      <td>Section 18(5)</td><td>Administrative</td></tr>
  <tr><td>Failure to notify ODPC of a data breach within 72 hours</td>
      <td style="color:#b91c1c;font-weight:700">KES 5,000,000 fine</td>
      <td>Section 43(3)</td><td>Administrative</td></tr>
  <tr><td>Obstruction of ODPC investigation</td>
      <td style="color:#b91c1c;font-weight:700">KES 2,000,000 fine + up to 5 years imprisonment</td>
      <td>Section 67</td><td>Criminal</td></tr>
  <tr><td>Unlawful cross-border data transfer</td>
      <td style="color:#b91c1c;font-weight:700">KES 5,000,000 per unlawful transfer</td>
      <td>Section 48-49</td><td>Administrative</td></tr>
  <tr><td>Civil compensation to data subjects for damages</td>
      <td style="color:#b91c1c;font-weight:700">Court-awarded damages (unlimited)</td>
      <td>Section 62</td><td>Civil</td></tr>
</table>

<div class="penalty-box">
  <h4>⚠️ Important Legal Notice for <?= htmlspecialchars($companyName) ?></h4>
  <p style="margin:0">Based on this assessment (<?= $riskLevel ?> – <?= $riskPercent ?>% risk),
  <strong><?= htmlspecialchars($companyName) ?></strong> could face regulatory action and penalties up to
  <strong style="color:#b91c1c">KES 5,000,000</strong> for identified non-compliance areas.
  Immediate remediation of all <strong>IMMEDIATE</strong> priority items is strongly advised.
  This report should be presented to senior management and the Board of Directors.</p>
</div>
</div>

<!-- ===================== SIGNATURE & VERIFICATION ===================== -->
<div class="pb">
<h2 class="sec">✅ 7. SIGNATURES & REPORT VERIFICATION</h2>

<div class="sig-grid">
  <div class="sig-box">
    <p style="font-weight:700;margin-bottom:4px">Organisation Representative:</p>
    <p><?= htmlspecialchars($companyName) ?></p>
    <p style="color:#6b7280;font-size:9pt">Data Protection Officer / Chief Executive</p>
    <div class="sig-line">Signature &amp; Official Stamp</div>
    <p style="font-size:9pt;margin-top:6px">Date: ____________________</p>
  </div>

  <div class="sig-box">
    <p style="font-weight:700;margin-bottom:4px">Assessment Conducted By:</p>
    <p style="font-weight:700;font-size:11pt">Christopher Khayere</p>
    <p style="font-size:9.5pt"><strong>Certified Data Protection Officer</strong></p>
    <p style="font-size:9pt;color:#6b7280">AI Security Platform</p>
    <p style="font-size:9pt">DPO Certificate No: DPO-KE-<?= date('Y') ?>-<?= substr($reportRef, -4) ?></p>
    <div class="sig-line">Digitally Signed – <?= $dateF ?></div>
  </div>
</div>

<div class="qr-section">
  <h3 style="margin-bottom:12px">🔐 Report Authenticity Verification</h3>
  <p>This report is registered under reference <strong><?= $reportRef ?></strong> in the AI Security Platform database.</p>
  <p>Verify the authenticity of this report and the assessor's credentials by scanning the QR code below
  or visiting the verification URL:</p>
  <p style="color:#3b82f6;font-size:10pt;font-weight:600;word-break:break-all;margin:10px 0"><?= $verifyUrl ?></p>
  <img src="<?= $qrUrl ?>" alt="Report Verification QR Code" style="width:170px;height:170px;border:1px solid #e2e8f0;border-radius:8px;margin-top:12px">
  <p style="font-size:8.5pt;color:#6b7280;margin-top:8px">
    Scan to verify: Report Reference, Assessor Credentials, Risk Score, Compliance Level, and Assessment Date
  </p>
  <p style="font-size:8pt;margin-top:12px;color:#9ca3af">
    <em>Report Reference: <?= $reportRef ?> | Generated: <?= $dateF ?> | <?= $timeF ?> | Framework: Kenya DPA No. 24 of 2019</em>
  </p>
</div>

<div class="footer">
  <p><strong>AI Security Platform v4.0</strong> &copy; <?= date('Y') ?> Christopher Khayere. All rights reserved.</p>
  <p>Report: <?= $reportRef ?> | <?= $dateF ?> | Kenya Data Protection Act No. 24 of 2019 | ODPC Kenya</p>
  <p style="margin-top:6px"><strong>Disclaimer:</strong> This assessment is based on information provided and automated technical scans conducted on <?= $dateF ?>.
  Results reflect the state of compliance at the time of assessment. This report does not constitute legal advice.
  For formal legal opinion, consult qualified legal counsel. Christopher Khayere is a Certified Data Protection Officer
  operating under the AI Security Platform. All findings should be reviewed with the organisation's legal advisors.</p>
</div>
</div>

</body>
</html>
<?php
    return ob_get_clean();
}
// ============================================================
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>📋 DPA Kenya Compliance – AI Security Platform</title>
<style>
  *{margin:0;padding:0;box-sizing:border-box}
  body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#0a0a0f;color:#e4e4e7;min-height:100vh}
  .container{max-width:1020px;margin:0 auto;padding:20px}

  /* NAVBAR */
  .navbar{background:#13131a;border:1px solid rgba(255,255,255,0.06);border-radius:12px;padding:15px 22px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px;margin-bottom:22px}
  .navbar h1{font-size:17px;background:linear-gradient(135deg,#06b6d4,#14b8a6);-webkit-background-clip:text;-webkit-text-fill-color:transparent;font-weight:700}
  .nav-links{display:flex;gap:6px;flex-wrap:wrap}
  .nav-links a{color:#a1a1aa;text-decoration:none;padding:6px 12px;border:1px solid rgba(255,255,255,0.1);border-radius:6px;font-size:11px;transition:all .2s}
  .nav-links a:hover,.nav-links a.active{background:rgba(6,182,212,0.1);border-color:#06b6d4;color:#06b6d4}
  .nav-links a.logout{background:rgba(239,68,68,0.08);color:#ef4444;border-color:rgba(239,68,68,0.3)}
  .nav-links a.logout:hover{background:rgba(239,68,68,0.2)}

  /* CARDS */
  .card{background:rgba(255,255,255,0.025);border:1px solid rgba(255,255,255,0.07);border-radius:12px;padding:24px;margin-bottom:18px}
  .card h3{color:#06b6d4;font-size:15px;margin-bottom:16px;padding-bottom:10px;border-bottom:1px solid rgba(255,255,255,0.06);display:flex;align-items:center;gap:8px}

  /* FORM */
  .form-row{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:10px}
  @media(max-width:640px){.form-row{grid-template-columns:1fr}}
  .form-group{margin-bottom:10px}
  .form-group label{display:block;color:#71717a;font-size:10px;text-transform:uppercase;letter-spacing:.8px;margin-bottom:5px;font-weight:600}
  .form-group input,.form-group select{width:100%;padding:10px 14px;background:rgba(0,0,0,0.35);border:1px solid rgba(255,255,255,0.1);border-radius:8px;color:#e4e4e7;font-size:13px;transition:border-color .2s}
  .form-group input:focus,.form-group select:focus{outline:none;border-color:#06b6d4;box-shadow:0 0 0 3px rgba(6,182,212,0.1)}
  .form-group small{color:#52525b;font-size:10px;margin-top:3px;display:block}

  /* PROGRESS */
  .sticky-progress{position:sticky;top:0;z-index:100;background:#13131a;border:1px solid rgba(255,255,255,0.08);border-radius:10px;padding:14px 20px;margin-bottom:18px;display:flex;align-items:center;gap:16px;flex-wrap:wrap;box-shadow:0 4px 20px rgba(0,0,0,0.4)}
  .prog-bar-wrap{flex:1;min-width:160px;background:rgba(255,255,255,0.06);border-radius:20px;height:10px;overflow:hidden}
  .prog-bar-fill{height:100%;background:linear-gradient(90deg,#06b6d4,#14b8a6);border-radius:20px;transition:width .3s}
  .prog-text{font-size:12px;color:#a1a1aa;white-space:nowrap}
  .prog-pct{font-size:14px;font-weight:700;color:#06b6d4;white-space:nowrap}

  /* SCAN BANNER */
  .scan-banner{background:rgba(6,182,212,0.08);border:1px solid rgba(6,182,212,0.25);border-radius:8px;padding:10px 16px;font-size:12px;color:#67e8f9;display:none;align-items:center;gap:10px;margin-bottom:14px}
  .scan-banner.show{display:flex}
  .scan-banner.done{background:rgba(34,197,94,0.08);border-color:rgba(34,197,94,0.25);color:#86efac}
  .scan-banner.error{background:rgba(239,68,68,0.08);border-color:rgba(239,68,68,0.25);color:#fca5a5}
  .spinner{width:14px;height:14px;border:2px solid rgba(6,182,212,0.3);border-top-color:#06b6d4;border-radius:50%;animation:spin .6s linear infinite;flex-shrink:0}
  @keyframes spin{to{transform:rotate(360deg)}}

  /* SCAN RESULTS CARD */
  .scan-results{background:rgba(0,0,0,0.25);border:1px solid rgba(255,255,255,0.07);border-radius:10px;padding:16px;margin-bottom:16px;display:none}
  .scan-results.show{display:block}
  .scan-results h4{color:#06b6d4;font-size:12px;margin-bottom:10px;text-transform:uppercase;letter-spacing:.5px}
  .scan-grid{display:flex;flex-wrap:wrap;gap:8px}
  .scan-chip{padding:5px 12px;border-radius:20px;font-size:11px;font-weight:600;display:flex;align-items:center;gap:5px}
  .chip-pass{background:rgba(34,197,94,0.15);color:#86efac;border:1px solid rgba(34,197,94,0.3)}
  .chip-fail{background:rgba(239,68,68,0.15);color:#fca5a5;border:1px solid rgba(239,68,68,0.3)}
  .chip-warn{background:rgba(234,179,8,0.15);color:#fde68a;border:1px solid rgba(234,179,8,0.3)}
  .scan-findings{margin-top:10px}
  .scan-finding-item{font-size:11px;padding:5px 10px;border-radius:4px;margin:3px 0;border-left:3px solid}
  .sf-critical{background:rgba(220,38,38,0.1);border-color:#dc2626;color:#fca5a5}
  .sf-high{background:rgba(249,115,22,0.1);border-color:#f97316;color:#fdba74}
  .sf-medium{background:rgba(234,179,8,0.1);border-color:#eab308;color:#fde68a}
  .sf-positive{background:rgba(34,197,94,0.1);border-color:#22c55e;color:#86efac}

  /* QUESTIONS */
  .category-header{background:rgba(6,182,212,0.06);border:1px solid rgba(6,182,212,0.15);border-radius:8px;padding:12px 16px;margin-bottom:4px;display:flex;justify-content:space-between;align-items:center}
  .category-header h3{color:#67e8f9;font-size:14px;margin:0}
  .category-count{font-size:11px;color:#52525b;background:rgba(255,255,255,0.05);padding:3px 10px;border-radius:10px}

  .q-block{padding:14px 16px;background:rgba(0,0,0,0.2);border-radius:8px;border-left:3px solid rgba(6,182,212,0.2);margin-bottom:8px;transition:border-color .2s}
  .q-block.answered{border-left-color:#14b8a6}
  .q-meta{display:flex;justify-content:space-between;margin-bottom:5px;flex-wrap:wrap;gap:4px}
  .q-num{font-size:9px;color:#06b6d4;text-transform:uppercase;letter-spacing:.8px;font-weight:600}
  .q-ref{font-size:9px;color:#52525b}
  .q-text{font-size:13.5px;font-weight:500;margin-bottom:6px;line-height:1.5}
  .q-guidance{font-size:11px;color:#60a5fa;margin-bottom:8px;padding:6px 10px;background:rgba(59,130,246,0.06);border-radius:4px;border-left:2px solid rgba(59,130,246,0.3)}

  .options{display:grid;grid-template-columns:repeat(4,1fr);gap:6px}
  @media(max-width:600px){.options{grid-template-columns:1fr 1fr}}
  .opt input[type=radio]{display:none}
  .opt label{display:block;padding:9px 6px;background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);border-radius:6px;cursor:pointer;text-align:center;transition:all .2s;font-size:11.5px;line-height:1.3}
  .opt label:hover{background:rgba(6,182,212,0.07);border-color:rgba(6,182,212,0.3)}
  .opt input[type=radio]:checked + label.yes{background:rgba(34,197,94,0.15);border-color:#22c55e;color:#86efac;font-weight:600}
  .opt input[type=radio]:checked + label.partial{background:rgba(234,179,8,0.15);border-color:#eab308;color:#fde68a;font-weight:600}
  .opt input[type=radio]:checked + label.no{background:rgba(239,68,68,0.15);border-color:#ef4444;color:#fca5a5;font-weight:600}
  .opt input[type=radio]:checked + label.dontknow{background:rgba(168,85,247,0.15);border-color:#a855f7;color:#d8b4fe;font-weight:600}

  /* SUBMIT */
  .btn-submit{background:linear-gradient(135deg,#06b6d4,#14b8a6);color:#fff;border:none;padding:16px 30px;border-radius:10px;font-size:15px;font-weight:700;cursor:pointer;width:100%;margin-top:20px;transition:opacity .2s;letter-spacing:.3px}
  .btn-submit:disabled{opacity:.35;cursor:not-allowed}
  .btn-submit:not(:disabled):hover{opacity:.9}

  /* RESULT */
  .result-header{text-align:center;padding:30px}
  .risk-ring{width:150px;height:150px;border-radius:50%;border:7px solid var(--rc);display:inline-flex;flex-direction:column;align-items:center;justify-content:center;margin:0 auto 16px}
  .risk-ring .rn{font-size:34pt;font-weight:900;color:var(--rc)}
  .risk-ring .rl{font-size:10px;text-transform:uppercase;color:var(--rc)}
  .btn-print{background:#fff;color:#000;border:none;padding:11px 22px;border-radius:8px;font-weight:700;cursor:pointer;margin:6px;font-size:13px}
  .btn-pdf{background:#ef4444;color:#fff;border:none;padding:11px 22px;border-radius:8px;font-weight:700;cursor:pointer;margin:6px;font-size:13px}
  .btn-new{background:rgba(255,255,255,0.08);color:#e4e4e7;border:1px solid rgba(255,255,255,0.1);padding:11px 22px;border-radius:8px;font-weight:700;cursor:pointer;margin:6px;font-size:13px;text-decoration:none;display:inline-block}
  .report-wrap{background:#fff;color:#1a1a2e;border-radius:12px;margin-top:20px;max-height:750px;overflow-y:auto;padding:30px}

  @media print{
    body{background:#fff;color:#1a1a2e}
    .navbar,.sticky-progress,.scan-banner,.scan-results,.btn-submit,.btn-print,.btn-pdf,.btn-new,.card:not(.report-card){display:none!important}
    .report-wrap{max-height:none;overflow:visible;padding:0;border-radius:0}
  }
</style>
</head>
<body>
<div class="container">

  <!-- NAVBAR -->
  <nav class="navbar">
    <h1>📋 DPA Kenya Compliance Assessment</h1>
    <div class="nav-links">
      <a href="index.php">Dashboard</a>
      <a href="dpa.php" class="active">DPA</a>
      <a href="attack.php">Attack</a>
      <a href="defense.php">Defense</a>
      <a href="cupp.php">CUPP</a>
      <a href="reports.php">Reports</a>
      <a href="index.php?logout=1" class="logout">Logout</a>
    </div>
  </nav>

<?php if (!$assessmentResult): ?>

  <!-- SCAN BANNER (sticky, real-time feedback) -->
  <div class="scan-banner" id="scanBanner">
    <div class="spinner" id="scanSpinner"></div>
    <span id="scanMsg">Scanning website…</span>
  </div>

  <!-- SCAN RESULTS CARD -->
  <div class="scan-results card" id="scanResults">
    <h4>🌐 Live Website Scan Results</h4>
    <div class="scan-grid" id="scanChips"></div>
    <div class="scan-findings" id="scanFindings"></div>
  </div>

  <!-- ORG DETAILS -->
  <div class="card">
    <h3>🏢 Organisation Details</h3>
    <form method="POST" id="dpaForm" onsubmit="return beforeSubmit()">
      <div class="form-row">
        <div class="form-group">
          <label>Company / Organisation Name *</label>
          <input type="text" name="company_name" id="company_name" placeholder="e.g., Acme Kenya Ltd" required autocomplete="organization">
        </div>
        <div class="form-group">
          <label>Website (enables live DPA scan)</label>
          <input type="text" name="company_website" id="company_website" placeholder="www.example.co.ke" autocomplete="url">
          <small>Enter domain without http:// — we scan for DPA compliance as you answer questions</small>
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>Industry / Sector *</label>
          <select name="company_industry" required>
            <option value="">— Select Industry —</option>
            <?php foreach ($industries as $label => $val): ?>
            <option value="<?= $val ?>"><?= htmlspecialchars($label) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Organisation Size *</label>
          <select name="company_size" required>
            <option value="">— Select Size —</option>
            <?php foreach ($companySizes as $label => $val): ?>
            <option value="<?= $val ?>"><?= htmlspecialchars($label) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <input type="hidden" name="website_scan_data" id="website_scan_data">
  </div>

  <!-- STICKY PROGRESS -->
  <div class="sticky-progress" id="stickyProg">
    <span class="prog-pct" id="progPct">0%</span>
    <div class="prog-bar-wrap"><div class="prog-bar-fill" id="progFill" style="width:0%"></div></div>
    <span class="prog-text" id="progText">0 / <?= count($questions) ?> questions answered</span>
    <span style="font-size:11px;color:#52525b">|</span>
    <span class="prog-text" id="scanStatusInline"></span>
  </div>

  <!-- QUESTIONS BY CATEGORY -->
  <?php foreach ($categories as $cat => $qs): ?>
  <div class="card">
    <div class="category-header">
      <h3><?= htmlspecialchars($cat) ?></h3>
      <span class="category-count"><?= count($qs) ?> questions</span>
    </div>
    <?php foreach ($qs as $q): ?>
    <div class="q-block" id="qblock_<?= $q['id'] ?>">
      <div class="q-meta">
        <span class="q-num">Q<?= $q['sort_order'] ?> · <?= htmlspecialchars($q['category']) ?></span>
        <span class="q-ref">📜 <?= htmlspecialchars($q['kenya_dpa_reference']) ?></span>
      </div>
      <div class="q-text"><?= htmlspecialchars($q['question']) ?></div>
      <?php if (!empty($q['guidance'])): ?>
      <div class="q-guidance">💡 <?= htmlspecialchars($q['guidance']) ?></div>
      <?php endif; ?>
      <div class="options">
        <?php foreach (['Yes', 'Partially', 'No', "I Don't Know"] as $opt):
          $oid   = 'q_' . $q['id'] . '_' . preg_replace('/[^a-zA-Z0-9]/', '_', $opt);
          $css   = ['Yes'=>'yes','Partially'=>'partial','No'=>'no',"I Don't Know"=>'dontknow'][$opt];
          $emoji = ['Yes'=>'✅ Yes','Partially'=>'⚠️ Partly','No'=>'❌ No',"I Don't Know"=>'❓ Unknown'][$opt];
        ?>
        <div class="opt">
          <input type="radio" name="q_<?= $q['id'] ?>" value="<?= htmlspecialchars($opt) ?>" id="<?= $oid ?>"
                 onchange="onAnswer(<?= $q['id'] ?>)" required>
          <label for="<?= $oid ?>" class="<?= $css ?>"><?= $emoji ?></label>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endforeach; ?>

      <button type="submit" name="submit_dpa" class="btn-submit" id="submitBtn" disabled>
        📊 GENERATE COMPREHENSIVE DPA COMPLIANCE REPORT
      </button>
    </form>

<?php else: ?>

  <!-- RESULT -->
  <div class="card result-header" style="--rc:<?= $riskColor ?>">
    <h3 style="justify-content:center">📊 Assessment Complete – <?= htmlspecialchars($companyName) ?></h3>
    <div class="risk-ring">
      <span class="rn"><?= $riskPercent ?>%</span>
      <span class="rl">Risk</span>
    </div>
    <p style="font-size:20px;font-weight:700;color:<?= $riskColor ?>;margin-bottom:6px">
      <?= htmlspecialchars($riskLevel) ?>
    </p>
    <p style="color:#a1a1aa;margin-bottom:16px">
      Compliance: <strong style="color:#22c55e"><?= $compliancePercent ?>%</strong> &nbsp;|&nbsp;
      Report Ref: <strong style="color:#06b6d4"><?= $reportRef ?></strong>
    </p>
    <button onclick="window.print()" class="btn-print">🖨️ Print / Save PDF</button>
    <button onclick="downloadReport()" class="btn-pdf">📥 Download Report</button>
    <a href="dpa.php" class="btn-new">🔄 New Assessment</a>
  </div>

  <div class="card report-card">
    <div class="report-wrap" id="reportPreview">
      <?= $reportHTML ?>
    </div>
  </div>

<?php endif; ?>

</div><!-- /container -->

<script>
const TOTAL = <?= count($questions) ?>;
let answered = 0;
let answeredIds = new Set();
let scanData = null;
let scanDone = false;
let scanTimeout = null;

function onAnswer(qId) {
  const block = document.getElementById('qblock_' + qId);
  if (!answeredIds.has(qId)) {
    answeredIds.add(qId);
    answered++;
    if (block) block.classList.add('answered');
  }
  updateProgress();
}

function updateProgress() {
  const pct = Math.round((answered / TOTAL) * 100);
  document.getElementById('progFill').style.width = pct + '%';
  document.getElementById('progPct').textContent = pct + '%';
  document.getElementById('progText').textContent = answered + ' / ' + TOTAL + ' questions answered';
  document.getElementById('submitBtn').disabled = (answered < TOTAL);
}

// Website scan
const domainInput = document.getElementById('company_website');
if (domainInput) {
  domainInput.addEventListener('input', function() {
    clearTimeout(scanTimeout);
    const d = this.value.trim().replace(/^https?:\/\//,'').replace(/\/$/,'');
    if (d.length >= 4 && d.includes('.')) {
      scanTimeout = setTimeout(() => startScan(d), 900);
    }
  });
}

function startScan(domain) {
  const banner = document.getElementById('scanBanner');
  const msg    = document.getElementById('scanMsg');
  const spin   = document.getElementById('scanSpinner');
  const inline = document.getElementById('scanStatusInline');

  banner.className = 'scan-banner show';
  spin.style.display = 'block';
  msg.textContent = '🔍 Scanning ' + domain + ' for DPA compliance indicators…';
  inline.textContent = '🔍 Scanning ' + domain + '…';

  fetch('dpa.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'ajax_scan_website=1&domain=' + encodeURIComponent(domain)
  })
  .then(r => r.json())
  .then(data => {
    scanData = data;
    document.getElementById('website_scan_data').value = JSON.stringify(data);
    scanDone = true;
    renderScanResults(data);
  })
  .catch(err => {
    banner.className = 'scan-banner show error';
    spin.style.display = 'none';
    msg.textContent = '❌ Scan failed: ' + err.message + ' – you may continue without scan data';
    inline.textContent = '⚠️ Scan failed';
    setTimeout(() => { banner.classList.remove('show'); }, 5000);
  });
}

function renderScanResults(data) {
  const banner   = document.getElementById('scanBanner');
  const spinner  = document.getElementById('scanSpinner');
  const results  = document.getElementById('scanResults');
  const chips    = document.getElementById('scanChips');
  const findings = document.getElementById('scanFindings');
  const inline   = document.getElementById('scanStatusInline');

  spinner.style.display = 'none';

  if (!data.reachable && !data.https) {
    banner.className = 'scan-banner show error';
    document.getElementById('scanMsg').textContent = '⚠️ ' + data.domain + ' unreachable – findings will show website as not verified';
    inline.textContent = '⚠️ Unreachable';
    setTimeout(() => banner.classList.remove('show'), 6000);
    return;
  }

  // Build summary
  const wr = data.web_risk_percent || 0;
  const wrLabel = wr <= 20 ? '✅ Good' : (wr <= 50 ? '⚠️ Needs Work' : '🔴 Critical');
  banner.className = 'scan-banner show done';
  document.getElementById('scanMsg').textContent = '✅ Scan complete for ' + data.domain + ' – Risk: ' + wr + '% (' + wrLabel + ')  |  ' + (data.findings ? data.findings.length : 0) + ' finding(s)';
  inline.textContent = '✅ Scan done – Risk: ' + wr + '%';
  setTimeout(() => banner.classList.remove('show'), 8000);

  // Chips
  chips.innerHTML = '';
  const chipData = [
    { label: 'HTTPS', pass: data.https },
    { label: 'SSL Valid', pass: data.ssl_valid },
    { label: 'Privacy Policy', pass: data.privacy?.privacy_policy },
    { label: 'Cookie Consent', pass: data.privacy?.cookie_consent },
    { label: 'Security Headers', pass: Object.values(data.sec_headers||{}).filter(h=>h.present).length >= 4 },
    { label: 'No Tracking Cookies', pass: !data.tracking_cookies?.length },
  ];
  chipData.forEach(c => {
    const d = document.createElement('div');
    d.className = 'scan-chip ' + (c.pass ? 'chip-pass' : 'chip-fail');
    d.textContent = (c.pass ? '✅ ' : '❌ ') + c.label;
    chips.appendChild(d);
  });

  // Findings
  findings.innerHTML = '';
  if (data.findings && data.findings.length) {
    const fTitle = document.createElement('p');
    fTitle.style.cssText = 'font-size:11px;color:#a1a1aa;margin:8px 0 4px';
    fTitle.textContent = '⚠️ Compliance Issues Found:';
    findings.appendChild(fTitle);
    data.findings.forEach(f => {
      const txt = typeof f === 'object' ? f.text : f;
      const lvl = typeof f === 'object' ? (f.level || 'medium') : 'medium';
      const el  = document.createElement('div');
      el.className = 'scan-finding-item sf-' + lvl;
      el.textContent = txt;
      findings.appendChild(el);
    });
  }
  if (data.positives && data.positives.length) {
    const pTitle = document.createElement('p');
    pTitle.style.cssText = 'font-size:11px;color:#a1a1aa;margin:8px 0 4px';
    pTitle.textContent = '✅ Compliance Positives:';
    findings.appendChild(pTitle);
    data.positives.slice(0,4).forEach(pos => {
      const el = document.createElement('div');
      el.className = 'scan-finding-item sf-positive';
      el.textContent = pos;
      findings.appendChild(el);
    });
  }
  results.classList.add('show');
}

function beforeSubmit() {
  if (!scanDone && domainInput && domainInput.value.trim().length > 3) {
    return confirm('Website scan is still in progress or not complete. Submit without full website scan data?');
  }
  return true;
}

function downloadReport() {
  const content = document.getElementById('reportPreview').innerHTML;
  const w = window.open('', '_blank', 'width=960,height=750');
  if (!w) { alert('Please allow pop-ups to download the report.'); return; }
  w.document.write('<!DOCTYPE html><html><head><meta charset="UTF-8"><title>DPA Report – <?= addslashes($reportRef ?? '') ?></title></head><body>' + content + '</body></html>');
  w.document.close();
  setTimeout(() => w.print(), 600);
}
</script>
</body>
</html>