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

// ============================================================
// LANGUAGE HANDLING
// ============================================================
$lang = isset($_SESSION['dpa_lang']) ? $_SESSION['dpa_lang'] : 'en';
$allowedLangs = ['en', 'sw'];
if (isset($_GET['lang']) && in_array($_GET['lang'], $allowedLangs)) {
    $lang = $_GET['lang'];
    $_SESSION['dpa_lang'] = $lang;
}

// Full bilingual translation system
function __($key) {
    global $lang, $translations;
    if (isset($translations[$lang][$key])) {
        return $translations[$lang][$key];
    }
    return $translations['en'][$key] ?? $key;
}

$translations = [];
$translations['en'] = [
    // Navigation & UI
    'page_title' => 'DPA Kenya Compliance Assessment',
    'nav_dashboard' => 'Dashboard',
    'nav_assessments' => 'Assessments',
    'nav_help' => 'Help',
    'nav_logout' => 'Logout',
    'org_details' => 'Organisation Details',
    'company_name_label' => 'Company / Organisation Name *',
    'company_name_placeholder' => 'e.g., Acme Kenya Ltd',
    'company_website_label' => 'Website (enables live DPA scan)',
    'company_website_placeholder' => 'www.example.co.ke',
    'website_hint' => 'Enter domain without http:// — we scan for DPA compliance as you answer',
    'company_industry_label' => 'Industry / Sector *',
    'company_size_label' => 'Organisation Size *',
    'select_industry' => '— Select Industry —',
    'select_size' => '— Select Size —',
    'progress_questions_answered' => 'questions answered',
    'scanning' => 'Scanning',
    'scan_done' => 'Scan done',
    'scan_failed' => 'Scan failed',
    'unreachable' => 'Unreachable',
    'for_dpa_indicators' => 'for DPA compliance indicators…',
    'generate_report_btn' => 'GENERATE COMPREHENSIVE DPA COMPLIANCE REPORT',
    'live_scan_results' => 'Live Website Scan Results',
    'assessment_complete' => 'Assessment Complete',
    'risk_score' => 'Risk Score',
    'compliance' => 'Compliance',
    'report_ref' => 'Report Ref',
    'print_save_pdf' => 'Print / Save PDF',
    'download_report' => 'Download Report',
    'new_assessment' => 'New Assessment',
    'questions_count' => 'questions',
    'critical_badge' => 'CRITICAL',
    'question_yes' => '✅ Yes',
    'question_partially' => '⚠️ Partially',
    'question_no' => '❌ No',
    'question_dont_know' => '❓ I Don\'t Know',
    'submit_warning' => 'Website scan is still in progress. Submit without scan data?',
    'compliance_issues' => 'Compliance Issues Found:',
    'compliance_positives_label' => 'Compliance Positives:',
    
    // Report - Cover
    'report_title_main' => 'DATA PROTECTION ACT',
    'report_subtitle' => 'Compliance Assessment Report – Kenya DPA No. 24 of 2019',
    'risk_score_label' => 'Risk Score',
    'compliance_level' => 'Compliance Level',
    'report_ref_label' => 'Report Reference',
    'assessment_date_label' => 'Assessment Date',
    'legal_framework_label' => 'Legal Framework',
    'regulator_label' => 'Regulator',
    'assessed_by_label' => 'Assessed By',
    'kenya_dpa_full' => 'Kenya Data Protection Act, No. 24 of 2019',
    'odpc_full' => 'Office of the Data Protection Commissioner (ODPC), Kenya',
    
    // Report - Executive Summary
    'executive_summary' => 'EXECUTIVE SUMMARY',
    'overall_risk_rating' => 'Overall Risk Rating',
    'indicators_assessed' => 'indicators assessed across',
    'compliance_categories' => 'compliance categories',
    'key_findings_leadership' => 'Key Findings for Leadership',
    'all_indicators_compliant' => 'All assessed indicators returned compliant responses. The organisation demonstrates strong DPA compliance posture with',
    'compliance_level_text' => 'compliance level.',
    'critical_gaps_found' => 'The following are the most critical compliance gaps requiring immediate attention:',
    'bottom_line' => 'Bottom Line',
    'solid_foundation_msg' => 'The organisation has a solid compliance foundation with minor areas for improvement. Continue monitoring and maintaining current controls.',
    'gaps_exist_msg' => 'Several compliance gaps exist that require structured remediation. Prioritize immediate and short-term recommendations to reduce regulatory exposure.',
    'significant_deficiencies_msg' => 'Significant compliance deficiencies exist that expose the organisation to substantial regulatory risk. Immediate executive attention and resource allocation are required.',
    'assessment_conducted_for' => 'This Data Protection Compliance Assessment was conducted for',
    'operating_in_sector' => 'operating in the',
    'with_employees' => 'sector with',
    'employees_text' => 'employees.',
    'the_assessment_evaluated' => 'The assessment evaluated',
    'compliance_indicators_text' => 'compliance indicators',
    'against_the' => 'against the',
    'and_regulations' => 'and the Data Protection (General) Regulations, 2021.',
    'organisation_received_score' => 'The organisation received a risk score of',
    'indicating_a' => 'indicating a',
    'posture_with' => 'posture with a',
    'overall_compliance_level' => 'overall compliance level.',
    'website_scan_incorporated' => 'Website scanning was performed and findings incorporated into this assessment.',
    
    // Summary cards
    'compliant_status' => 'Compliant',
    'partial_status' => 'Partial',
    'non_compliant_status' => 'Non-Compliant',
    'unknown_status' => 'Unknown',
    'detail_label' => 'Detail',
    'information_label' => 'Information',
    'organisation_label' => 'Organisation',
    'website_label' => 'Website',
    'industry_label' => 'Industry',
    'org_size_label' => 'Organisation Size',
    'framework_full' => 'Kenya Data Protection Act No. 24 of 2019 & DPA (General) Regulations, 2021',
    
    // Category breakdown
    'compliance_by_category_title' => 'COMPLIANCE BY CATEGORY',
    'compliance_by_category_desc' => 'The following table shows compliance performance across each assessment category.',
    'category_col' => 'Category',
    'questions_col' => 'Questions',
    'failed_col' => 'Failed',
    'compliance_bar_col' => 'Compliance Bar',
    'risk_percent_col' => 'Risk %',
    'status_col' => 'Status',
    'status_compliant' => 'Compliant',
    'status_partial' => 'Partial',
    'status_non_compliant' => 'Non-Compliant',
    'status_very_high' => 'Very High Risk',
    'status_critical' => 'Critical',
    'categories_attention' => 'Categories Requiring Immediate Attention',
    'categories_gaps_msg' => 'The following compliance categories have significant gaps (≥40% non-compliant responses):',
    'prioritize_remediation' => 'These areas represent the highest regulatory risk and should be prioritized for remediation.',
    'overall_compliance_indicator' => 'Overall Compliance Indicator',
    'overall_compliance_dpa' => 'overall compliance with Kenya DPA 2019',
    
    // Detailed findings
    'detailed_findings_title' => 'DETAILED FINDINGS & RESPONSES',
    'detailed_findings_desc' => 'The table below captures every assessment question, response, compliance status, risk rating, and applicable DPA section reference.',
    'assessment_question_col' => 'Assessment Question',
    'response_col' => 'Response',
    'risk_col' => 'Risk',
    'compliance_guidance_col' => 'Compliance Guidance',
    'dpa_reference_col' => 'DPA Reference',
    'risk_low' => 'Low (0/3)',
    'risk_medium' => 'Medium (1/3)',
    'risk_high' => 'High (2/3)',
    'risk_critical' => 'Critical (3/3)',
    
    // Website scan
    'website_compliance_scan_title' => 'WEBSITE COMPLIANCE SCAN',
    'website_scan_desc' => 'An automated security and privacy compliance scan was performed on',
    'on_date_at' => 'on',
    'scan_evaluates_text' => 'The scan evaluates technical compliance indicators required under the Kenya DPA 2019.',
    'website_unreachable_msg' => 'could not be reached at scan time. Online compliance indicators could not be verified. Manual verification required.',
    'website_dpa_risk' => 'Website DPA Risk Score',
    'good_label' => 'Good',
    'needs_work_label' => 'Needs Improvement',
    'critical_label_web' => 'Critical Issues Found',
    'quick_compliance_checks' => 'Quick Compliance Checks',
    'check_col' => 'Check',
    'status_col_scan' => 'Status',
    'importance_col' => 'Importance',
    'dpa_section_col' => 'DPA Section',
    'https_tls_check' => 'HTTPS / TLS Encryption',
    'ssl_cert_check' => 'Valid SSL Certificate',
    'privacy_policy_check' => 'Privacy Policy',
    'cookie_consent_check' => 'Cookie Consent Mechanism',
    'tracking_cookies_check' => 'Tracking Cookies Present',
    'data_collection_forms_check' => 'Data Collection Forms',
    'kenya_dpa_ref_check' => 'Kenya DPA / ODPC Reference',
    'active_status' => 'Active',
    'not_found_status' => 'Not Found',
    'valid_status' => 'Valid',
    'invalid_expired_status' => 'Invalid/Expired',
    'detected_status' => 'Detected',
    'implemented_status' => 'Implemented',
    'not_detected_status' => 'Not Detected',
    'found_status' => 'Found',
    'none_detected_status' => 'None Detected',
    'form_s_count' => 'Form(s)',
    'none_status' => 'None',
    'critical_encrypt_text' => 'Critical – all personal data must be encrypted in transit',
    'critical_ssl_text' => 'Critical – invalid certificate exposes users to MITM attacks',
    'mandatory_display_text' => 'Mandatory – must be prominently displayed',
    'required_non_essential_text' => 'Required for any non-essential or tracking cookies',
    'require_explicit_optin_text' => 'Require explicit opt-in consent if present',
    'point_of_collection_text' => 'Each form must have point-of-collection privacy notice',
    'demonstrates_local_text' => 'Demonstrates local compliance awareness',
    'http_security_headers_title' => 'HTTP Security Headers Analysis',
    'header_col' => 'Header',
    'purpose_col' => 'Purpose',
    'dpa_link_col' => 'DPA Link',
    'present_status' => 'Present',
    'missing_status' => 'Missing',
    'issues_requiring_action_title' => 'Website Compliance Issues Requiring Action',
    'compliance_positives_title' => 'Website Compliance Positives',
    'ssl_issuer_label' => 'SSL Certificate Issuer',
    'expiry_label' => 'Expiry',
    
    // Recommendations
    'prioritised_recommendations_title' => 'PRIORITISED RECOMMENDATIONS',
    'action_plan_desc' => 'The following action plan is based on assessment findings, prioritised by urgency and regulatory impact.',
    'failure_warning_prefix' => 'Failure to act exposes',
    'penalties_up_to_text' => 'to penalties up to KES 5,000,000 under the Kenya DPA 2019.',
    'immediate_section' => 'IMMEDIATE – Within 30 Days',
    'short_term_section' => 'SHORT-TERM – 30 to 90 Days',
    'medium_term_section' => 'MEDIUM-TERM – 3 to 6 Months',
    'long_term_section' => 'LONG-TERM – 6 to 12 Months',
    'badge_immediate' => 'IMMEDIATE',
    'badge_short_term' => 'SHORT-TERM',
    'badge_medium_term' => 'MEDIUM-TERM',
    'badge_long_term' => 'LONG-TERM',
    'legal_basis_label' => 'Legal Basis',
    'target_timeframe_label' => 'Target Timeframe',
    'penalty_exposure_label' => 'Penalty Exposure',
    'no_recommendations_title' => 'No Recommendations Required',
    'all_compliant_recs_msg' => 'All indicators returned compliant responses. Strong DPA compliance posture. Continue monitoring and annual reassessment.',
    
    // Legal penalties
    'legal_penalties_title' => 'LEGAL PENALTIES – KENYA DATA PROTECTION ACT 2019',
    'legal_penalties_desc' => 'Non-compliance with the Kenya DPA 2019 carries significant financial and criminal penalties:',
    'offence_col' => 'Offence',
    'penalty_col' => 'Penalty',
    'section_col' => 'Section',
    'type_col' => 'Type',
    'general_violations_row' => 'General DPA violations (data protection principles)',
    'general_penalty_text' => 'KES 5,000,000 or 1% annual turnover',
    'type_civil_admin' => 'Civil / Administrative',
    'unlawful_processing_row' => 'Unlawful processing of personal data',
    'unlawful_penalty_text' => 'KES 3,000,000 fine + up to 10 years imprisonment',
    'type_criminal' => 'Criminal',
    'failure_register_row' => 'Failure to register as Data Controller/Processor with ODPC',
    'register_penalty_text' => 'KES 1,000,000 mandatory fine',
    'type_administrative' => 'Administrative',
    'failure_notify_row' => 'Failure to notify ODPC of data breach within 72 hours',
    'notify_penalty_text' => 'KES 5,000,000 fine',
    'obstruction_row' => 'Obstruction of ODPC investigation',
    'obstruction_penalty_text' => 'KES 2,000,000 fine + up to 5 years imprisonment',
    'unlawful_transfer_row' => 'Unlawful cross-border data transfer',
    'transfer_penalty_text' => 'KES 5,000,000 per unlawful transfer',
    'civil_compensation_row' => 'Civil compensation to data subjects for damages',
    'compensation_penalty_text' => 'Court-awarded damages (unlimited)',
    'type_civil' => 'Civil',
    'important_legal_notice' => 'Important Legal Notice for',
    'based_on_assessment_text' => 'Based on this assessment',
    'could_face_action_text' => 'could face regulatory action and penalties up to',
    'for_identified_areas_text' => 'for identified non-compliance areas.',
    'immediate_remediation_advised' => 'Immediate remediation of all IMMEDIATE priority items is strongly advised.',
    'present_to_board_text' => 'This report should be presented to senior management and the Board of Directors.',
    
    // Industry-specific
    'industry_specific_notes_title' => 'INDUSTRY-SPECIFIC COMPLIANCE NOTES',
    
    // Glossary
    'glossary_title' => 'DEFINITIONS & GLOSSARY OF TERMS',
    'glossary_dpa_term' => 'Data Protection Act (DPA) 2019',
    'glossary_dpa_def' => 'Kenya\'s primary data protection legislation (Act No. 24 of 2019), providing comprehensive framework for processing personal data, rights of data subjects, and obligations of data controllers and processors.',
    'glossary_odpc_term' => 'Office of the Data Protection Commissioner (ODPC)',
    'glossary_odpc_def' => 'The regulatory authority established under the DPA responsible for oversight, enforcement, registration of data controllers/processors, and handling complaints in Kenya.',
    'glossary_personal_data_term' => 'Personal Data',
    'glossary_personal_data_def' => 'Any information relating to an identified or identifiable natural person, including name, ID number, location data, online identifiers, or factors specific to physical, physiological, genetic, mental, economic, cultural, or social identity.',
    'glossary_data_subject_term' => 'Data Subject',
    'glossary_data_subject_def' => 'An identified or identifiable natural person who is the subject of personal data. Data subjects have rights including access, rectification, erasure, restriction, portability, and objection.',
    'glossary_controller_term' => 'Data Controller',
    'glossary_controller_def' => 'A natural or legal person, public authority, agency, or other body which determines the purpose and means of processing personal data.',
    'glossary_processor_term' => 'Data Processor',
    'glossary_processor_def' => 'A natural or legal person, public authority, agency, or other body which processes personal data on behalf of the data controller.',
    'glossary_dpa_contract_term' => 'Data Processing Agreement (DPA)',
    'glossary_dpa_contract_def' => 'A legally binding contract between a data controller and data processor setting out the subject matter, duration, nature, purpose of processing, types of personal data, and obligations.',
    'glossary_dpia_term' => 'Data Protection Impact Assessment (DPIA)',
    'glossary_dpia_def' => 'A process to identify and minimize data protection risks of a project. Required under Section 41(5) for processing likely to result in high risk to individuals\' rights and freedoms.',
    'glossary_ropa_term' => 'Record of Processing Activities (RoPA)',
    'glossary_ropa_def' => 'A documented inventory of all personal data processing activities, including purposes, legal basis, categories, recipients, retention periods, and security measures (DPA Section 25).',
    'glossary_dpo_term' => 'Data Protection Officer (DPO)',
    'glossary_dpo_def' => 'An individual appointed by a data controller or processor responsible for overseeing data protection strategy and ensuring DPA compliance.',
    'glossary_sensitive_term' => 'Sensitive Personal Data / Special Categories',
    'glossary_sensitive_def' => 'Data revealing racial/ethnic origin, political opinions, religious/philosophical beliefs, trade union membership, genetic/biometric data, health data, or sex life/orientation. Enhanced protection under Section 31.',
    'glossary_consent_term' => 'Consent',
    'glossary_consent_def' => 'Any freely given, specific, informed, and unambiguous indication of the data subject\'s wishes by which they signify agreement to processing of their personal data.',
    'glossary_cross_border_term' => 'Cross-Border Data Transfer',
    'glossary_cross_border_def' => 'Transfer of personal data from Kenya to another country or international organization. Regulated under Sections 48-49 requiring adequate safeguards or ODPC authorization.',
    'glossary_breach_term' => 'Data Breach',
    'glossary_breach_def' => 'A breach of security leading to accidental or unlawful destruction, loss, alteration, unauthorized disclosure of, or access to, personal data. Must be reported to ODPC within 72 hours (Section 43).',
    'glossary_sccs_term' => 'Standard Contractual Clauses (SCCs)',
    'glossary_sccs_def' => 'Pre-approved contractual terms issued by a data protection authority providing adequate safeguards for cross-border data transfers to countries without an adequacy decision.',
    
    // Signatures
    'signatures_title' => 'SIGNATURES & REPORT VERIFICATION',
    'organisation_representative' => 'Organisation Representative',
    'dpo_or_ceo' => 'Data Protection Officer / Chief Executive',
    'signature_and_stamp' => 'Signature & Official Stamp',
    'date_line' => 'Date',
    'assessment_conducted_by_title' => 'Assessment Conducted By',
    'certified_dpo_title' => 'Certified Data Protection Officer',
    'digitally_signed_on' => 'Digitally Signed',
    'report_authenticity_title' => 'Report Authenticity Verification',
    'report_registered_under' => 'This report is registered under reference',
    'verify_by_scanning' => 'Verify authenticity by scanning the QR code or visiting the URL below.',
    'scan_to_verify_text' => 'Scan to verify: Report Reference, Assessor Credentials, Risk Score, Compliance Level, and Assessment Date',
    'generated_on' => 'Generated',
    'framework_short' => 'Kenya DPA No. 24 of 2019',
    'odpc_kenya_short' => 'ODPC Kenya',
    'disclaimer_text' => 'This assessment is based on information provided and automated technical scans conducted on',
    'disclaimer_text_2' => 'Results reflect compliance state at time of assessment. This does not constitute legal advice. Consult qualified legal counsel for formal legal opinion.',
];

// Swahili translations
$translations['sw'] = [
    'page_title' => 'Tathmini ya Uzingatiaji wa DPA Kenya',
    'nav_dashboard' => 'Dashibodi',
    'nav_assessments' => 'Tathmini',
    'nav_help' => 'Msaada',
    'nav_logout' => 'Ondoka',
    'org_details' => 'Maelezo ya Shirika',
    'company_name_label' => 'Jina la Kampuni / Shirika *',
    'company_name_placeholder' => 'mfano, Acme Kenya Ltd',
    'company_website_label' => 'Tovuti (inawasha uchunguzi wa DPA)',
    'company_website_placeholder' => 'www.mfano.co.ke',
    'website_hint' => 'Ingiza anwani bila http:// — tunachunguza uzingatiaji wa DPA unapojibu',
    'company_industry_label' => 'Sekta *',
    'company_size_label' => 'Ukubwa wa Shirika *',
    'select_industry' => '— Chagua Sekta —',
    'select_size' => '— Chagua Ukubwa —',
    'progress_questions_answered' => 'maswali yamejibiwa',
    'scanning' => 'Inachunguza',
    'scan_done' => 'Uchunguzi umekamilika',
    'scan_failed' => 'Uchunguzi umeshindwa',
    'unreachable' => 'Haipatikani',
    'for_dpa_indicators' => 'kwa viashiria vya uzingatiaji wa DPA…',
    'generate_report_btn' => 'ZALISHA RIPOTI KAMILI YA UZINGATIAJI WA DPA',
    'live_scan_results' => 'Matokeo ya Uchunguzi wa Tovuti',
    'assessment_complete' => 'Tathmini Imekamilika',
    'risk_score' => 'Alama ya Hatari',
    'compliance' => 'Uzingatiaji',
    'report_ref' => 'Nambari ya Ripoti',
    'print_save_pdf' => 'Chapisha / Hifadhi PDF',
    'download_report' => 'Pakua Ripoti',
    'new_assessment' => 'Tathmini Mpya',
    'questions_count' => 'maswali',
    'critical_badge' => 'MUHIMU',
    'question_yes' => '✅ Ndiyo',
    'question_partially' => '⚠️ Kiasi',
    'question_no' => '❌ Hapana',
    'question_dont_know' => '❓ Sijui',
    'submit_warning' => 'Uchunguzi wa tovuti bado unaendelea. Tuma bila data ya uchunguzi?',
    'compliance_issues' => 'Masuala ya Uzingatiaji Yaliyopatikana:',
    'compliance_positives_label' => 'Mambo Chanya ya Uzingatiaji:',
    
    'report_title_main' => 'SHERIA YA ULINZI WA DATA',
    'report_subtitle' => 'Ripoti ya Tathmini ya Uzingatiaji – DPA Kenya Na. 24 ya 2019',
    'risk_score_label' => 'Alama ya Hatari',
    'compliance_level' => 'Kiwango cha Uzingatiaji',
    'report_ref_label' => 'Nambari ya Ripoti',
    'assessment_date_label' => 'Tarehe ya Tathmini',
    'legal_framework_label' => 'Mfumo wa Kisheria',
    'regulator_label' => 'Mdhibiti',
    'assessed_by_label' => 'Imefanywa na',
    'kenya_dpa_full' => 'Sheria ya Ulinzi wa Data ya Kenya, Na. 24 ya 2019',
    'odpc_full' => 'Ofisi ya Kamishna wa Ulinzi wa Data (ODPC), Kenya',
    
    'executive_summary' => 'MUHTASARI WA UTENDAJI',
    'overall_risk_rating' => 'Ukadiriaji wa Hatari kwa Jumla',
    'indicators_assessed' => 'viashiria vimetathminiwa katika',
    'compliance_categories' => 'makundi ya uzingatiaji',
    'key_findings_leadership' => 'Matokeo Muhimu kwa Uongozi',
    'all_indicators_compliant' => 'Viashiria vyote vilivyotathminiwa vilirejesha majibu ya kuzingatia. Shirika linaonyesha msimamo imara wa uzingatiaji wa DPA na',
    'compliance_level_text' => 'kiwango cha uzingatiaji.',
    'critical_gaps_found' => 'Ifuatayo ni mapungufu muhimu zaidi ya uzingatiaji yanayohitaji uangalizi wa haraka:',
    'bottom_line' => 'Hitimisho',
    'solid_foundation_msg' => 'Shirika lina msingi imara wa uzingatiaji na maeneo madogo ya kuboresha. Endelea kufuatilia na kudumisha udhibiti wa sasa.',
    'gaps_exist_msg' => 'Kuna mapungufu kadhaa ya uzingatiaji yanayohitaji urekebishaji uliopangwa. Weka kipaumbele mapendekezo ya haraka na ya muda mfupi.',
    'significant_deficiencies_msg' => 'Kuna upungufu mkubwa wa uzingatiaji unaofichua shirika kwenye hatari kubwa ya kisheria. Uangalizi wa haraka wa mtendaji unahitajika.',
    'assessment_conducted_for' => 'Tathmini hii ya Uzingatiaji wa Ulinzi wa Data ilifanywa kwa',
    'operating_in_sector' => 'inayofanya kazi katika sekta ya',
    'with_employees' => 'na',
    'employees_text' => 'wafanyakazi.',
    'the_assessment_evaluated' => 'Tathmini ilitathmini',
    'compliance_indicators_text' => 'viashiria vya uzingatiaji',
    'against_the' => 'dhidi ya',
    'and_regulations' => 'na Kanuni za Ulinzi wa Data (Jumla), 2021.',
    'organisation_received_score' => 'Shirika lilipata alama ya hatari ya',
    'indicating_a' => 'ikionyesha',
    'posture_with' => 'msimamo na',
    'overall_compliance_level' => 'kiwango cha jumla cha uzingatiaji.',
    'website_scan_incorporated' => 'Uchunguzi wa tovuti ulifanyika na matokeo yamejumuishwa katika tathmini hii.',
    
    'compliant_status' => 'Inazingatia',
    'partial_status' => 'Kiasi',
    'non_compliant_status' => 'Haizingatii',
    'unknown_status' => 'Haijulikani',
    'detail_label' => 'Maelezo',
    'information_label' => 'Taarifa',
    'organisation_label' => 'Shirika',
    'website_label' => 'Tovuti',
    'industry_label' => 'Sekta',
    'org_size_label' => 'Ukubwa wa Shirika',
    'framework_full' => 'Sheria ya Ulinzi wa Data ya Kenya Na. 24 ya 2019 na Kanuni za DPA (Jumla), 2021',
    
    'compliance_by_category_title' => 'UZINGATIAJI KWA KUNDI',
    'compliance_by_category_desc' => 'Jedwali lifuatalo linaonyesha utendaji wa uzingatiaji katika kila kundi la tathmini.',
    'category_col' => 'Kundi',
    'questions_col' => 'Maswali',
    'failed_col' => 'Imeshindwa',
    'compliance_bar_col' => 'Kipimo cha Uzingatiaji',
    'risk_percent_col' => 'Hatari %',
    'status_col' => 'Hali',
    'status_compliant' => 'Inazingatia',
    'status_partial' => 'Kiasi',
    'status_non_compliant' => 'Haizingatii',
    'status_very_high' => 'Hatari Kubwa Sana',
    'status_critical' => 'Muhimu',
    'categories_attention' => 'Makundi Yanayohitaji Uangalizi wa Haraka',
    'categories_gaps_msg' => 'Makundi yafuatayo yana mapungufu makubwa (≥40% ya majibu yasiyozingatia):',
    'prioritize_remediation' => 'Maeneo haya yanawakilisha hatari kubwa zaidi ya kisheria na yanapaswa kupewa kipaumbele kwa urekebishaji.',
    'overall_compliance_indicator' => 'Kiashiria cha Jumla cha Uzingatiaji',
    'overall_compliance_dpa' => 'uzingatiaji wa jumla na DPA Kenya 2019',
    
    'detailed_findings_title' => 'MATOKEO YA KINA NA MAJIBU',
    'detailed_findings_desc' => 'Jedwali hapa chini linanasa kila swali la tathmini, jibu, hali ya uzingatiaji, ukadiriaji wa hatari, na rejea ya kifungu cha DPA.',
    'assessment_question_col' => 'Swali la Tathmini',
    'response_col' => 'Jibu',
    'risk_col' => 'Hatari',
    'compliance_guidance_col' => 'Maelekezo ya Uzingatiaji',
    'dpa_reference_col' => 'Rejea ya DPA',
    'risk_low' => 'Chini (0/3)',
    'risk_medium' => 'Wastani (1/3)',
    'risk_high' => 'Juu (2/3)',
    'risk_critical' => 'Muhimu (3/3)',
    
    'website_compliance_scan_title' => 'UCHUNGUZI WA UZINGATIAJI WA TOVUTI',
    'website_scan_desc' => 'Uchunguzi wa kiotomatiki wa usalama na faragha ulifanywa kwenye',
    'on_date_at' => 'tarehe',
    'scan_evaluates_text' => 'Uchunguzi unatathmini viashiria vya uzingatiaji wa kiufundi vinavyotakiwa chini ya DPA Kenya 2019.',
    'website_unreachable_msg' => 'haikuweza kufikiwa wakati wa uchunguzi. Viashiria vya uzingatiaji mtandaoni havikuweza kuthibitishwa. Uthibitishaji wa mwongozo unahitajika.',
    'website_dpa_risk' => 'Alama ya Hatari ya DPA ya Tovuti',
    'good_label' => 'Nzuri',
    'needs_work_label' => 'Inahitaji Uboreshaji',
    'critical_label_web' => 'Masuala Muhimu Yaliyopatikana',
    'quick_compliance_checks' => 'Ukaguzi wa Haraka wa Uzingatiaji',
    'check_col' => 'Angalio',
    'status_col_scan' => 'Hali',
    'importance_col' => 'Umuhimu',
    'dpa_section_col' => 'Kifungu cha DPA',
    'https_tls_check' => 'Usimbaji wa HTTPS / TLS',
    'ssl_cert_check' => 'Cheti Halali cha SSL',
    'privacy_policy_check' => 'Sera ya Faragha',
    'cookie_consent_check' => 'Utaratibu wa Ridhaa ya Vidakuzi',
    'tracking_cookies_check' => 'Vidakuzi vya Ufuatiliaji Vipo',
    'data_collection_forms_check' => 'Fomu za Kukusanya Data',
    'kenya_dpa_ref_check' => 'Rejea ya DPA Kenya / ODPC',
    'active_status' => 'Inafanya kazi',
    'not_found_status' => 'Haijapatikana',
    'valid_status' => 'Sahihi',
    'invalid_expired_status' => 'Si sahihi/Imeisha',
    'detected_status' => 'Imegunduliwa',
    'implemented_status' => 'Imetekelezwa',
    'not_detected_status' => 'Haijagunduliwa',
    'found_status' => 'Imepatikana',
    'none_detected_status' => 'Hakuna Kilichogunduliwa',
    'form_s_count' => 'Fomu',
    'none_status' => 'Hakuna',
    'critical_encrypt_text' => 'Muhimu – data zote binafsi lazima zisimbwe wakati wa kusafirisha',
    'critical_ssl_text' => 'Muhimu – cheti batili kinafichua watumiaji kwenye mashambulizi ya MITM',
    'mandatory_display_text' => 'Lazima – lazima ionyeshwe kwa uwazi',
    'required_non_essential_text' => 'Inahitajika kwa vidakuzi vyovyote visivyo vya muhimu au vya ufuatiliaji',
    'require_explicit_optin_text' => 'Inahitaji ridhaa ya wazi ya kuchagua kuingia ikiwa ipo',
    'point_of_collection_text' => 'Kila fomu lazima iwe na ilani ya faragha wakati wa ukusanyaji',
    'demonstrates_local_text' => 'Inaonyesha uelewa wa uzingatiaji wa ndani',
    'http_security_headers_title' => 'Uchambuzi wa Vichwa vya Usalama vya HTTP',
    'header_col' => 'Kichwa',
    'purpose_col' => 'Madhumuni',
    'dpa_link_col' => 'Kiungo cha DPA',
    'present_status' => 'Ipo',
    'missing_status' => 'Haipo',
    'issues_requiring_action_title' => 'Masuala ya Uzingatiaji wa Tovuti Yanayohitaji Hatua',
    'compliance_positives_title' => 'Mambo Chanya ya Uzingatiaji wa Tovuti',
    'ssl_issuer_label' => 'Mtoaji wa Cheti cha SSL',
    'expiry_label' => 'Mwisho',
    
    'prioritised_recommendations_title' => 'MAPENDEKEZO YALIYOPEWA KIPAUMBELE',
    'action_plan_desc' => 'Mpango wa utekelezaji ufuatao unategemea matokeo ya tathmini, ukipewa kipaumbele kwa uharaka na athari za kisheria.',
    'failure_warning_prefix' => 'Kushindwa kutekeleza kunafichua',
    'penalties_up_to_text' => 'kwa adhabu hadi KES 5,000,000 chini ya DPA Kenya 2019.',
    'immediate_section' => 'MARA MOJA – Ndani ya Siku 30',
    'short_term_section' => 'MUDA MFUPI – Siku 30 hadi 90',
    'medium_term_section' => 'MUDA WA KATI – Miezi 3 hadi 6',
    'long_term_section' => 'MUDA MREFU – Miezi 6 hadi 12',
    'badge_immediate' => 'MARA MOJA',
    'badge_short_term' => 'MUDA MFUPI',
    'badge_medium_term' => 'MUDA WA KATI',
    'badge_long_term' => 'MUDA MREFU',
    'legal_basis_label' => 'Msingi wa Kisheria',
    'target_timeframe_label' => 'Muda Unaolengwa',
    'penalty_exposure_label' => 'Adhabu Inayowezekana',
    'no_recommendations_title' => 'Hakuna Mapendekezo Yanayohitajika',
    'all_compliant_recs_msg' => 'Viashiria vyote vilirejesha majibu ya kuzingatia. Msimamo imara wa DPA. Endelea na ufuatiliaji na tathmini ya kila mwaka.',
    
    'legal_penalties_title' => 'ADHABU ZA KISHERIA – SHERIA YA ULINZI WA DATA YA KENYA 2019',
    'legal_penalties_desc' => 'Kutozingatia DPA Kenya 2019 kuna adhabu kubwa za kifedha na jinai:',
    'offence_col' => 'Kosa',
    'penalty_col' => 'Adhabu',
    'section_col' => 'Kifungu',
    'type_col' => 'Aina',
    'general_violations_row' => 'Ukiukaji wa jumla wa DPA (kanuni za ulinzi wa data)',
    'general_penalty_text' => 'KES 5,000,000 au 1% ya mauzo ya mwaka',
    'type_civil_admin' => 'Madai / Utawala',
    'unlawful_processing_row' => 'Uchakataji haramu wa data binafsi',
    'unlawful_penalty_text' => 'Faini ya KES 3,000,000 + hadi miaka 10 gerezani',
    'type_criminal' => 'Jinai',
    'failure_register_row' => 'Kushindwa kujisajili kama Mdhibiti/Mchakataji wa Data na ODPC',
    'register_penalty_text' => 'Faini ya lazima ya KES 1,000,000',
    'type_administrative' => 'Utawala',
    'failure_notify_row' => 'Kushindwa kuarifu ODPC kuhusu uvunjaji wa data ndani ya saa 72',
    'notify_penalty_text' => 'Faini ya KES 5,000,000',
    'obstruction_row' => 'Kuzuia uchunguzi wa ODPC',
    'obstruction_penalty_text' => 'Faini ya KES 2,000,000 + hadi miaka 5 gerezani',
    'unlawful_transfer_row' => 'Uhamishaji haramu wa data nje ya mipaka',
    'transfer_penalty_text' => 'KES 5,000,000 kwa kila uhamishaji haramu',
    'civil_compensation_row' => 'Fidia ya madai kwa wamiliki wa data kwa uharibifu',
    'compensation_penalty_text' => 'Uharibifu ulioamuliwa na mahakama (bila kikomo)',
    'type_civil' => 'Madai',
    'important_legal_notice' => 'Ilani Muhimu ya Kisheria kwa',
    'based_on_assessment_text' => 'Kulingana na tathmini hii',
    'could_face_action_text' => 'inaweza kukabiliwa na hatua za kisheria na adhabu hadi',
    'for_identified_areas_text' => 'kwa maeneo yaliyotambuliwa ya kutozingatia.',
    'immediate_remediation_advised' => 'Urekebishaji wa haraka wa vipengele vyote vya MARA MOJA unapendekezwa kwa nguvu.',
    'present_to_board_text' => 'Ripoti hii inapaswa kuwasilishwa kwa usimamizi mkuu na Bodi ya Wakurugenzi.',
    
    'industry_specific_notes_title' => 'MAELEZO YA UZINGATIAJI KWA SEKTA',
    
    'glossary_title' => 'UFAFANUZI NA GLOSARI YA MANENO',
    'glossary_dpa_term' => 'Sheria ya Ulinzi wa Data (DPA) 2019',
    'glossary_dpa_def' => 'Sheria kuu ya ulinzi wa data ya Kenya (Sheria Na. 24 ya 2019), inayotoa mfumo kamili wa kuchakata data binafsi, haki za wamiliki wa data, na wajibu wa wadhibiti na wachakataji.',
    'glossary_odpc_term' => 'Ofisi ya Kamishna wa Ulinzi wa Data (ODPC)',
    'glossary_odpc_def' => 'Mamlaka ya udhibiti iliyoanzishwa chini ya DPA inayohusika na usimamizi, utekelezaji, usajili wa wadhibiti/wachakataji, na kushughulikia malalamiko nchini Kenya.',
    'glossary_personal_data_term' => 'Data Binafsi',
    'glossary_personal_data_def' => 'Taarifa yoyote inayomhusu mtu halisi aliyetambuliwa au anayeweza kutambuliwa, ikijumuisha jina, nambari ya kitambulisho, data ya eneo, vitambulisho vya mtandaoni.',
    'glossary_data_subject_term' => 'Mhusika wa Data',
    'glossary_data_subject_def' => 'Mtu halisi aliyetambuliwa au anayeweza kutambuliwa ambaye ni mhusika wa data binafsi. Ana haki za ufikiaji, marekebisho, ufutaji, uzuiaji, uhamishaji, na kupinga.',
    'glossary_controller_term' => 'Mdhibiti wa Data',
    'glossary_controller_def' => 'Mtu halisi au wa kisheria, mamlaka ya umma, wakala, au chombo kinachobainisha madhumuni na njia ya uchakataji wa data binafsi.',
    'glossary_processor_term' => 'Mchakataji wa Data',
    'glossary_processor_def' => 'Mtu halisi au wa kisheria, mamlaka ya umma, wakala, au chombo kinachochakata data binafsi kwa niaba ya mdhibiti.',
    'glossary_dpa_contract_term' => 'Mkataba wa Uchakataji wa Data (DPA)',
    'glossary_dpa_contract_def' => 'Mkataba wa kisheria kati ya mdhibiti na mchakataji unaobainisha somo, muda, asili, madhumuni ya uchakataji, aina za data, na wajibu.',
    'glossary_dpia_term' => 'Tathmini ya Athari za Ulinzi wa Data (DPIA)',
    'glossary_dpia_def' => 'Mchakato wa kutambua na kupunguza hatari za ulinzi wa data za mradi. Inahitajika chini ya Kifungu cha 41(5) kwa uchakataji wenye hatari kubwa.',
    'glossary_ropa_term' => 'Rekodi ya Shughuli za Uchakataji (RoPA)',
    'glossary_ropa_def' => 'Orodha iliyoandikwa ya shughuli zote za uchakataji wa data binafsi, ikijumuisha madhumuni, msingi wa kisheria, kategoria, wapokeaji, vipindi vya uhifadhi (Kifungu cha 25).',
    'glossary_dpo_term' => 'Afisa wa Ulinzi wa Data (DPO)',
    'glossary_dpo_def' => 'Mtu aliyeteuliwa na mdhibiti au mchakataji anayehusika na kusimamia mkakati wa ulinzi wa data na kuhakikisha uzingatiaji wa DPA.',
    'glossary_sensitive_term' => 'Data Binafsi Nyeti / Kategoria Maalum',
    'glossary_sensitive_def' => 'Data inayofichua asili ya rangi/kabila, maoni ya kisiasa, imani za kidini/kifalsafa, uanachama wa chama cha wafanyakazi, data za kijenetiki/biometriki, afya. Ulinzi ulioimarishwa chini ya Kifungu cha 31.',
    'glossary_consent_term' => 'Ridhaa',
    'glossary_consent_def' => 'Dalili yoyote iliyotolewa kwa hiari, mahususi, yenye taarifa na isiyo na utata ya matakwa ya mhusika wa data kukubali uchakataji wa data zake.',
    'glossary_cross_border_term' => 'Uhamishaji wa Data Nje ya Mipaka',
    'glossary_cross_border_def' => 'Uhamishaji wa data binafsi kutoka Kenya kwenda nchi nyingine. Unadhibitiwa chini ya Vifungu 48-49 vinavyohitaji ulinzi wa kutosha au idhini ya ODPC.',
    'glossary_breach_term' => 'Uvunjaji wa Data',
    'glossary_breach_def' => 'Uvunjaji wa usalama unaosababisha uharibifu, upotevu, mabadiliko, ufichuzi usioidhinishwa wa data binafsi. Lazima uripotiwe kwa ODPC ndani ya saa 72 (Kifungu cha 43).',
    'glossary_sccs_term' => 'Vifungu vya Kawaida vya Kimkataba (SCC)',
    'glossary_sccs_def' => 'Masharti ya kimkataba yaliyoidhinishwa awali yanayotoa ulinzi wa kutosha kwa uhamishaji wa data kwenda nchi zisizo na uamuzi wa utoshelevu.',
    
    'signatures_title' => 'SAHIHI NA UTHIBITISHAJI WA RIPOTI',
    'organisation_representative' => 'Mwakilishi wa Shirika',
    'dpo_or_ceo' => 'Afisa wa Ulinzi wa Data / Mtendaji Mkuu',
    'signature_and_stamp' => 'Sahihi na Muhuri Rasmi',
    'date_line' => 'Tarehe',
    'assessment_conducted_by_title' => 'Tathmini Imefanywa Na',
    'certified_dpo_title' => 'Afisa wa Ulinzi wa Data Aliyethibitishwa',
    'digitally_signed_on' => 'Imesainiwa Kidigitali',
    'report_authenticity_title' => 'Uthibitishaji wa Uhalisi wa Ripoti',
    'report_registered_under' => 'Ripoti hii imesajiliwa chini ya nambari',
    'verify_by_scanning' => 'Thibitisha uhalisi kwa kuchanganua msimbo wa QR au kutembelea URL hapa chini.',
    'scan_to_verify_text' => 'Changanua kuthibitisha: Nambari ya Ripoti, Sifa za Mtathmini, Alama ya Hatari, Kiwango cha Uzingatiaji, na Tarehe ya Tathmini',
    'generated_on' => 'Imezalishwa',
    'framework_short' => 'DPA Kenya Na. 24 ya 2019',
    'odpc_kenya_short' => 'ODPC Kenya',
    'disclaimer_text' => 'Tathmini hii inategemea taarifa zilizotolewa na uchunguzi wa kiufundi uliofanywa tarehe',
    'disclaimer_text_2' => 'Matokeo yanaonyesha hali ya uzingatiaji wakati wa tathmini. Hii si ushauri wa kisheria. Wasiliana na mshauri wa kisheria kwa maoni rasmi.',
];

// ============================================================
// DARK/LIGHT MODE
// ============================================================
$theme = isset($_SESSION['dpa_theme']) ? $_SESSION['dpa_theme'] : 'dark';
if (isset($_GET['theme']) && in_array($_GET['theme'], ['dark', 'light'])) {
    $theme = $_GET['theme'];
    $_SESSION['dpa_theme'] = $theme;
}

try {
    $pdo = getDBConnection();

    $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,
        failed_categories TEXT,
        non_compliant_questions TEXT,
        partial_questions TEXT,
        assessment_lang TEXT DEFAULT 'en'
    )");

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

    $pdo->exec("CREATE TABLE IF NOT EXISTS dpa_recommendations (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        risk_level TEXT,
        category TEXT,
        failed_question_ids TEXT,
        priority TEXT,
        recommendation TEXT NOT NULL,
        recommendation_sw TEXT,
        timeframe TEXT,
        legal_reference TEXT,
        penalty_risk TEXT,
        triggers_on_answer TEXT,
        triggers_on_category_fail 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
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS industry_templates (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        industry_key TEXT UNIQUE,
        industry_name TEXT,
        industry_name_sw TEXT,
        template_content TEXT,
        template_content_sw TEXT,
        specific_requirements TEXT,
        specific_requirements_sw TEXT
    )");

    $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);

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

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

// ============================================================
// DEFAULT QUESTIONS - All properly formatted with Swahili translations
// Questions that work with Yes/Partially/No/I Don't Know answers
// ============================================================
function insertDefaultQuestions($pdo) {
    $questions = [
        // 1. Data Collection & Consent
        ['Data Collection & Consent', 'Ukusanyaji wa Data na Ridhaa',
         'Has your organization identified and documented a lawful basis for every personal data processing activity?',
         'Je, shirika lako limetambua na kuandika msingi halali kwa kila shughuli ya uchakataji wa data binafsi?',
         'DPA requires at least one of: consent, contract, legal obligation, vital interests, public task, or legitimate interests. Document each basis in your RoPA.',
         'DPA inahitaji angalau moja ya: ridhaa, mkataba, wajibu wa kisheria, maslahi muhimu, kazi ya umma, au maslahi halali. Andika kila msingi katika RoPA yako.',
         3.0, 'Section 30, Kenya DPA 2019', 1, 0, 'data_consent'],

        ['Data Collection & Consent', 'Ukusanyaji wa Data na Ridhaa',
         'Do you obtain explicit, informed, and freely given consent from data subjects before processing their personal data?',
         'Je, unapata ridhaa ya wazi, yenye taarifa, na ya hiari kutoka kwa wamiliki wa data kabla ya kuchakata data zao binafsi?',
         'Consent must be specific, informed, and unambiguous. Pre-ticked boxes, silence, or inactivity do not constitute valid consent under Section 32.',
         'Ridhaa lazima iwe mahususi, yenye taarifa, na isiyo na utata. Visanduku vilivyotiwa alama mapema, ukimya, au kutofanya chochote si ridhaa halali chini ya Kifungu cha 32.',
         3.0, 'Section 32, Kenya DPA 2019', 2, 0, 'data_consent'],

        ['Data Collection & Consent', 'Ukusanyaji wa Data na Ridhaa',
         'Can data subjects withdraw consent at any time, and is the withdrawal process as easy as giving consent?',
         'Je, wamiliki wa data wanaweza kuondoa ridhaa wakati wowote, na je, mchakato wa kuondoa ni rahisi kama kutoa ridhaa?',
         'Withdrawal must not affect lawfulness of prior processing. Mechanisms for withdrawal must be easily accessible and clearly communicated.',
         'Uondoaji haupaswi kuathiri uhalali wa uchakataji wa awali. Taratibu za kuondoa lazima ziweze kufikiwa kwa urahisi na ziwasilishwe kwa uwazi.',
         2.5, 'Section 32(5), Kenya DPA 2019', 3, 0, 'data_consent'],

        ['Data Collection & Consent', 'Ukusanyaji wa Data na Ridhaa',
         'Do you have a specific process for obtaining verifiable parental or guardian consent before processing children\'s personal data (under 18)?',
         'Je, una mchakato maalum wa kupata ridhaa inayoweza kuthibitishwa ya mzazi au mlezi kabla ya kuchakata data binafsi za watoto (chini ya miaka 18)?',
         'Children under 18 require verifiable guardian consent. Age verification mechanisms must be in place. Consent records must be maintained for accountability.',
         'Watoto chini ya miaka 18 wanahitaji ridhaa ya mlezi inayoweza kuthibitishwa. Taratibu za uthibitishaji wa umri lazima ziwepo. Rekodi za ridhaa lazima zihifadhiwe.',
         3.5, 'Section 33, Kenya DPA 2019', 4, 0, 'data_consent'],

        ['Data Collection & Consent', 'Ukusanyaji wa Data na Ridhaa',
         'Is special category data (health, biometric, ethnicity, religion, etc.) only processed when strictly necessary and with enhanced safeguards?',
         'Je, data za kategoria maalum (afya, biometriki, kabila, dini, n.k.) zinachakatwa tu inapobidi kabisa na kwa ulinzi ulioimarishwa?',
         'Special category data requires explicit consent or specific legal grounds under Section 31. Enhanced security, DPIAs, and data minimisation are mandatory.',
         'Data za kategoria maalum zinahitaji ridhaa ya wazi au misingi maalum ya kisheria chini ya Kifungu cha 31. Usalama ulioimarishwa, DPIA, na upunguzaji wa data ni lazima.',
         3.5, 'Section 31, Kenya DPA 2019', 5, 0, 'data_consent'],

        // 2. Data Storage & Security
        ['Data Storage & Security', 'Uhifadhi na Usalama wa Data',
         'Are all locations where personal data is physically or digitally stored documented with appropriate security controls?',
         'Je, maeneo yote ambapo data binafsi zinahifadhiwa kimwili au kidigitali yameandikwa na udhibiti sahihi wa usalama?',
         'Document all storage locations: on-premises servers, cloud data centers, third-party facilities. Each must have physical security, access controls, and environmental protections.',
         'Andika maeneo yote ya uhifadhi: seva za ndani, vituo vya data vya wingu, vifaa vya watu wengine. Kila moja lazima iwe na usalama wa kimwili, udhibiti wa ufikiaji, na ulinzi wa mazingira.',
         3.5, 'Section 41 & 48, Kenya DPA 2019', 6, 0, 'data_storage'],

        ['Data Storage & Security', 'Uhifadhi na Usalama wa Data',
         'Is personal data encrypted at rest (storage) and in transit (network) using current industry-standard encryption?',
         'Je, data binafsi zimesimbwa zikiwa zimehifadhiwa na zinaposafirishwa kwa kutumia usimbaji wa kiwango cha kisasa cha sekta?',
         'Use AES-256 minimum for data at rest and TLS 1.2+ for data in transit. Encryption keys must be securely managed with access strictly limited to authorized personnel.',
         'Tumia AES-256 kwa kiwango cha chini kwa data iliyohifadhiwa na TLS 1.2+ kwa data inayosafiri. Vifunguo vya usimbaji lazima vidhibitiwe kwa usalama na ufikiaji uwe kwa wafanyakazi walioidhinishwa pekee.',
         3.0, 'Section 41, Kenya DPA 2019', 7, 0, 'data_storage'],

        ['Data Storage & Security', 'Uhifadhi na Usalama wa Data',
         'Do you have documented technical and organizational security policies covering all systems that process personal data?',
         'Je, una sera za usalama za kiufundi na za shirika zilizoandikwa zinazoshughulikia mifumo yote inayochakata data binafsi?',
         'Security policies must cover: encryption, access controls, network security, incident response, backup/recovery, and regular security testing. Review and update at least annually.',
         'Sera za usalama lazima zishughulikie: usimbaji, udhibiti wa ufikiaji, usalama wa mtandao, kukabiliana na matukio, hifadhi/urejeshaji, na upimaji wa usalama wa mara kwa mara. Kagua na usasishe angalau kila mwaka.',
         3.0, 'Section 41, Kenya DPA 2019', 8, 0, 'data_storage'],

        ['Data Storage & Security', 'Uhifadhi na Usalama wa Data',
         'Are access controls implemented ensuring only authorized personnel can access personal data based on the principle of least privilege?',
         'Je, udhibiti wa ufikiaji umetekelezwa kuhakikisha wafanyakazi walioidhinishwa pekee wanaweza kufikia data binafsi kwa kanuni ya haki ndogo?',
         'Implement Role-Based Access Control (RBAC), Multi-Factor Authentication (MFA), regular access reviews, and privileged access logging. Remove access promptly when staff leave.',
         'Tekeleza Udhibiti wa Ufikiaji kwa Majukumu (RBAC), Uthibitishaji wa Mambo Mengi (MFA), mapitio ya ufikiaji mara kwa mara, na kumbukumbu za ufikiaji wa haki maalum. Ondoa ufikiaji mara moja wafanyakazi wanapoondoka.',
         3.0, 'Section 41, Kenya DPA 2019', 9, 0, 'data_storage'],

        ['Data Storage & Security', 'Uhifadhi na Usalama wa Data',
         'Do you conduct regular security risk assessments and penetration testing on all systems that store or process personal data?',
         'Je, unafanya tathmini za hatari za usalama na upimaji wa kupenya mara kwa mara kwenye mifumo yote inayohifadhi au kuchakata data binafsi?',
         'Conduct penetration testing and vulnerability scanning at least annually. Perform DPIAs for high-risk processing. Remediate findings within defined timelines.',
         'Fanya upimaji wa kupenya na uchunguzi wa udhaifu angalau kila mwaka. Fanya DPIA kwa uchakataji wa hatari kubwa. Rekebisha matokeo ndani ya muda ulioainishwa.',
         3.0, 'Section 41, Kenya DPA 2019', 10, 0, 'data_storage'],

        ['Data Storage & Security', 'Uhifadhi na Usalama wa Data',
         'Do you have a documented and tested Data Breach Response Plan that includes 72-hour notification procedures to the ODPC?',
         'Je, una Mpango wa Kukabiliana na Uvunjaji wa Data ulioandikwa na uliojaribiwa unaojumuisha taratibu za taarifa kwa ODPC ndani ya saa 72?',
         'Breach plan must include: detection procedures, containment steps, ODPC notification (72hrs), data subject notification, documentation, and post-incident review. Test the plan annually.',
         'Mpango wa uvunjaji lazima ujumuishe: taratibu za kugundua, hatua za kudhibiti, taarifa kwa ODPC (saa 72), taarifa kwa mhusika wa data, nyaraka, na mapitio ya baada ya tukio. Jaribu mpango kila mwaka.',
         3.5, 'Section 43, Kenya DPA 2019', 11, 1, 'data_storage'],

        // 3. Data Subject Rights
        ['Data Subject Rights', 'Haki za Mhusika wa Data',
         'Do data subjects have a clear, documented mechanism to submit access requests for their personal data?',
         'Je, wamiliki wa data wana utaratibu wazi, ulioandikwa wa kuwasilisha maombi ya ufikiaji wa data zao binafsi?',
         'Right of access must be fulfilled within 21 days. Provide data in a commonly used electronic format. First copy must be free. Verify identity before releasing data.',
         'Haki ya ufikiaji lazima itekelezwe ndani ya siku 21. Toa data katika muundo wa kielektroniki unaotumika kwa kawaida. Nakala ya kwanza lazima iwe bure. Thibitisha utambulisho kabla ya kutoa data.',
         3.0, 'Section 26, Kenya DPA 2019', 12, 0, 'data_subject_rights'],

        ['Data Subject Rights', 'Haki za Mhusika wa Data',
         'Do you have procedures for handling requests to rectify inaccurate or incomplete personal data within a reasonable timeframe?',
         'Je, una taratibu za kushughulikia maombi ya kurekebisha data binafsi zisizo sahihi au zisizo kamili ndani ya muda unaofaa?',
         'Corrections must be made promptly and communicated to third parties where data was shared. Verify accuracy of corrections and document the process.',
         'Marekebisho lazima yafanywe mara moja na yawasilishwe kwa watu wengine pale data iliposhirikiwa. Thibitisha usahihi wa marekebisho na uandike mchakato.',
         2.5, 'Section 27, Kenya DPA 2019', 13, 0, 'data_subject_rights'],

        ['Data Subject Rights', 'Haki za Mhusika wa Data',
         'Do you have a clear procedure for processing erasure requests (right to be forgotten) including exceptions for legal obligations?',
         'Je, una utaratibu wazi wa kushughulikia maombi ya kufuta (haki ya kusahauliwa) ukijumuisha isipokuwa kwa wajibu wa kisheria?',
         'Erasure applies when data no longer necessary, consent withdrawn, or processing unlawful. Balance against legal retention obligations. Document decisions.',
         'Ufutaji unatumika pale data haihitajiki tena, ridhaa imeondolewa, au uchakataji ni haramu. Sawazisha dhidi ya wajibu wa kisheria wa uhifadhi. Andika maamuzi.',
         2.5, 'Section 28, Kenya DPA 2019', 14, 0, 'data_subject_rights'],

        ['Data Subject Rights', 'Haki za Mhusika wa Data',
         'Can data subjects object to automated decision-making or profiling that produces legal effects or significantly affects them?',
         'Je, wamiliki wa data wanaweza kupinga maamuzi ya kiotomatiki au uchambuzi unaozalisha athari za kisheria au kuwaathiri kwa kiasi kikubwa?',
         'Offer human review of automated decisions. Profiling of children is prohibited. Inform subjects about automated processing and their right to object.',
         'Toa mapitio ya kibinadamu ya maamuzi ya kiotomatiki. Uchambuzi wa watoto umekatazwa. Fahamisha wamiliki kuhusu uchakataji wa kiotomatiki na haki yao ya kupinga.',
         2.5, 'Section 34, Kenya DPA 2019', 15, 0, 'data_subject_rights'],

        ['Data Subject Rights', 'Haki za Mhusika wa Data',
         'Do you provide data portability — can data subjects receive their data in a structured, commonly used, machine-readable format?',
         'Je, unatoa uwezo wa kuhamisha data — wamiliki wa data wanaweza kupokea data zao katika muundo uliopangwa, unaotumika kwa kawaida, unaosomeka na mashine?',
         'Data portability applies where processing based on consent/contract and done by automated means. Respond within 21 days. Ensure secure transfer methods.',
         'Uhamishaji wa data unatumika pale uchakataji unategemea ridhaa/mkataba na unafanywa kwa njia za kiotomatiki. Jibu ndani ya siku 21. Hakikisha njia salama za uhamishaji.',
         2.0, 'Section 35, Kenya DPA 2019', 16, 0, 'data_subject_rights'],

        // 4. Data Minimisation & Retention
        ['Data Minimisation & Retention', 'Upunguzaji wa Data na Uhifadhi',
         'Do you only collect personal data that is adequate, relevant, and limited to what is necessary for your stated purposes?',
         'Je, unakusanya tu data binafsi inayotosha, inayofaa, na iliyopunguzwa kwa kile kinachohitajika kwa madhumuni yako yaliyotajwa?',
         'Data minimisation is a core DPA principle. Avoid "just in case" collection. Regular audits should identify and eliminate unnecessary data fields.',
         'Upunguzaji wa data ni kanuni ya msingi ya DPA. Epuka ukusanyaji wa "ikiwa tu". Ukaguzi wa mara kwa mara unapaswa kutambua na kuondoa sehemu za data zisizo za lazima.',
         2.5, 'Section 25(b), Kenya DPA 2019', 17, 0, 'data_minimisation'],

        ['Data Minimisation & Retention', 'Upunguzaji wa Data na Uhifadhi',
         'Do you have a documented data retention schedule with defined retention periods for each category of personal data?',
         'Je, una ratiba iliyoandikwa ya uhifadhi wa data na vipindi vilivyoainishwa vya uhifadhi kwa kila kategoria ya data binafsi?',
         'Retention periods must be justified and documented. Different categories may have different legal/business requirements. Communicate retention periods to data subjects.',
         'Vipindi vya uhifadhi lazima viwe na sababu na viandikwe. Kategoria tofauti zinaweza kuwa na mahitaji tofauti ya kisheria/kibiashara. Wasilisha vipindi vya uhifadhi kwa wamiliki wa data.',
         2.5, 'Section 25(e), Kenya DPA 2019', 18, 0, 'data_minimisation'],

        ['Data Minimisation & Retention', 'Upunguzaji wa Data na Uhifadhi',
         'Is there a documented process for securely deleting or destroying personal data once the retention period has expired?',
         'Je, kuna mchakato ulioandikwa wa kufuta au kuharibu kwa usalama data binafsi mara muda wa uhifadhi unapokwisha?',
         'Secure disposal methods: shredding physical records, cryptographic erasure for digital, secure deletion verification. Document destruction certificates for audit trail.',
         'Njia za utupaji salama: kusaga rekodi za karatasi, kufuta kwa kisimbaji kwa data za kidigitali, uthibitishaji wa ufutaji salama. Andika vyeti vya uharibifu kwa njia ya ukaguzi.',
         2.5, 'Section 25(e), Kenya DPA 2019', 19, 0, 'data_minimisation'],

        ['Data Minimisation & Retention', 'Upunguzaji wa Data na Uhifadhi',
         'Do you conduct periodic data audits to identify and securely remove personal data that is no longer needed?',
         'Je, unafanya ukaguzi wa data mara kwa mara kutambua na kuondoa kwa usalama data binafsi ambazo hazihitajiki tena?',
         'Regular audits maintain data minimisation and reduce breach exposure. Schedule quarterly or bi-annual reviews. Document findings and corrective actions taken.',
         'Ukaguzi wa mara kwa mara hudumisha upunguzaji wa data na kupunguza hatari ya uvunjaji. Panga mapitio ya kila robo au nusu mwaka. Andika matokeo na hatua za kurekebisha zilizochukuliwa.',
         2.0, 'Section 25, Kenya DPA 2019', 20, 0, 'data_minimisation'],

        // 5. Privacy Notices & Transparency
        ['Privacy Notices & Transparency', 'Ilani za Faragha na Uwazi',
         'Do you have a clear, concise, and easily accessible privacy notice/policy published for data subjects?',
         'Je, una ilani/sera ya faragha iliyo wazi, fupi, na inayoweza kufikiwa kwa urahisi iliyochapishwa kwa wamiliki wa data?',
         'Privacy notice must be in plain language, prominently displayed on your website, and available at all data collection points. Include version date.',
         'Ilani ya faragha lazima iwe kwa lugha rahisi, ionyeshwe kwa uwazi kwenye tovuti yako, na ipatikane katika sehemu zote za ukusanyaji wa data. Jumuisha tarehe ya toleo.',
         3.0, 'Section 29, Kenya DPA 2019', 21, 1, 'privacy_notices'],

        ['Privacy Notices & Transparency', 'Ilani za Faragha na Uwazi',
         'Does your privacy notice include all mandatory disclosures: controller identity, data categories, purposes, legal basis, retention, and data subject rights?',
         'Je, ilani yako ya faragha inajumuisha ufichuzi wote wa lazima: utambulisho wa mdhibiti, kategoria za data, madhumuni, msingi wa kisheria, uhifadhi, na haki za mhusika wa data?',
         'Mandatory disclosures per Section 29: controller/DPO contact details, data categories, purposes, legal basis, recipients, retention periods, and all data subject rights.',
         'Ufichuzi wa lazima kwa mujibu wa Kifungu cha 29: maelezo ya mawasiliano ya mdhibiti/DPO, kategoria za data, madhumuni, msingi wa kisheria, wapokeaji, vipindi vya uhifadhi, na haki zote za mhusika wa data.',
         3.0, 'Section 29, Kenya DPA 2019', 22, 1, 'privacy_notices'],

        ['Privacy Notices & Transparency', 'Ilani za Faragha na Uwazi',
         'Are data subjects informed about how their data will be used at the exact point of data collection?',
         'Je, wamiliki wa data wanafahamishwa kuhusu jinsi data zao zitatumika wakati hasa wa ukusanyaji wa data?',
         'Just-in-time privacy notices at each data collection point. Every form, signup, or collection interface must explain purpose, legal basis, and rights before data is submitted.',
         'Ilani za faragha za wakati huo katika kila sehemu ya ukusanyaji. Kila fomu, usajili, au kiolesura cha ukusanyaji lazima kieleze madhumuni, msingi wa kisheria, na haki kabla ya data kuwasilishwa.',
         2.5, 'Section 29, Kenya DPA 2019', 23, 0, 'privacy_notices'],

        ['Privacy Notices & Transparency', 'Ilani za Faragha na Uwazi',
         'Is your privacy notice regularly reviewed and updated to accurately reflect your current data processing activities?',
         'Je, ilani yako ya faragha inakaguliwa na kusasishwa mara kwa mara ili kuonyesha kwa usahihi shughuli zako za sasa za uchakataji wa data?',
         'Review at least annually or when processing changes significantly. Version-control all updates with dates. Notify data subjects of material changes.',
         'Kagua angalau kila mwaka au wakati uchakataji unabadilika kwa kiasi kikubwa. Dhibiti matoleo ya masasisho yote kwa tarehe. Fahamisha wamiliki wa data kuhusu mabadiliko muhimu.',
         2.0, 'Section 29, Kenya DPA 2019', 24, 0, 'privacy_notices'],

        // 6. Data Processors & Third Parties
        ['Data Processors & Third Parties', 'Wachakataji wa Data na Watu Wengine',
         'Do you have written Data Processing Agreements (DPAs) in place with all third-party vendors who handle personal data on your behalf?',
         'Je, una Mikataba ya Uchakataji wa Data (DPA) iliyoandikwa na wachuuzi wote wa nje wanaoshughulikia data binafsi kwa niaba yako?',
         'Written contracts with processors are mandatory under Section 46. Must include: processing scope, duration, nature, purpose, data types, and security obligations.',
         'Mikataba iliyoandikwa na wachakataji ni lazima chini ya Kifungu cha 46. Lazima ijumuishe: upeo wa uchakataji, muda, asili, madhumuni, aina za data, na wajibu wa usalama.',
         3.0, 'Section 46, Kenya DPA 2019', 25, 0, 'data_processors'],

        ['Data Processors & Third Parties', 'Wachakataji wa Data na Watu Wengine',
         'Do you conduct due diligence and security capability assessments on all data processors before engaging their services?',
         'Je, unafanya uchunguzi wa kina na tathmini za uwezo wa usalama kwa wachakataji wote wa data kabla ya kushirikisha huduma zao?',
         'Controllers are responsible for processor compliance. Assess security posture, certifications, breach history. Document assessment before contract signing.',
         'Wadhibiti wanawajibika kwa uzingatiaji wa wachakataji. Tathmini msimamo wa usalama, uthibitisho, historia ya uvunjaji. Andika tathmini kabla ya kusaini mkataba.',
         2.5, 'Section 46, Kenya DPA 2019', 26, 0, 'data_processors'],

        ['Data Processors & Third Parties', 'Wachakataji wa Data na Watu Wengine',
         'Do you maintain a current register or inventory of all data processors and the categories of personal data they handle?',
         'Je, unadumisha sajili au orodha ya kisasa ya wachakataji wote wa data na kategoria za data binafsi wanazoshughulikia?',
         'Processor register supports accountability and breach management. Include: processor name, contact, data categories, processing purpose, location, and DPA reference.',
         'Sajili ya wachakataji inasaidia uwajibikaji na usimamizi wa uvunjaji. Jumuisha: jina la mchakataji, mawasiliano, kategoria za data, madhumuni ya uchakataji, eneo, na rejea ya DPA.',
         2.5, 'Section 46, Kenya DPA 2019', 27, 0, 'data_processors'],

        // 7. Cross-Border Data Transfers
        ['Cross-Border Data Transfers', 'Uhamishaji wa Data Nje ya Mipaka',
         'If you transfer personal data outside Kenya, have you ensured appropriate safeguards are in place for each transfer?',
         'Ikiwa unahamisha data binafsi nje ya Kenya, je, umehakikisha ulinzi unaofaa upo kwa kila uhamishaji?',
         'International transfers require: adequacy decision, Standard Contractual Clauses (SCCs), Binding Corporate Rules, or explicit consent. Document the legal basis for each transfer.',
         'Uhamishaji wa kimataifa unahitaji: uamuzi wa utoshelevu, Vifungu vya Kawaida vya Kimkataba (SCC), Kanuni za Kampuni Zinazofunga, au ridhaa ya wazi. Andika msingi wa kisheria kwa kila uhamishaji.',
         3.0, 'Section 48, Kenya DPA 2019', 28, 0, 'cross_border'],

        ['Cross-Border Data Transfers', 'Uhamishaji wa Data Nje ya Mipaka',
         'Have you obtained ODPC authorization where required for cross-border transfers to countries without adequate data protection?',
         'Je, umepata idhini ya ODPC pale inapohitajika kwa uhamishaji wa data kwenda nchi zisizo na ulinzi wa kutosha wa data?',
         'Transfers to countries lacking adequate protection require ODPC approval. Application must demonstrate appropriate safeguards. Maintain records of all authorizations.',
         'Uhamishaji kwenda nchi zisizo na ulinzi wa kutosha unahitaji idhini ya ODPC. Ombi lazima lionyeshe ulinzi unaofaa. Dumisha rekodi za idhini zote.',
         3.0, 'Section 48-49, Kenya DPA 2019', 29, 0, 'cross_border'],

        // 8. ODPC Registration & Governance
        ['ODPC Registration & Governance', 'Usajili wa ODPC na Utawala',
         'Is your organization registered as a Data Controller or Data Processor with the Office of the Data Protection Commissioner (ODPC)?',
         'Je, shirika lako limesajiliwa kama Mdhibiti au Mchakataji wa Data na Ofisi ya Kamishna wa Ulinzi wa Data (ODPC)?',
         'Registration is mandatory under Section 18. Failure attracts KES 1,000,000 fine. Registration must be renewed annually. Display registration certificate.',
         'Usajili ni lazima chini ya Kifungu cha 18. Kushindwa kuna adhabu ya KES 1,000,000. Usajili lazima ufanywe upya kila mwaka. Onyesha cheti cha usajili.',
         4.0, 'Section 18, Kenya DPA 2019', 30, 1, 'odpc_registration'],

        ['ODPC Registration & Governance', 'Usajili wa ODPC na Utawala',
         'Have you appointed a Data Protection Officer (DPO) with the required qualifications and registered their details with the ODPC?',
         'Je, umemteua Afisa wa Ulinzi wa Data (DPO) mwenye sifa zinazotakiwa na kusajili maelezo yao na ODPC?',
         'DPO required for public bodies, large-scale processing, or special category data. DPO must have expert knowledge, adequate resources, independence, and direct reporting line.',
         'DPO inahitajika kwa mashirika ya umma, uchakataji mkubwa, au data za kategoria maalum. DPO lazima awe na ujuzi wa kitaalamu, rasilimali za kutosha, uhuru, na njia ya kuripoti moja kwa moja.',
         3.0, 'Section 24, Kenya DPA 2019', 31, 0, 'odpc_registration'],

        ['ODPC Registration & Governance', 'Usajili wa ODPC na Utawala',
         'Do you maintain a comprehensive Record of Processing Activities (RoPA) documenting all personal data processing operations?',
         'Je, unadumisha Rekodi kamili ya Shughuli za Uchakataji (RoPA) inayoandika shughuli zote za uchakataji wa data binafsi?',
         'RoPA must include: purposes, legal basis, data categories, recipients, transfers, retention periods, and security measures. Must be available to ODPC upon request.',
         'RoPA lazima ijumuishe: madhumuni, msingi wa kisheria, kategoria za data, wapokeaji, uhamishaji, vipindi vya uhifadhi, na hatua za usalama. Lazima ipatikane kwa ODPC inapoomba.',
         3.0, 'Section 25, Kenya DPA 2019', 32, 0, 'odpc_registration'],

        // 9. Staff Training & Awareness
        ['Staff Training & Awareness', 'Mafunzo ya Wafanyakazi na Uelewa',
         'Do all employees who handle personal data receive regular, role-specific data protection training?',
         'Je, wafanyakazi wote wanaoshughulikia data binafsi wanapata mafunzo ya mara kwa mara, mahususi kwa jukumu, ya ulinzi wa data?',
         'Training must be conducted at least annually and upon hire. Include: DPA principles, data subject rights, breach procedures, security practices. Document completion.',
         'Mafunzo lazima yafanywe angalau kila mwaka na wakati wa kuajiriwa. Jumuisha: kanuni za DPA, haki za mhusika wa data, taratibu za uvunjaji, mazoezi ya usalama. Andika ukamilishaji.',
         2.5, 'Section 25, Kenya DPA 2019', 33, 0, 'staff_training'],

        ['Staff Training & Awareness', 'Mafunzo ya Wafanyakazi na Uelewa',
         'Are staff members aware of their personal obligations under the DPA and the penalties for non-compliance including fines and imprisonment?',
         'Je, wafanyakazi wanafahamu wajibu wao binafsi chini ya DPA na adhabu kwa kutozingatia ikijumuisha faini na kifungo?',
         'Staff must understand: KES 5M fines, criminal penalties up to 10 years, personal liability. Include DPA obligations in employment contracts and code of conduct.',
         'Wafanyakazi lazima waelewe: faini za KES 5M, adhabu za jinai hadi miaka 10, dhima ya kibinafsi. Jumuisha wajibu wa DPA katika mikataba ya ajira na kanuni za maadili.',
         2.5, 'Section 64-65, Kenya DPA 2019', 34, 0, 'staff_training'],

        ['Staff Training & Awareness', 'Mafunzo ya Wafanyakazi na Uelewa',
         'Do employment contracts and confidentiality agreements include specific data protection and confidentiality obligations?',
         'Je, mikataba ya ajira na mikataba ya usiri inajumuisha wajibu maalum wa ulinzi wa data na usiri?',
         'Contractual obligations create enforceable accountability. Include: data handling procedures, confidentiality (surviving termination), breach reporting duties, and training requirements.',
         'Wajibu wa kimkataba huunda uwajibikaji unaoweza kutekelezwa. Jumuisha: taratibu za kushughulikia data, usiri (unaodumu baada ya kumalizika), wajibu wa kuripoti uvunjaji, na mahitaji ya mafunzo.',
         2.0, 'Section 41, Kenya DPA 2019', 35, 0, 'staff_training'],

        // 10. Website & Digital Compliance
        ['Website & Digital Compliance', 'Uzingatiaji wa Tovuti na Dijitali',
         'Does your website enforce HTTPS/TLS encryption on all pages, especially those collecting or displaying personal data?',
         'Je, tovuti yako inatekeleza usimbaji wa HTTPS/TLS kwenye kurasa zote, hasa zile zinazokusanya au kuonyesha data binafsi?',
         'All pages must use HTTPS with TLS 1.2+. Implement HSTS headers. Redirect HTTP to HTTPS. Unencrypted transmission is a Section 41 violation.',
         'Kurasa zote lazima zitumie HTTPS na TLS 1.2+. Tekeleza vichwa vya HSTS. Elekeza HTTP kwenda HTTPS. Usafirishaji bila usimbaji ni ukiukaji wa Kifungu cha 41.',
         3.0, 'Section 41, Kenya DPA 2019', 36, 0, 'website_compliance'],

        ['Website & Digital Compliance', 'Uzingatiaji wa Tovuti na Dijitali',
         'Is a comprehensive, DPA-compliant privacy policy prominently displayed and easily accessible from every page of your website?',
         'Je, sera ya faragha kamili, inayozingatia DPA, inaonyeshwa kwa uwazi na inaweza kufikiwa kwa urahisi kutoka kila ukurasa wa tovuti yako?',
         'Privacy policy must be linked in website footer and at all data collection points. Cover all Section 29 requirements. Use clear, non-legalistic language.',
         'Sera ya faragha lazima iunganishwe kwenye sehemu ya chini ya tovuti na katika sehemu zote za ukusanyaji data. Shughulikia mahitaji yote ya Kifungu cha 29. Tumia lugha wazi, isiyo ya kisheria.',
         3.0, 'Section 29, Kenya DPA 2019', 37, 1, 'website_compliance'],

        ['Website & Digital Compliance', 'Uzingatiaji wa Tovuti na Dijitali',
         'Does your website have a functional cookie consent mechanism that obtains explicit opt-in consent before setting non-essential cookies?',
         'Je, tovuti yako ina utaratibu wa ridhaa ya vidakuzi unaofanya kazi unaopata ridhaa ya wazi ya kuchagua kuingia kabla ya kuweka vidakuzi visivyo vya muhimu?',
         'Pre-consent cookies limited to essential only. Tracking/analytics/marketing cookies require explicit opt-in. Consent must be freely given, specific, and easily withdrawable.',
         'Vidakuzi kabla ya ridhaa vinapaswa kuwa muhimu tu. Vidakuzi vya ufuatiliaji/uchambuzi/masoko vinahitaji kuchagua kuingia kwa wazi. Ridhaa lazima itolewe kwa hiari, iwe mahususi, na iweze kuondolewa kwa urahisi.',
         2.5, 'Section 32, Kenya DPA 2019', 38, 0, 'website_compliance'],

        ['Website & Digital Compliance', 'Uzingatiaji wa Tovuti na Dijitali',
         'Are all web forms that collect personal data secured with HTTPS and accompanied by a just-in-time privacy notice?',
         'Je, fomu zote za wavuti zinazokusanya data binafsi zinalindwa kwa HTTPS na kuambatana na ilani ya faragha ya wakati huo?',
         'Forms must use POST method over HTTPS with CSRF protection. Each form must explain: purpose of collection, legal basis, and link to full privacy policy.',
         'Fomu lazima zitumie njia ya POST juu ya HTTPS na ulinzi wa CSRF. Kila fomu lazima ieleze: madhumuni ya ukusanyaji, msingi wa kisheria, na kiungo cha sera kamili ya faragha.',
         2.5, 'Section 29, Kenya DPA 2019', 39, 0, 'website_compliance'],

        // 11. Data Protection Impact Assessment
        ['Data Protection Impact Assessment', 'Tathmini ya Athari za Ulinzi wa Data',
         'Have you conducted Data Protection Impact Assessments (DPIAs) for all high-risk data processing activities?',
         'Je, umefanya Tathmini za Athari za Ulinzi wa Data (DPIA) kwa shughuli zote za uchakataji wa data zenye hatari kubwa?',
         'DPIAs mandatory for: large-scale special category data, systematic monitoring, new technologies. Conduct before processing begins. Consult DPO. Review periodically.',
         'DPIA ni lazima kwa: data za kategoria maalum kwa kiwango kikubwa, ufuatiliaji wa kimfumo, teknolojia mpya. Fanya kabla ya uchakataji kuanza. Wasiliana na DPO. Pitia mara kwa mara.',
         3.0, 'Section 41(5), Kenya DPA 2019', 40, 0, 'dpia'],

        ['Data Protection Impact Assessment', 'Tathmini ya Athari za Ulinzi wa Data',
         'Do you have a documented process for determining when a DPIA is required for new projects or processing activities?',
         'Je, una mchakato ulioandikwa wa kuamua wakati DPIA inahitajika kwa miradi mipya au shughuli za uchakataji?',
         'Establish DPIA threshold assessment as part of project approval. Any processing likely to result in high risk triggers mandatory DPIA. Document the decision rationale.',
         'Anzisha tathmini ya kizingiti cha DPIA kama sehemu ya idhini ya mradi. Uchakataji wowote unaowezekana kusababisha hatari kubwa unasababisha DPIA ya lazima. Andika sababu za uamuzi.',
         2.5, 'Section 41(5), Kenya DPA 2019', 41, 0, 'dpia'],
    ];

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

// ============================================================
// DEFAULT RECOMMENDATIONS with Swahili translations
// ============================================================
function insertDefaultRecommendations($pdo) {
    $recs = [
        ['critical,very-high,high', 'ODPC Registration', '30', 'immediate',
         'Register as a Data Controller/Processor with ODPC immediately at odpc.go.ke. Non-registration carries a KES 1,000,000 mandatory fine under Section 18.',
         'Jiandikishe kama Mdhibiti/Mchakataji wa Data na ODPC mara moja kwenye odpc.go.ke. Kutojisajili kuna adhabu ya lazima ya KES 1,000,000 chini ya Kifungu cha 18.',
         '30 days', 'Section 18, Kenya DPA 2019', 'KES 1,000,000 fixed penalty',
         '2,3', 'ODPC Registration & Governance'],

        ['critical,very-high,high', 'Data Breach Response', '11', 'immediate',
         'Establish, document, and test a Data Breach Response Plan. Ensure capability to notify ODPC within 72 hours as required by Section 43.',
         'Anzisha, andika, na ujaribu Mpango wa Kukabiliana na Uvunjaji wa Data. Hakikisha uwezo wa kuarifu ODPC ndani ya saa 72 kama inavyotakiwa na Kifungu cha 43.',
         '30 days', 'Section 43, Kenya DPA 2019', 'KES 5,000,000 fine',
         '2,3', 'Data Storage & Security'],

        ['critical,very-high', 'Data Encryption', '6,7', 'immediate',
         'Implement encryption immediately: AES-256 for stored data, TLS 1.2+ for data in transit. Document all data storage locations. Unencrypted personal data violates Section 41.',
         'Tekeleza usimbaji mara moja: AES-256 kwa data iliyohifadhiwa, TLS 1.2+ kwa data inayosafiri. Andika maeneo yote ya uhifadhi wa data. Data binafsi isiyosimbwa inakiuka Kifungu cha 41.',
         '14 days', 'Section 41, Kenya DPA 2019', 'Criminal liability + civil damages',
         '2,3', 'Data Storage & Security'],

        ['all', 'Privacy Notice', '21,22', 'immediate',
         'Publish a comprehensive privacy policy covering all Section 29 requirements: controller identity, purposes, legal basis, data categories, recipients, retention, and data subject rights.',
         'Chapisha sera kamili ya faragha inayoshughulikia mahitaji yote ya Kifungu cha 29: utambulisho wa mdhibiti, madhumuni, msingi wa kisheria, kategoria za data, wapokeaji, uhifadhi, na haki za mhusika wa data.',
         '30 days', 'Section 29, Kenya DPA 2019', 'ODPC enforcement + KES 5,000,000',
         '2,3', 'Privacy Notices & Transparency'],

        ['critical,very-high', 'Children Data', '4', 'immediate',
         'Implement verifiable parental/guardian consent mechanisms for processing children\'s data. Establish age verification. Processing minors\' data without proper consent violates Section 33.',
         'Tekeleza taratibu za ridhaa ya mzazi/mlezi inayoweza kuthibitishwa kwa kuchakata data za watoto. Anzisha uthibitishaji wa umri. Kuchakata data za watoto bila ridhaa sahihi kunakiuka Kifungu cha 33.',
         '30 days', 'Section 33, Kenya DPA 2019', 'KES 5,000,000 + criminal liability',
         '2,3', 'Data Collection & Consent'],

        ['critical,very-high,high,moderate', 'Data Subject Rights', '12,13,14,15,16', 'short-term',
         'Implement Data Subject Rights Management: access (21-day SLA), rectification, erasure, portability, and objection procedures. Create response templates and tracking system.',
         'Tekeleza Usimamizi wa Haki za Mhusika wa Data: ufikiaji (SLA ya siku 21), marekebisho, ufutaji, uhamishaji, na taratibu za kupinga. Unda violezo vya majibu na mfumo wa ufuatiliaji.',
         '60 days', 'Section 26-35, Kenya DPA 2019', 'ODPC complaints + court damages',
         '2,3', 'Data Subject Rights'],

        ['critical,very-high,high,moderate', 'Consent Management', '2,3,5', 'short-term',
         'Deploy Consent Management Platform ensuring consent is freely given, specific, informed, unambiguous, and easily withdrawable. Document all consent records for accountability.',
         'Weka Jukwaa la Usimamizi wa Ridhaa kuhakikisha ridhaa inatolewa kwa hiari, ni mahususi, yenye taarifa, isiyo na utata, na inaweza kuondolewa kwa urahisi. Andika rekodi zote za ridhaa.',
         '60 days', 'Section 32, Kenya DPA 2019', 'KES 5,000,000 + processing injunction',
         '2,3', 'Data Collection & Consent'],

        ['critical,very-high,high,moderate', 'Data Processor Contracts', '25,26,27', 'short-term',
         'Execute DPAs with all vendors and processors. Include Section 46 mandatory clauses. Conduct due diligence. Maintain current processor register.',
         'Tekeleza DPA na wachuuzi na wachakataji wote. Jumuisha vifungu vya lazima vya Kifungu cha 46. Fanya uchunguzi wa kina. Dumisha sajili ya kisasa ya wachakataji.',
         '60 days', 'Section 46, Kenya DPA 2019', 'Joint liability with processors',
         '2,3', 'Data Processors & Third Parties'],

        ['all', 'Data Protection Officer', '31', 'short-term',
         'Appoint a qualified DPO. Register DPO details with ODPC. Ensure adequate resources, independence, and direct reporting to highest management level.',
         'Mteue DPO mwenye sifa. Sajili maelezo ya DPO na ODPC. Hakikisha rasilimali za kutosha, uhuru, na kuripoti moja kwa moja kwa usimamizi wa juu.',
         '60 days', 'Section 24, Kenya DPA 2019', 'ODPC enforcement + reputational risk',
         '2,3', 'ODPC Registration & Governance'],

        ['all', 'DPIA Programme', '40,41', 'medium-term',
         'Establish DPIA programme for high-risk processing. Create threshold assessment process. Conduct DPIAs before launching new products or processing activities.',
         'Anzisha mpango wa DPIA kwa uchakataji wa hatari kubwa. Unda mchakato wa tathmini ya kizingiti. Fanya DPIA kabla ya kuzindua bidhaa mpya au shughuli za uchakataji.',
         '3 months', 'Section 41(5), Kenya DPA 2019', 'Regulatory censure + suspension',
         '2,3', 'Data Protection Impact Assessment'],

        ['all', 'Staff Training', '33,34', 'medium-term',
         'Implement mandatory annual data protection training for all staff. Role-specific training for DPO, IT, HR, marketing. Document all training completion records.',
         'Tekeleza mafunzo ya lazima ya kila mwaka ya ulinzi wa data kwa wafanyakazi wote. Mafunzo mahususi kwa DPO, IT, HR, masoko. Andika rekodi zote za ukamilishaji wa mafunzo.',
         '3 months', 'Section 25, Kenya DPA 2019', 'Employer liability for staff breaches',
         '2,3', 'Staff Training & Awareness'],

        ['all', 'RoPA Documentation', '32', 'medium-term',
         'Create comprehensive Record of Processing Activities. Document: purposes, categories, recipients, transfers, retention periods, and security measures for all processing.',
         'Unda Rekodi kamili ya Shughuli za Uchakataji. Andika: madhumuni, kategoria, wapokeaji, uhamishaji, vipindi vya uhifadhi, na hatua za usalama kwa uchakataji wote.',
         '3 months', 'Section 25, Kenya DPA 2019', 'ODPC audit failure + KES 5,000,000',
         '2,3', 'ODPC Registration & Governance'],

        ['all', 'Retention & Disposal', '18,19,20', 'medium-term',
         'Develop Data Retention and Disposal Policy with defined retention periods per category, automated deletion scheduling, and secure disposal certification.',
         'Tengeneza Sera ya Uhifadhi na Utupaji wa Data na vipindi vilivyoainishwa kwa kila kategoria, ratiba ya ufutaji wa kiotomatiki, na uthibitisho wa utupaji salama.',
         '3 months', 'Section 25(e), Kenya DPA 2019', 'Unlawful retention = DPA violation',
         '2,3', 'Data Minimisation & Retention'],

        ['all', 'Privacy by Design', null, 'long-term',
         'Embed Privacy by Design principles into all systems, products, and processes. Establish privacy governance committee with regular DPA compliance review cycles.',
         'Weka kanuni za Faragha kwa Ubunifu katika mifumo, bidhaa, na michakato yote. Anzisha kamati ya utawala wa faragha na mizunguko ya mapitio ya uzingatiaji wa DPA.',
         '6 months', 'Section 25, Kenya DPA 2019', 'Systemic non-compliance risk',
         null, null],

        ['all', 'Cross-Border Transfers', '28,29', 'long-term',
         'Conduct international data transfer audit. Implement SCCs or obtain ODPC authorization for transfers to countries without adequate data protection.',
         'Fanya ukaguzi wa uhamishaji wa data wa kimataifa. Tekeleza SCC au pata idhini ya ODPC kwa uhamishaji kwenda nchi zisizo na ulinzi wa kutosha.',
         '6 months', 'Section 48-49, Kenya DPA 2019', 'KES 5,000,000 per transfer',
         '2,3', 'Cross-Border Data Transfers'],

        ['all', 'Compliance Certification', null, 'long-term',
         'Pursue ISO 27001 certification. Conduct annual third-party DPA compliance audits. This demonstrates good faith accountability to the ODPC.',
         'Fuatilia uthibitisho wa ISO 27001. Fanya ukaguzi wa kila mwaka wa uzingatiaji wa DPA na watu wengine. Hii inaonyesha uwajibikaji wa nia njema kwa ODPC.',
         '12 months', 'Section 17, Kenya DPA 2019', 'Demonstrates good faith to ODPC',
         null, null],
    ];

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

// ============================================================
// INDUSTRY TEMPLATES with Swahili
// ============================================================
function insertIndustryTemplates($pdo) {
    $templates = [
        ['financial', 'Financial Services / Banking', 'Huduma za Kifedha / Benki',
         '<div class="industry-notes"><h4>Industry-Specific: Financial Services</h4><p>Must comply with <strong>CBK Prudential Guidelines</strong> plus DPA 2019:</p><ul><li><strong>KYC/AML Data:</strong> Requires clear lawful basis and secure storage (S.30).</li><li><strong>CRB Sharing:</strong> Explicit consent required (S.32).</li><li><strong>Fraud Detection:</strong> Automated systems must comply with S.34.</li><li><strong>Data Localization:</strong> CBK requires critical data stored in Kenya (S.48).</li><li><strong>Breach Notification:</strong> Notify ODPC (72hrs) AND CBK (24hrs).</li><li><strong>Retention:</strong> Minimum 7 years per CBK — implement tiered policies.</li></ul></div>',
         '<div class="industry-notes"><h4>Mahususi kwa Sekta: Huduma za Kifedha</h4><p>Lazima zizingatie <strong>Miongozo ya CBK</strong> pamoja na DPA 2019:</p><ul><li><strong>Data za KYC/AML:</strong> Zinahitaji msingi halali na hifadhi salama (K.30).</li><li><strong>Ushirikishaji CRB:</strong> Ridhaa ya wazi inahitajika (K.32).</li><li><strong>Ugunduzi wa Udanganyifu:</strong> Mifumo ya kiotomatiki lazima izingatie K.34.</li><li><strong>Uwekaji Data Ndani:</strong> CBK inahitaji data muhimu Kenya (K.48).</li><li><strong>Taarifa ya Uvunjaji:</strong> Arifu ODPC (saa 72) NA CBK (saa 24).</li><li><strong>Uhifadhi:</strong> Angalau miaka 7 kwa CBK — tekeleza sera zilizopangwa.</li></ul></div>'],

        ['healthcare', 'Healthcare / Medical', 'Afya / Matibabu',
         '<div class="industry-notes"><h4>Industry-Specific: Healthcare</h4><p>Handle <strong>special category data</strong> requiring enhanced protection:</p><ul><li><strong>Explicit Consent:</strong> Required for health data (S.31(a)).</li><li><strong>Confidentiality:</strong> Comply with Medical Practitioners Act + DPA.</li><li><strong>Data Sharing:</strong> With insurers/researchers needs consent/legal basis.</li><li><strong>Records Retention:</strong> Per Ministry of Health (7-10 years adults).</li><li><strong>Telemedicine:</strong> Encrypted channels + secure storage (S.41).</li><li><strong>DPIA:</strong> Mandatory for large-scale health processing (S.41(5)).</li></ul></div>',
         '<div class="industry-notes"><h4>Mahususi kwa Sekta: Afya</h4><p>Shughulikia <strong>data za kategoria maalum</strong> zinazohitaji ulinzi ulioimarishwa:</p><ul><li><strong>Ridhaa ya Wazi:</strong> Inahitajika kwa data za afya (K.31(a)).</li><li><strong>Usiri:</strong> Zingatia Sheria ya Madaktari + DPA.</li><li><strong>Ushirikishaji Data:</strong> Na bima/watafiti kunahitaji ridhaa/msingi wa kisheria.</li><li><strong>Uhifadhi Rekodi:</strong> Kwa Wizara ya Afya (miaka 7-10 watu wazima).</li><li><strong>Telemedicine:</strong> Njia zilizosimbwa + hifadhi salama (K.41).</li><li><strong>DPIA:</strong> Lazima kwa uchakataji mkubwa wa afya (K.41(5)).</li></ul></div>'],

        ['technology', 'Technology / IT Services', 'Teknolojia / Huduma za IT',
         '<div class="industry-notes"><h4>Industry-Specific: Technology/IT</h4><p>Often act as both <strong>Controllers and Processors</strong>:</p><ul><li><strong>Privacy by Design:</strong> Embed in development lifecycle (S.25).</li><li><strong>Cloud:</strong> DPAs with all sub-processors (S.46).</li><li><strong>API Security:</strong> Auth, encryption, rate limiting, audit logs (S.41).</li><li><strong>Data Portability:</strong> Machine-readable exports (S.35).</li><li><strong>AI/ML:</strong> Human review options for automated decisions (S.34).</li><li><strong>Pen Testing:</strong> Regular security testing essential.</li></ul></div>',
         '<div class="industry-notes"><h4>Mahususi kwa Sekta: Teknolojia/IT</h4><p>Mara nyingi hufanya kama <strong>Wadhibiti na Wachakataji</strong>:</p><ul><li><strong>Faragha kwa Ubunifu:</strong> Weka katika mzunguko wa maendeleo (K.25).</li><li><strong>Wingu:</strong> DPA na wachakataji wote wadogo (K.46).</li><li><strong>Usalama wa API:</strong> Uthibitishaji, usimbaji, kumbukumbu (K.41).</li><li><strong>Uhamishaji Data:</strong> Mauzo kwa muundo unaosomeka (K.35).</li><li><strong>AI/ML:</strong> Chaguo za mapitio ya kibinadamu (K.34).</li><li><strong>Upimaji Kupenya:</strong> Upimaji wa usalama wa mara kwa mara ni muhimu.</li></ul></div>'],

        ['retail', 'Retail / E-commerce', 'Rejareja / E-commerce',
         '<div class="industry-notes"><h4>Industry-Specific: Retail/E-commerce</h4><p>Process significant customer and payment data:</p><ul><li><strong>PCI DSS:</strong> Payment card data must comply with PCI DSS + S.41.</li><li><strong>Marketing:</strong> Email/SMS requires opt-in consent (S.32).</li><li><strong>Profiling:</strong> Recommendation engines comply with S.34.</li><li><strong>Delivery:</strong> DPAs with courier/logistics partners (S.46).</li><li><strong>Cookies:</strong> Comprehensive consent management mandatory (S.32).</li><li><strong>Retention:</strong> Purchase history must be justified.</li></ul></div>',
         '<div class="industry-notes"><h4>Mahususi kwa Sekta: Rejareja/E-Commerce</h4><p>Chakata data nyingi za wateja na malipo:</p><ul><li><strong>PCI DSS:</strong> Data za kadi lazima zizingatie PCI DSS + K.41.</li><li><strong>Masoko:</strong> Barua pepe/SMS zinahitaji ridhaa (K.32).</li><li><strong>Uchambuzi:</strong> Injini za mapendekezo zizingatie K.34.</li><li><strong>Utoaji:</strong> DPA na washirika wa usafirishaji (K.46).</li><li><strong>Vidakuzi:</strong> Usimamizi kamili wa ridhaa ni lazima (K.32).</li><li><strong>Uhifadhi:</strong> Historia ya manunuzi lazima iwe na sababu.</li></ul></div>'],
    ];

    $stmt = $pdo->prepare("INSERT OR IGNORE INTO industry_templates (industry_key, industry_name, industry_name_sw, template_content, template_content_sw, specific_requirements, specific_requirements_sw) VALUES (?,?,?,?,?,?,?)");
    foreach ($templates as $t) {
        $stmt->execute($t);
    }
}

// ============================================================
// 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];
$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; }

    $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/4.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);

        $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";
            }
        }

        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'];
        }

        $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'];
        }

        $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 under Section 32'];
        }

        $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';

        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 ({$res['forms_count']} form(s)) without visible privacy notice – Section 29 violation"];
            }
        }

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

        $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 {
        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 on HTTP only – all personal data transmitted in plaintext (Section 41 violation)'];
            $res['web_risk_percent'] = 85;
        } else {
            $res['findings'][] = ['level' => 'info', 'text' => 'Website unreachable – manual verification required'];
        }
    }
    curl_close($ch);
    return $res;
}

// ============================================================
// FORM PROCESSING
// ============================================================
$assessmentResult  = false;
$reportHTML        = '';
$reportRef         = '';
$riskPercent       = 0;
$riskLevel         = '';
$riskColor         = '';
$compliancePercent = 0;
$failedCategories  = [];
$nonCompliantQuestions = [];
$partialQuestions      = [];

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;
        $critMultiplier = $q['is_critical'] ? 1.5 : 1.0;
        $weighted    = $score * $q['weight'] * $critMultiplier;
        $maxWeighted = 3 * $q['weight'] * $critMultiplier;

        if ($score == 2 && $q['is_critical']) {
            $weighted *= 1.3;
        }

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

        $cat = $q['category'];
        if (!isset($categoryScores[$cat])) $categoryScores[$cat] = ['score' => 0, 'max' => 0, 'count' => 0, 'questions' => [], 'failed' => 0, 'partial' => 0];
        $categoryScores[$cat]['score'] += $weighted;
        $categoryScores[$cat]['max']   += $maxWeighted;
        $categoryScores[$cat]['count']++;
        $categoryScores[$cat]['questions'][] = $q['id'];
        
        if ($score == 2) {
            $categoryScores[$cat]['failed']++;
            $nonCompliantQuestions[] = $q['id'];
        } elseif ($score == 1) {
            $categoryScores[$cat]['partial']++;
            $partialQuestions[] = $q['id'];
        }

        // Use language-appropriate question/guidance
        $qText = ($lang === 'sw' && !empty($q['question_sw'])) ? $q['question_sw'] : $q['question'];
        $gText = ($lang === 'sw' && !empty($q['guidance_sw'])) ? $q['guidance_sw'] : $q['guidance'];
        $catText = ($lang === 'sw' && !empty($q['category_sw'])) ? $q['category_sw'] : $q['category'];

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

    foreach ($categoryScores as $cat => $cs) {
        $catFailedPercent = ($cs['count'] > 0) ? ($cs['failed'] / $cs['count']) * 100 : 0;
        if ($catFailedPercent >= 40) {
            $failedCategories[] = $cat;
        }
    }

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

    if ($websiteScan && isset($websiteScan['web_risk_percent'])) {
        $webScore = $websiteScan['web_risk_percent'];
        if (!$websiteScan['https'] || !$websiteScan['privacy']['privacy_policy']) {
            $webScore = min(100, $webScore * 1.25);
        }
        $webAdj      = $webScore * 0.15;
        $riskPercent = min(100, round($riskPercent + $webAdj));
    }

    $penaltyMultiplier = [
        'financial' => 1.3, 'healthcare' => 1.3, 'technology' => 1.2,
        'government' => 1.1, 'retail' => 1.1, 'legal' => 1.0,
        'education' => 1.0, 'media' => 1.0, 'hospitality' => 0.9,
        'manufacturing' => 0.9, 'realestate' => 0.9, 'ngo' => 0.8,
        'transport' => 0.9, 'agriculture' => 0.8, 'other' => 0.8
    ];
    
    $industryPenaltyFactor = $penaltyMultiplier[$companyIndustry] ?? 1.0;
    $riskPercent = min(100, round($riskPercent * $industryPenaltyFactor));
    $riskPercent = max(5, min(99, $riskPercent));

    $compliancePercent = ($maxScore > 0) ? round((1 - ($totalScore / $maxScore)) * 100) : 95;

    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'; }

    // DYNAMIC RECOMMENDATIONS
    $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 = [];
    $allFailedPartialIds = array_merge($nonCompliantQuestions, $partialQuestions);
    
    foreach ($allRecs as $rec) {
        $levels = array_map('trim', explode(',', $rec['risk_level']));
        $shouldInclude = in_array($riskClass, $levels) || in_array('all', $levels);
        
        if (!$shouldInclude && !empty($rec['failed_question_ids'])) {
            $triggerIds = array_map('intval', explode(',', $rec['failed_question_ids']));
            foreach ($triggerIds as $tid) {
                if (in_array($tid, $allFailedPartialIds)) {
                    $shouldInclude = true;
                    break;
                }
            }
        }
        
        if (!$shouldInclude && !empty($rec['triggers_on_category_fail'])) {
            $triggerCats = array_map('trim', explode(',', $rec['triggers_on_category_fail']));
            foreach ($triggerCats as $tcat) {
                if (in_array($tcat, $failedCategories)) {
                    $shouldInclude = true;
                    break;
                }
            }
        }
        
        if (!$shouldInclude && !empty($rec['triggers_on_answer'])) {
            $triggerAnswers = array_map('intval', explode(',', $rec['triggers_on_answer']));
            foreach ($allFailedPartialIds as $fid) {
                if (isset($responses[$fid]) && in_array($responses[$fid]['score'], $triggerAnswers)) {
                    $shouldInclude = true;
                    break;
                }
            }
        }
        
        if ($shouldInclude) {
            $recommendations[] = $rec;
        }
    }
    
    if (empty($recommendations)) {
        foreach ($allRecs as $rec) {
            $levels = array_map('trim', explode(',', $rec['risk_level']));
            if (in_array('all', $levels)) {
                $recommendations[] = $rec;
            }
        }
    }

    $reportRef = 'DPA-' . date('Ymd-His');
    $assessmentDate = date('Y-m-d H:i:s');

    $industryTemplate = null;
    if ($companyIndustry) {
        $stmt = $pdo->prepare("SELECT * FROM industry_templates WHERE industry_key = ?");
        $stmt->execute([$companyIndustry]);
        $industryTemplate = $stmt->fetch();
        // Use language-appropriate template
        if ($industryTemplate && $lang === 'sw' && !empty($industryTemplate['template_content_sw'])) {
            $industryTemplate['template_content'] = $industryTemplate['template_content_sw'];
        }
    }

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

    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,
             failed_categories,non_compliant_questions,partial_questions,assessment_lang)
            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,
            json_encode($failedCategories), json_encode($nonCompliantQuestions),
            json_encode($partialQuestions), $lang
        ]);
    } catch(Exception $e) { /* non-fatal */ }

    $assessmentResult = true;
}

// ============================================================
// REPORT GENERATOR - Single language (no mixing)
// ============================================================
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;

    // Set locale for date formatting
    if ($lang === 'sw') {
        setlocale(LC_TIME, 'sw_KE.UTF-8', 'sw_KE', 'sw');
    }
    $dateF = date('jS F Y', strtotime($assessmentDate));
    $timeF = date('H:i T', strtotime($assessmentDate));

    $riskIcons = ['Low Risk'=>'✅','Moderate Risk'=>'⚠️','High Risk'=>'🔶','Very High Risk'=>'🚨','Critical Risk'=>'⛔'];
    $riskIcon  = $riskIcons[$riskLevel] ?? '⚠️';
    $compColor = $compliancePercent >= 80 ? '#22c55e' : ($compliancePercent >= 60 ? '#eab308' : ($compliancePercent >= 40 ? '#f97316' : '#ef4444'));

    $verifyUrl = 'https://sttpx.top/member/verify.php?ref=' . urlencode($reportRef);

    // QR Code at the end (single QR code on the signatures page)
    $qrUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=' . urlencode($verifyUrl);

    $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;
    }

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

    $criticalFindings = [];
    foreach ($responses as $r) {
        if ($r['score'] >= 2) {
            $criticalFindings[] = $r;
        }
    }
    usort($criticalFindings, function($a, $b) {
        return ($b['weight'] * $b['score']) - ($a['weight'] * $a['score']);
    });
    $topFindings = array_slice($criticalFindings, 0, 5);

    // Single language output based on $lang
    ob_start();
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>">
<head>
<meta charset="UTF-8">
<title><?= __('report_title') ?> – <?= 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 { page-break-after: always; text-align: center; padding: 50px 20px; }
  .cover h1 { font-size: 24pt; letter-spacing: 2px; margin: 0; color: #1a1a2e; }
  .cover h2 { font-size: 16pt; color: #374151; margin: 6px 0 30px; font-weight: 400; }
  .cover-badge { display: inline-block; width: 140px; height: 140px; border-radius: 50%;
    border: 6px solid <?= $riskColor ?>; background: #fafafa;
    line-height: 1.2; padding-top: 35px; margin: 20px auto; }
  .cover-badge .big { font-size: 32pt; font-weight: 900; color: <?= $riskColor ?>; display: block; }
  .cover-badge .sm  { font-size: 9pt; text-transform: uppercase; color: <?= $riskColor ?>; display: block; }
  .cover-risk { font-size: 18pt; font-weight: 700; color: <?= $riskColor ?>; margin: 10px 0; }
  .cover-org  { font-size: 15pt; 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; }

  .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 ?>; }

  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; }

  .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-grid { display: flex; flex-wrap: wrap; gap: 12px; margin: 16px 0; }
  .s-card { flex: 1; min-width: 110px; border-radius: 8px; padding: 14px; text-align: center; border: 1px solid #e2e8f0; }
  .s-card .num { font-size: 24pt; font-weight: 800; display: block; }
  .s-card .lbl { font-size: 8.5pt; text-transform: uppercase; color: #6b7280; }

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

  .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') ?>; }

  .exec-insight { background: #f0fdf4; border: 1px solid #86efac; border-radius: 8px; padding: 14px 18px; margin: 12px 0; }
  .exec-insight h4 { color: #065f46; margin: 0 0 6px; font-size: 11pt; }
  
  .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; }

  .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-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; }

  .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; }

  .glossary-term { font-weight: 700; font-size: 10pt; margin: 8px 0 2px; }
  .glossary-def  { font-size: 9pt; color: #374151; margin: 0 0 8px 12px; padding-left: 8px; border-left: 2px solid #e2e8f0; }

  .industry-notes { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 14px 18px; margin: 12px 0; }
  .industry-notes h4 { color: <?= $riskColor ?>; margin: 0 0 8px; font-size: 11pt; }
  .industry-notes ul { margin: 8px 0 0 18px; padding: 0; }
  .industry-notes li { margin: 4px 0; font-size: 9.5pt; }

  .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 { text-align: center; font-size: 8pt; color: #9ca3af; margin-top: 30px; padding-top: 12px; border-top: 1px solid #e2e8f0; }

  .qr-section { text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #e2e8f0; }
  .qr-section img { width: 180px; height: 180px; border: 1px solid #e2e8f0; border-radius: 8px; }

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

<!-- ===================== COVER PAGE ===================== -->
<div class="cover">
  <h1><?= __('report_title') ?></h1>
  <h2><?= __('report_subtitle') ?></h2>

  <div class="cover-badge">
    <span class="big"><?= $riskPercent ?>%</span>
    <span class="sm"><?= __('risk_score_label') ?></span>
  </div>
  <div class="cover-risk"><?= $riskIcon ?> <?= $riskLevel ?></div>

  <p style="font-size:11pt;color:#6b7280;margin:6px 0">
    <?= __('compliance_level_label') ?>: <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"><?= htmlspecialchars($industryName) ?> &nbsp;|&nbsp; <?= htmlspecialchars($sizeName) ?></p>

  <div class="cover-meta">
    <p><strong>📄 <?= __('report_reference') ?>:</strong> <?= $reportRef ?></p>
    <p><strong>📅 <?= __('assessment_date_label') ?>:</strong> <?= $dateF ?> at <?= $timeF ?></p>
    <p><strong>⚖️ <?= __('framework') ?>:</strong> <?= __('kenya_dpa_full') ?></p>
    <p><strong>🏛️ <?= __('odpc_kenya') ?>:</strong> Office of the Data Protection Commissioner (ODPC), Kenya</p>
    <p><strong>👤 <?= __('assessed_by') ?>:</strong> Christopher Khayere</p>
  </div>
</div>

<!-- ===================== 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_label') ?>: <strong style="color:<?= $compColor ?>"><?= $compliancePercent ?>%</strong> &nbsp;|&nbsp;
    <?= $answeredCount ?> <?= __('indicators_assessed_across') ?> <?= count($categories) ?> <?= __('compliance_categories') ?>
  </p>
</div>

<p><?= __('assessment_conducted_for') ?>
<strong><?= htmlspecialchars($companyName) ?></strong>
<?php if (!empty($companyWebsite)): ?>(<em><?= htmlspecialchars($companyWebsite) ?></em>)<?php endif; ?>,
<?= __('operating_in') ?> <strong><?= htmlspecialchars($industryName) ?></strong> <?= __('sector_with') ?> <strong><?= htmlspecialchars($sizeName) ?></strong> <?= __('employees') ?>
<?= __('assessment_evaluated') ?> <strong><?= $answeredCount ?> <?= __('compliance_indicators') ?></strong> <?= __('against_the') ?>
<strong><?= __('kenya_dpa_full') ?></strong> <?= __('and_regulations') ?></p>

<p><?= __('organisation_received') ?>
<strong style="color:<?= $riskColor ?>"><?= $riskPercent ?>%</strong>,
<?= __('indicating') ?> <strong style="color:<?= $riskColor ?>"><?= $riskLevel ?></strong> <?= __('posture_with') ?>
<strong style="color:<?= $compColor ?>"><?= $compliancePercent ?>% <?= __('overall_compliance') ?></strong>
<?php if ($websiteScan && $websiteScan['reachable']): ?>
<?= __('website_scanning_performed') ?>
<?php endif; ?></p>

<div class="exec-insight">
  <h4>📌 <?= __('key_findings_leadership') ?></h4>
  <?php if (empty($topFindings)): ?>
  <p style="margin:0;font-size:10pt"><?= __('all_compliant_msg') ?> <?= $compliancePercent ?>% <?= __('compliance_level') ?></p>
  <?php else: ?>
  <p style="margin:0 0 8px;font-size:9.5pt"><?= __('critical_gaps_msg') ?></p>
  <ol style="margin:0;padding-left:20px;font-size:9.5pt">
    <?php foreach ($topFindings as $i => $f): ?>
    <li style="margin:4px 0">
      <strong style="color:<?= $f['color'] ?>">[<?= $f['risk_label'] ?>]</strong> 
      <?= htmlspecialchars($f['question']) ?>
      <br><small style="color:#6b7280">📜 <?= htmlspecialchars($f['reference']) ?></small>
    </li>
    <?php endforeach; ?>
  </ol>
  <?php endif; ?>
  <p style="margin:10px 0 0;font-size:9pt;color:#065f46">
    <strong>💡 <?= __('bottom_line') ?>:</strong> 
    <?php if ($riskPercent <= 30): ?>
    <?= __('solid_foundation') ?>
    <?php elseif ($riskPercent <= 55): ?>
    <?= __('gaps_exist') ?>
    <?php else: ?>
    <?= __('significant_deficiencies') ?>
    <?php endif; ?>
  </p>
</div>

<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_status') ?></span>
  </div>
  <div class="s-card" style="border-color:#eab308">
    <span class="num" style="color:#eab308"><?= $statusCount[1] ?></span>
    <span class="lbl"><?= __('partial_status') ?></span>
  </div>
  <div class="s-card" style="border-color:#ef4444">
    <span class="num" style="color:#ef4444"><?= $statusCount[2] ?></span>
    <span class="lbl"><?= __('non_compliant_status') ?></span>
  </div>
  <div class="s-card" style="border-color:#a855f7">
    <span class="num" style="color:#a855f7"><?= $statusCount[3] ?></span>
    <span class="lbl"><?= __('unknown_status') ?></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>

<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><?= htmlspecialchars($industryName) ?></td></tr>
  <tr><td><strong>👥 <?= __('organisation_size') ?></strong></td><td><?= htmlspecialchars($sizeName) ?></td></tr>
  <tr><td><strong>📅 <?= __('assessment_date_label') ?></strong></td><td><?= $dateF ?> at <?= $timeF ?></td></tr>
  <tr><td><strong>📋 <?= __('report_reference') ?></strong></td><td><?= $reportRef ?></td></tr>
  <tr><td><strong>⚠️ <?= __('risk_score_colon') ?></strong></td>
      <td style="color:<?= $riskColor ?>;font-weight:700"><?= $riskPercent ?>% – <?= $riskLevel ?></td></tr>
  <tr><td><strong>✅ <?= __('compliance_level_colon') ?></strong></td>
      <td style="color:<?= $compColor ?>;font-weight:700"><?= $compliancePercent ?>%</td></tr>
  <tr><td><strong>👤 <?= __('assessed_by') ?></strong></td><td>Christopher Khayere</td></tr>
  <tr><td><strong>⚖️ <?= __('framework') ?></strong></td><td><?= __('framework_full') ?></td></tr>
</table>
</div>

<!-- ===================== COMPLIANCE BY CATEGORY ===================== -->
<div class="pb">
<h2 class="sec">📈 2. <?= __('compliance_by_category') ?></h2>
<p><?= __('compliance_by_category_desc') ?></p>

<table>
  <tr>
    <th><?= __('category') ?></th>
    <th width="60" style="text-align:center"><?= __('questions_header') ?></th>
    <th width="50" style="text-align:center"><?= __('failed_header') ?></th>
    <th width="120"><?= __('compliance_bar') ?></th>
    <th width="70" style="text-align:center"><?= __('risk_percent') ?></th>
    <th width="120" style="text-align:center"><?= __('status_header') ?></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_cat');     $cBg = '#d1fae5'; $cColor = '#065f46'; $barColor = '#22c55e'; }
    elseif  ($catRisk <= 40) { $cStatus = '⚠️ '.__('partial_cat');       $cBg = '#fef3c7'; $cColor = '#92400e'; $barColor = '#eab308'; }
    elseif  ($catRisk <= 60) { $cStatus = '🔶 '.__('non_compliant_cat'); $cBg = '#ffedd5'; $cColor = '#9a3412'; $barColor = '#f97316'; }
    elseif  ($catRisk <= 80) { $cStatus = '🚨 '.__('very_high_risk_cat'); $cBg = '#fee2e2'; $cColor = '#991b1b'; $barColor = '#ef4444'; }
    else                      { $cStatus = '⛔ '.__('critical_cat');      $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 style="text-align:center;color:#dc2626;font-weight:700"><?= $cs['failed'] ?></td>
    <td>
      <div class="pbar-wrap">
        <div class="pbar-fill" style="width:<?= $catComp ?>%;background:<?= $barColor ?>"></div>
      </div>
      <small style="color:#6b7280"><?= $catComp ?>%</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>

<?php if (!empty($failedCategories)): ?>
<div class="penalty-box">
  <h4>⚠️ <?= __('categories_requiring_attention') ?></h4>
  <p style="margin:4px 0;font-size:9.5pt">
    <?= __('categories_significant_gaps') ?>
    <strong><?= implode(', ', $failedCategories) ?></strong>.
    <?= __('prioritized_remediation') ?>
  </p>
</div>
<?php endif; ?>

<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') ?>
</p>
</div>

<!-- ===================== DETAILED FINDINGS ===================== -->
<div class="pb">
<h2 class="sec">📝 3. <?= __('detailed_findings') ?></h2>
<p><?= __('detailed_findings_desc') ?></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';
    $riskLabels = ['Compliant'=>'Low (0/3)','Partial'=>'Medium (1/3)','Non-Compliant'=>'High (2/3)','Unknown'=>'Critical (3/3)'];
    $riskTxt = $riskLabels[$r['risk_label']] ?? ($r['score'].'/3');
    $optLabels = ['Yes'=>'✅ Yes','Partially'=>'⚠️ Partially','No'=>'❌ No',"I Don't Know"=>'❓ Unknown'];
    $rEmoji = $optLabels[$r['answer']] ?? $r['answer'];
  ?>
  <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 ?>"><?= $rEmoji ?></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 ===================== -->
<?php if ($websiteScan): ?>
<div class="pb">
<h2 class="sec">🌐 4. <?= __('website_compliance_scan') ?> – <?= htmlspecialchars($companyWebsite ?: 'N/A') ?></h2>
<p><?= __('website_scan_desc') ?> <strong><?= htmlspecialchars($companyWebsite) ?></strong> <?= __('on_date') ?> <?= $dateF ?> at <?= $timeF ?>. <?= __('scan_evaluates') ?></p>

<?php if (!$websiteScan['reachable']): ?>
<div class="web-finding wf-high">
  <strong>⚠️ <?= $websiteScan['https'] === false ? __('http_only') : __('no_https') ?>:</strong> <?= htmlspecialchars($companyWebsite) ?> <?= __('website_unreachable_warning') ?>
</div>
<?php else: ?>

<?php
$wr = $websiteScan['web_risk_percent'] ?? 0;
$wrColor = $wr <= 20 ? '#22c55e' : ($wr <= 50 ? '#eab308' : '#ef4444');
$wrLabel = $wr <= 20 ? '✅ '.__('good_label') : ($wr <= 50 ? '⚠️ '.__('needs_work') : '🔴 '.__('critical_label_web'));
?>
<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: <?= $websiteScan['ssl_valid'] ? '✅ Yes' : '❌ No' ?> &nbsp;|&nbsp;
         Cookies: <?= $websiteScan['cookie_count'] ?> &nbsp;|&nbsp;
         Forms: <?= $websiteScan['forms_count'] ?></small>
</div>

<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') ?></strong></td>
      <td><?= $websiteScan['https'] ? '<span class="badge b-pass">✅ '.__('active').'</span>' : '<span class="badge b-fail">❌ '.__('not_found').'</span>' ?></td>
      <td><?= __('critical_encrypt') ?></td><td>Section 41</td></tr>
  <tr><td><strong><?= __('ssl_cert') ?></strong></td>
      <td><?= $websiteScan['ssl_valid'] ? '<span class="badge b-pass">✅ '.__('valid').'</span>' : '<span class="badge b-fail">❌ '.__('invalid_expired').'</span>' ?></td>
      <td><?= __('critical_ssl') ?></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_display') ?></td><td>Section 29</td></tr>
  <tr><td><strong><?= __('cookie_consent_mech') ?></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_non_essential') ?></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_optin') ?></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_count').'</span>' : '<span class="badge b-pass">✅ '.__('none').'</span>' ?></td>
      <td><?= __('point_of_collection') ?></td><td>Section 29</td></tr>
  <tr><td><strong><?= __('kenya_dpa_ref') ?></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') ?></td><td>Section 29</td></tr>
</table>

<h3 class="sub">🔒 <?= __('http_security_headers') ?></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>

<?php if (!empty($websiteScan['findings'])): ?>
<h3 class="sub">⚠️ <?= __('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; ?>

<?php if (!empty($websiteScan['positives'])): ?>
<h3 class="sub">✅ <?= __('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; ?>
</div>
<?php endif; ?>

<!-- ===================== RECOMMENDATIONS ===================== -->
<div class="pb">
<h2 class="sec">🎯 5. <?= __('prioritised_recommendations') ?></h2>
<p><?= __('action_plan_desc') ?> <strong><?= __('failure_warning') ?> <?= htmlspecialchars($companyName) ?> <?= __('penalties_up_to') ?></strong></p>

<?php
$pConfig = [
  'immediate'   => ['label' => '🔴 '.__('immediate_label'),  'cls' => 'pri-immediate', 'badge' => __('immediate_badge')],
  'short-term'  => ['label' => '🟠 '.__('short_term_label'),  'cls' => 'pri-short-term', 'badge' => __('short_term_badge')],
  'medium-term' => ['label' => '🔵 '.__('medium_term_label'), 'cls' => 'pri-medium-term', 'badge' => __('medium_term_badge')],
  'long-term'   => ['label' => '🟢 '.__('long_term_label'), 'cls' => 'pri-long-term', 'badge' => __('long_term_badge')],
];
foreach ($pConfig as $pKey => $pCfg):
  if (empty($pGroups[$pKey])) continue;
?>
<h3 class="sub"><?= $pCfg['label'] ?></h3>
<?php foreach ($pGroups[$pKey] as $rec):
  $recText = ($lang === 'sw' && !empty($rec['recommendation_sw'])) ? $rec['recommendation_sw'] : $rec['recommendation'];
?>
<div class="rec-card">
  <span class="pri-badge <?= $pCfg['cls'] ?>"><?= $pCfg['badge'] ?></span>
  <?php if (!empty($rec['category'])): ?>
  <span style="font-size:8pt;color:#6b7280;margin-left:8px">[<?= htmlspecialchars($rec['category']) ?>]</span>
  <?php endif; ?>
  <strong><?= htmlspecialchars($recText) ?></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; ?>

<?php if (empty($pGroups['immediate']) && empty($pGroups['short-term']) && empty($pGroups['medium-term']) && empty($pGroups['long-term'])): ?>
<div class="exec-insight">
  <h4>✅ <?= __('no_recommendations') ?></h4>
  <p style="margin:0"><?= __('all_compliant_recs') ?></p>
</div>
<?php endif; ?>
</div>

<!-- ===================== LEGAL PENALTIES ===================== -->
<div class="pb">
<h2 class="sec">⚖️ 6. <?= __('legal_penalties_title') ?></h2>
<p><?= __('legal_penalties_desc') ?></p>

<table>
  <tr><th><?= __('offence') ?></th><th><?= __('penalty') ?></th><th><?= __('section') ?></th><th><?= __('type') ?></th></tr>
  <tr><td><?= __('general_violations') ?></td><td style="color:#b91c1c;font-weight:700"><?= __('general_penalty') ?></td><td>Section 64</td><td><?= __('civil_admin') ?></td></tr>
  <tr><td><?= __('unlawful_processing') ?></td><td style="color:#b91c1c;font-weight:700"><?= __('unlawful_penalty') ?></td><td>Section 65</td><td><?= __('criminal') ?></td></tr>
  <tr><td><?= __('failure_register') ?></td><td style="color:#b91c1c;font-weight:700"><?= __('register_penalty') ?></td><td>Section 18(5)</td><td><?= __('administrative') ?></td></tr>
  <tr><td><?= __('failure_notify') ?></td><td style="color:#b91c1c;font-weight:700"><?= __('notify_penalty') ?></td><td>Section 43(3)</td><td><?= __('administrative') ?></td></tr>
  <tr><td><?= __('obstruction') ?></td><td style="color:#b91c1c;font-weight:700"><?= __('obstruction_penalty') ?></td><td>Section 67</td><td><?= __('criminal') ?></td></tr>
  <tr><td><?= __('unlawful_transfer') ?></td><td style="color:#b91c1c;font-weight:700"><?= __('transfer_penalty') ?></td><td>Section 48-49</td><td><?= __('administrative') ?></td></tr>
  <tr><td><?= __('civil_compensation') ?></td><td style="color:#b91c1c;font-weight:700"><?= __('compensation_penalty') ?></td><td>Section 62</td><td><?= __('civil') ?></td></tr>
</table>

<div class="penalty-box">
  <h4>⚠️ <?= __('important_legal_notice') ?> <?= htmlspecialchars($companyName) ?></h4>
  <p style="margin:0"><?= __('based_on_assessment') ?> (<?= $riskLevel ?> – <?= $riskPercent ?>% risk),
  <strong><?= htmlspecialchars($companyName) ?></strong> <?= __('could_face_action') ?>
  <strong style="color:#b91c1c">KES 5,000,000</strong> <?= __('for_identified_areas') ?>
  <?= __('immediate_remediation') ?> <?= __('present_to_board') ?></p>
</div>
</div>

<!-- ===================== INDUSTRY-SPECIFIC NOTES ===================== -->
<?php if ($industryTemplate): ?>
<div class="pb">
<h2 class="sec">🏭 7. <?= __('industry_specific_notes') ?></h2>
<?= $industryTemplate['template_content'] ?>
</div>
<?php endif; ?>

<!-- ===================== GLOSSARY ===================== -->
<div class="pb">
<h2 class="sec">📚 <?= $industryTemplate ? '8' : '7' ?>. <?= __('glossary_title') ?></h2>

<div class="glossary-term"><?= __('glossary_dpa') ?></div>
<div class="glossary-def"><?= __('glossary_dpa_def') ?></div>

<div class="glossary-term"><?= __('glossary_odpc') ?></div>
<div class="glossary-def"><?= __('glossary_odpc_def') ?></div>

<div class="glossary-term"><?= __('glossary_personal_data') ?></div>
<div class="glossary-def"><?= __('glossary_personal_data_def') ?></div>

<div class="glossary-term"><?= __('glossary_data_subject') ?></div>
<div class="glossary-def"><?= __('glossary_data_subject_def') ?></div>

<div class="glossary-term"><?= __('glossary_controller') ?></div>
<div class="glossary-def"><?= __('glossary_controller_def') ?></div>

<div class="glossary-term"><?= __('glossary_processor') ?></div>
<div class="glossary-def"><?= __('glossary_processor_def') ?></div>

<div class="glossary-term"><?= __('glossary_dpa_contract') ?></div>
<div class="glossary-def"><?= __('glossary_dpa_contract_def') ?></div>

<div class="glossary-term"><?= __('glossary_dpia') ?></div>
<div class="glossary-def"><?= __('glossary_dpia_def') ?></div>

<div class="glossary-term"><?= __('glossary_ropa') ?></div>
<div class="glossary-def"><?= __('glossary_ropa_def') ?></div>

<div class="glossary-term"><?= __('glossary_dpo') ?></div>
<div class="glossary-def"><?= __('glossary_dpo_def') ?></div>

<div class="glossary-term"><?= __('glossary_sensitive') ?></div>
<div class="glossary-def"><?= __('glossary_sensitive_def') ?></div>

<div class="glossary-term"><?= __('glossary_consent') ?></div>
<div class="glossary-def"><?= __('glossary_consent_def') ?></div>

<div class="glossary-term"><?= __('glossary_cross_border') ?></div>
<div class="glossary-def"><?= __('glossary_cross_border_def') ?></div>

<div class="glossary-term"><?= __('glossary_breach') ?></div>
<div class="glossary-def"><?= __('glossary_breach_def') ?></div>

<div class="glossary-term"><?= __('glossary_sccs') ?></div>
<div class="glossary-def"><?= __('glossary_sccs_def') ?></div>
</div>

<!-- ===================== SIGNATURES WITH QR CODE ===================== -->
<div class="pb">
<h2 class="sec">✅ <?= $industryTemplate ? '9' : '8' ?>. <?= __('signatures_title') ?></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"><?= __('dpo_ceo') ?></p>
    <div class="sig-line"><?= __('signature_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_label') ?>:</p>
    <p style="font-weight:700;font-size:11pt">Christopher Khayere</p>
    <p style="font-size:9.5pt"><strong><?= __('certified_dpo') ?></strong></p>
    <div class="sig-line"><?= __('digitally_signed') ?> – <?= $dateF ?></div>
  </div>
</div>

<div class="qr-section">
  <h3 style="margin-bottom:12px">🔐 <?= __('report_authenticity') ?></h3>
  <p style="font-size:10pt"><?= __('report_registered_under') ?> <strong><?= $reportRef ?></strong>. <?= __('verify_by_scanning') ?></p>
  <p style="color:#3b82f6;font-size:10pt;font-weight:600;word-break:break-all;margin:10px 0"><?= $verifyUrl ?></p>
  <img src="<?= $qrUrl ?>" alt="QR Code" style="width:180px;height:180px;border:1px solid #e2e8f0;border-radius:8px;margin-top:12px">
  <p style="font-size:8.5pt;color:#6b7280;margin-top:8px">
    <?= __('scan_to_verify') ?>
  </p>
  <p style="font-size:8pt;margin-top:12px;color:#9ca3af">
    <em><?= __('report_reference') ?>: <?= $reportRef ?> | <?= __('generated') ?>: <?= $dateF ?> | <?= $timeF ?> | <?= __('framework_label') ?>: <?= __('kenya_dpa_short') ?></em>
  </p>
</div>

<div class="footer">
  <p><strong><?= __('disclaimer') ?> <?= $dateF ?>. <?= __('disclaimer_2') ?></strong></p>
  <p style="margin-top:6px"><?= __('report_reference') ?>: <?= $reportRef ?> | <?= $dateF ?> | <?= __('kenya_dpa_short') ?> | <?= __('odpc_kenya') ?></p>
</div>
</div>

</body>
</html>
<?php
    return ob_get_clean();
}
// ============================================================
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>" data-theme="<?= $theme ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= __('page_title') ?> | AI Security Platform</title>
<style>
  :root {
    --bg-primary: #0a0a0f;
    --bg-secondary: #13131a;
    --bg-card: rgba(255,255,255,0.025);
    --bg-input: rgba(0,0,0,0.35);
    --text-primary: #e4e4e7;
    --text-secondary: #a1a1aa;
    --text-muted: #71717a;
    --text-dim: #52525b;
    --border: rgba(255,255,255,0.07);
    --border-hover: rgba(255,255,255,0.15);
    --accent: #06b6d4;
    --accent-light: #67e8f9;
    --accent-bg: rgba(6,182,212,0.06);
    --accent-border: rgba(6,182,212,0.15);
    --gradient: linear-gradient(135deg,#06b6d4,#14b8a6);
    --shadow: 0 4px 20px rgba(0,0,0,0.4);
    --navbar-bg: #13131a;
  }

  [data-theme="light"] {
    --bg-primary: #f8fafc;
    --bg-secondary: #ffffff;
    --bg-card: rgba(0,0,0,0.02);
    --bg-input: #ffffff;
    --text-primary: #1a1a2e;
    --text-secondary: #4b5563;
    --text-muted: #6b7280;
    --text-dim: #9ca3af;
    --border: rgba(0,0,0,0.08);
    --border-hover: rgba(0,0,0,0.15);
    --accent: #0891b2;
    --accent-light: #06b6d4;
    --accent-bg: rgba(8,145,178,0.06);
    --accent-border: rgba(8,145,178,0.2);
    --gradient: linear-gradient(135deg,#0891b2,#059669);
    --shadow: 0 2px 12px rgba(0,0,0,0.08);
    --navbar-bg: #ffffff;
  }

  *{margin:0;padding:0;box-sizing:border-box}
  body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:var(--bg-primary);color:var(--text-primary);min-height:100vh;transition:background .3s,color .3s}
  .container{max-width:1020px;margin:0 auto;padding:20px}

  .navbar{background:var(--navbar-bg);border:1px solid var(--border);border-radius:12px;padding:15px 22px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px;margin-bottom:22px;box-shadow:var(--shadow)}
  .navbar h1{font-size:17px;background:var(--gradient);-webkit-background-clip:text;-webkit-text-fill-color:transparent;font-weight:700}
  .nav-links{display:flex;gap:6px;flex-wrap:wrap;align-items:center}
  .nav-links a,.nav-links button{color:var(--text-secondary);text-decoration:none;padding:6px 12px;border:1px solid var(--border);border-radius:6px;font-size:11px;transition:all .2s;background:transparent;cursor:pointer}
  .nav-links a:hover,.nav-links button:hover,.nav-links a.active{background:var(--accent-bg);border-color:var(--accent);color:var(--accent)}
  .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)}

  .toggle-group{display:flex;gap:4px;align-items:center;margin-left:8px}
  .toggle-btn{padding:4px 8px;border:1px solid var(--border);border-radius:4px;background:transparent;color:var(--text-secondary);cursor:pointer;font-size:10px;transition:all .2s}
  .toggle-btn.active{background:var(--accent-bg);border-color:var(--accent);color:var(--accent)}

  .card{background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;margin-bottom:18px}
  .card h3{color:var(--accent);font-size:15px;margin-bottom:16px;padding-bottom:10px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:8px}

  .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:var(--text-muted);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:var(--bg-input);border:1px solid var(--border);border-radius:8px;color:var(--text-primary);font-size:13px;transition:border-color .2s}
  .form-group input:focus,.form-group select:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px rgba(6,182,212,0.1)}
  .form-group small{color:var(--text-dim);font-size:10px;margin-top:3px;display:block}

  .sticky-progress{position:sticky;top:0;z-index:100;background:var(--navbar-bg);border:1px solid var(--border);border-radius:10px;padding:14px 20px;margin-bottom:18px;display:flex;align-items:center;gap:16px;flex-wrap:wrap;box-shadow:var(--shadow)}
  .prog-bar-wrap{flex:1;min-width:160px;background:var(--bg-card);border-radius:20px;height:10px;overflow:hidden}
  .prog-bar-fill{height:100%;background:var(--gradient);border-radius:20px;transition:width .3s}
  .prog-text{font-size:12px;color:var(--text-secondary);white-space:nowrap}
  .prog-pct{font-size:14px;font-weight:700;color:var(--accent);white-space:nowrap}

  .scan-banner{background:var(--accent-bg);border:1px solid var(--accent-border);border-radius:8px;padding:10px 16px;font-size:12px;color:var(--accent-light);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:var(--accent);border-radius:50%;animation:spin .6s linear infinite;flex-shrink:0}
  @keyframes spin{to{transform:rotate(360deg)}}

  .scan-results{background:var(--bg-input);border:1px solid var(--border);border-radius:10px;padding:16px;margin-bottom:16px;display:none}
  .scan-results.show{display:block}
  .scan-results h4{color:var(--accent);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}

  .category-header{background:var(--accent-bg);border:1px solid var(--accent-border);border-radius:8px;padding:12px 16px;margin-bottom:4px;display:flex;justify-content:space-between;align-items:center}
  .category-header h3{color:var(--accent-light);font-size:14px;margin:0;border-bottom:none;padding-bottom:0}
  .category-count{font-size:11px;color:var(--text-dim);background:var(--bg-card);padding:3px 10px;border-radius:10px}

  .q-block{padding:14px 16px;background:var(--bg-input);border-radius:8px;border-left:3px solid var(--accent-border);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:var(--accent);text-transform:uppercase;letter-spacing:.8px;font-weight:600}
  .q-ref{font-size:9px;color:var(--text-dim)}
  .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:var(--bg-card);border:1px solid var(--border);border-radius:6px;cursor:pointer;text-align:center;transition:all .2s;font-size:11.5px;line-height:1.3}
  .opt label:hover{background:var(--accent-bg);border-color:var(--accent-border)}
  .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}

  .btn-submit{background:var(--gradient);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-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-download{background:#06b6d4;color:#fff;border:none;padding:11px 22px;border-radius:8px;font-weight:700;cursor:pointer;margin:6px;font-size:13px}
  .btn-new{background:var(--bg-card);color:var(--text-primary);border:1px solid var(--border);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!important;color:#1a1a2e!important}
    .navbar,.sticky-progress,.scan-banner,.scan-results,.btn-submit,.btn-print,.btn-download,.btn-new,.card:not(.report-card),.nav-links{display:none!important}
    .report-wrap{max-height:none;overflow:visible;padding:0;border-radius:0}
    .container{max-width:100%;padding:0}
  }
</style>
</head>
<body>
<div class="container">

  <nav class="navbar">
    <h1>🛡️ DPA Kenya Compliance</h1>
    <div class="nav-links">
      <a href="dashboard.php"><?= __('nav_dashboard') ?></a>
      <a href="dpa.php" class="active"><?= __('nav_assessments') ?></a>
      <a href="help.php"><?= __('nav_help') ?></a>
      
      <div class="toggle-group">
        <button class="toggle-btn <?= $theme === 'dark' ? 'active' : '' ?>" onclick="setTheme('dark')" title="Dark Mode">🌙</button>
        <button class="toggle-btn <?= $theme === 'light' ? 'active' : '' ?>" onclick="setTheme('light')" title="Light Mode">☀️</button>
      </div>
      
      <div class="toggle-group">
        <button class="toggle-btn <?= $lang === 'en' ? 'active' : '' ?>" onclick="setLang('en')" title="English">EN</button>
        <button class="toggle-btn <?= $lang === 'sw' ? 'active' : '' ?>" onclick="setLang('sw')" title="Kiswahili">SW</button>
      </div>
      
      <a href="logout.php" class="logout"><?= __('nav_logout') ?></a>
    </div>
  </nav>

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

  <div class="scan-banner" id="scanBanner">
    <div class="spinner" id="scanSpinner"></div>
    <span id="scanMsg"><?= __('scanning_msg') ?>…</span>
  </div>

  <div class="scan-results card" id="scanResults">
    <h4>🌐 <?= __('live_website_scan') ?></h4>
    <div class="scan-grid" id="scanChips"></div>
    <div class="scan-findings" id="scanFindings"></div>
  </div>

  <div class="card">
    <h3>🏢 <?= __('org_details') ?></h3>
    <form method="POST" id="dpaForm" onsubmit="return beforeSubmit()">
      <div class="form-row">
        <div class="form-group">
          <label><?= __('company_name') ?></label>
          <input type="text" name="company_name" id="company_name" placeholder="<?= __('company_name_placeholder') ?>" required autocomplete="organization">
        </div>
        <div class="form-group">
          <label><?= __('company_website') ?></label>
          <input type="text" name="company_website" id="company_website" placeholder="<?= __('company_website_placeholder') ?>" autocomplete="url">
          <small><?= __('website_hint') ?></small>
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label><?= __('company_industry') ?></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><?= __('company_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>

  <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) ?> <?= __('progress_questions') ?></span>
    <span style="font-size:11px;color:var(--text-dim)">|</span>
    <span class="prog-text" id="scanStatusInline"></span>
  </div>

  <?php foreach ($categories as $cat => $qs): ?>
  <div class="card">
    <div class="category-header">
      <h3><?= ($lang === 'sw' && !empty($qs[0]['category_sw'])) ? htmlspecialchars($qs[0]['category_sw']) : htmlspecialchars($cat) ?></h3>
      <span class="category-count"><?= count($qs) ?> <?= __('category_questions') ?></span>
    </div>
    <?php foreach ($qs as $q): 
      $qText = ($lang === 'sw' && !empty($q['question_sw'])) ? $q['question_sw'] : $q['question'];
      $gText = ($lang === 'sw' && !empty($q['guidance_sw'])) ? $q['guidance_sw'] : $q['guidance'];
    ?>
    <div class="q-block" id="qblock_<?= $q['id'] ?>">
      <div class="q-meta">
        <span class="q-num">Q<?= $q['sort_order'] ?> · <?= ($lang === 'sw' && !empty($q['category_sw'])) ? htmlspecialchars($q['category_sw']) : htmlspecialchars($q['category']) ?></span>
        <span class="q-ref">📜 <?= htmlspecialchars($q['kenya_dpa_reference']) ?></span>
        <?php if ($q['is_critical']): ?>
        <span style="font-size:8px;color:#ef4444;font-weight:700"><?= __('critical_label') ?></span>
        <?php endif; ?>
      </div>
      <div class="q-text"><?= htmlspecialchars($qText) ?></div>
      <?php if (!empty($gText)): ?>
      <div class="q-guidance">💡 <?= htmlspecialchars($gText) ?></div>
      <?php endif; ?>
      <div class="options">
        <?php 
        $optMap = ['Yes' => 'yes', 'Partially' => 'partial', 'No' => 'no', "I Don't Know" => 'dontknow'];
        $emojiMap = ['Yes' => '✅ '.__('question_yes'), 'Partially' => '⚠️ '.__('question_partially'), 'No' => '❌ '.__('question_no'), "I Don't Know" => '❓ '.__('question_unknown')];
        foreach ($optMap as $opt => $css):
          $oid = 'q_' . $q['id'] . '_' . preg_replace('/[^a-zA-Z0-9]/', '_', $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 ?>"><?= $emojiMap[$opt] ?></label>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endforeach; ?>

      <button type="submit" name="submit_dpa" class="btn-submit" id="submitBtn" disabled>
        📊 <?= __('generate_report') ?>
      </button>
    </form>

<?php else: ?>

  <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_score') ?></span>
    </div>
    <p style="font-size:20px;font-weight:700;color:<?= $riskColor ?>;margin-bottom:6px">
      <?= htmlspecialchars($riskLevel) ?>
    </p>
    <p style="color:var(--text-secondary);margin-bottom:16px">
      <?= __('compliance') ?>: <strong style="color:#22c55e"><?= $compliancePercent ?>%</strong> &nbsp;|&nbsp;
      <?= __('report_ref') ?>: <strong style="color:var(--accent)"><?= $reportRef ?></strong>
    </p>
    <button onclick="window.print()" class="btn-print">🖨️ <?= __('print_save') ?></button>
    <button onclick="downloadCleanReport()" class="btn-download">📥 <?= __('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>

<script>
function setTheme(theme) {
    const url = new URL(window.location);
    url.searchParams.set('theme', theme);
    window.location = url.toString();
}

function setLang(lang) {
    const url = new URL(window.location);
    url.searchParams.set('lang', lang);
    window.location = url.toString();
}

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 + ' <?= __("progress_questions") ?>';
  document.getElementById('submitBtn').disabled = (answered < TOTAL);
}

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_msg") ?> ' + domain + ' <?= __("for_dpa_indicators") ?>';
  inline.textContent = '🔍 <?= __("scan_status_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_status_failed") ?>: ' + err.message;
    inline.textContent = '⚠️ <?= __("scan_status_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 + ' <?= __("scan_unreachable_msg") ?>';
    inline.textContent = '⚠️ <?= __("scan_status_unreachable") ?>';
    setTimeout(() => banner.classList.remove('show'), 6000);
    return;
  }

  const wr = data.web_risk_percent || 0;
  const wrLabel = wr <= 20 ? '✅ <?= __("good_label") ?>' : (wr <= 50 ? '⚠️ <?= __("needs_work") ?>' : '🔴 <?= __("critical_label_web") ?>');
  banner.className = 'scan-banner show done';
  document.getElementById('scanMsg').textContent = '✅ <?= __("scan_status_done") ?> ' + data.domain + ' – Risk: ' + wr + '% (' + wrLabel + ')';
  inline.textContent = '✅ <?= __("scan_status_done") ?> – Risk: ' + wr + '%';
  setTimeout(() => banner.classList.remove('show'), 8000);

  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.innerHTML = '';
  if (data.findings && data.findings.length) {
    const fTitle = document.createElement('p');
    fTitle.style.cssText = 'font-size:11px;color:var(--text-secondary);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:var(--text-secondary);margin:8px 0 4px';
    pTitle.textContent = '✅ <?= __("compliance_positives_label") ?>';
    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('<?= __("submit_warning") ?>');
  }
  return true;
}

function downloadCleanReport() {
  const reportEl = document.getElementById('reportPreview');
  if (!reportEl) return;
  const cleanHTML = reportEl.innerHTML;
  const fullHTML = '<!DOCTYPE html><html lang="<?= $lang ?>"><head><meta charset="UTF-8"><title>DPA Report – <?= addslashes($reportRef ?? '') ?></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;padding:30px}.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 ?>}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}.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}.rec-card{border-left:4px solid <?= $riskColor ?>;padding:10px 14px;margin:8px 0;background:#f8fafc;border-radius:0 6px 6px 0}.penalty-box{background:#fef2f2;border:2px solid #fecaca;border-radius:8px;padding:16px 20px;margin:18px 0}.footer{text-align:center;font-size:8pt;color:#9ca3af;margin-top:30px;padding-top:12px;border-top:1px solid #e2e8f0}@media print{body{padding:0}}</style></head><body>' + cleanHTML + '</body></html>';
  const blob = new Blob([fullHTML], { type: 'text/html;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'DPA_Report_<?= addslashes($reportRef ?? 'assessment') ?>.html';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}
</script>
</body>
</html>