<?php
/**
 * dpia-automation.php - Data Protection Impact Assessment with Report Generation
 * Fixed: activity_name NOT NULL constraint
 */

require_once '../config.php';
requireLogin();

$userId = $_SESSION['user_id'];
$user = getUserById($userId);
$org = getUserOrganization($userId);
$organizationId = $org ? $org['id'] : null;

$pdo = getDBConnection();
$message = '';
$messageType = '';

// Check organization
if (!$organizationId) {
    echo '<!DOCTYPE html><html><head><title>Organization Required - Soul Guard</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>body{font-family:Inter,sans-serif;background:#f1f5f9;display:flex;justify-content:center;align-items:center;height:100vh;margin:0}.card{background:white;border-radius:16px;padding:40px;text-align:center;max-width:500px;box-shadow:0 4px 6px rgba(0,0,0,0.1)}.btn{display:inline-block;padding:12px 24px;background:#0f3b5c;color:white;text-decoration:none;border-radius:8px;margin-top:20px}i{font-size:48px;color:#f59e0b;margin-bottom:20px}</style>
    </head><body><div class="card"><i class="fas fa-building"></i><h2>Organization Required</h2><p>Set up your organization before conducting DPIAs.</p><a href="organization.php?create=1" class="btn">Create Organization</a></div></body></html>';
    exit;
}

// =============================================
// VIEW REPORT MODE
// =============================================
$viewReport = isset($_GET['report']) && !empty($_GET['report']);
$reportDpia = null;

if ($viewReport) {
    $reportId = $_GET['report'];
    try {
        $stmt = $pdo->prepare("SELECT * FROM dpia_records WHERE id = ? AND organization_id = ?");
        $stmt->execute([$reportId, $organizationId]);
        $reportDpia = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {}
    
    if ($reportDpia) {
        displayDpiaReport($reportDpia, $org, $user);
        exit;
    }
}

// =============================================
// HANDLE FORM SUBMISSIONS
// =============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create_dpia':
                try {
                    $reference = 'DPIA-' . date('Ymd') . '-' . rand(1000, 9999);
                    $projectName = trim($_POST['project_name']);
                    
                    if (empty($projectName)) {
                        throw new Exception('Project name is required.');
                    }
                    
                    $stmt = $pdo->prepare("
                        INSERT INTO dpia_records (
                            user_id, organization_id, activity_name, dpia_reference, project_name, 
                            project_description, processing_activity, retention_period,
                            third_party_sharing, risk_identification, risk_assessment,
                            mitigation_measures, risk_level, notes, status, created_at
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft', datetime('now'))
                    ");
                    
                    $stmt->execute([
                        $userId, $organizationId,
                        $projectName,
                        $reference, $projectName,
                        $_POST['project_description'] ?? null,
                        $_POST['processing_activity'] ?? '',
                        $_POST['retention_period'] ?? null,
                        isset($_POST['third_party_sharing']) ? 1 : 0,
                        $_POST['risk_identification'] ?? null,
                        $_POST['risk_assessment'] ?? null,
                        $_POST['mitigation_measures'] ?? null,
                        $_POST['risk_level'] ?? 'Medium',
                        $_POST['notes'] ?? null
                    ]);
                    
                    $newId = $pdo->lastInsertId();
                    $message = '✅ DPIA created successfully! Reference: ' . $reference;
                    
                    // Redirect to report
                    header("Location: dpia-automation.php?report={$newId}&msg=" . urlencode($message) . "&type=success");
                    exit;
                } catch (Exception $e) {
                    $message = '❌ Error: ' . $e->getMessage();
                    $messageType = 'error';
                }
                break;
                
            case 'update_dpia':
                try {
                    $projectName = trim($_POST['project_name']);
                    
                    if (empty($projectName)) {
                        throw new Exception('Project name is required.');
                    }
                    
                    $stmt = $pdo->prepare("
                        UPDATE dpia_records SET
                            activity_name = ?, project_name = ?, project_description = ?,
                            processing_activity = ?, retention_period = ?, third_party_sharing = ?,
                            risk_identification = ?, risk_assessment = ?, mitigation_measures = ?,
                            risk_level = ?, notes = ?
                        WHERE id = ? AND organization_id = ?
                    ");
                    
                    $stmt->execute([
                        $projectName, $projectName,
                        $_POST['project_description'] ?? null,
                        $_POST['processing_activity'] ?? '',
                        $_POST['retention_period'] ?? null,
                        isset($_POST['third_party_sharing']) ? 1 : 0,
                        $_POST['risk_identification'] ?? null,
                        $_POST['risk_assessment'] ?? null,
                        $_POST['mitigation_measures'] ?? null,
                        $_POST['risk_level'] ?? 'Medium',
                        $_POST['notes'] ?? null,
                        $_POST['dpia_id'], $organizationId
                    ]);
                    
                    $message = '✅ DPIA updated successfully!';
                    $messageType = 'success';
                } catch (Exception $e) {
                    $message = '❌ Error: ' . $e->getMessage();
                    $messageType = 'error';
                }
                break;
                
            case 'submit_review':
                try {
                    $stmt = $pdo->prepare("UPDATE dpia_records SET status = 'pending_review' WHERE id = ? AND organization_id = ?");
                    $stmt->execute([$_POST['dpia_id'], $organizationId]);
                    $message = '✅ DPIA submitted for review!';
                    $messageType = 'success';
                } catch (Exception $e) {
                    $message = '❌ Error: ' . $e->getMessage();
                    $messageType = 'error';
                }
                break;
                
            case 'approve_dpia':
                try {
                    $stmt = $pdo->prepare("UPDATE dpia_records SET status = 'approved', approved_by = ?, approval_date = datetime('now'), completed_at = datetime('now') WHERE id = ? AND organization_id = ?");
                    $stmt->execute([$userId, $_POST['dpia_id'], $organizationId]);
                    $message = '✅ DPIA approved!';
                    $messageType = 'success';
                } catch (Exception $e) {
                    $message = '❌ Error: ' . $e->getMessage();
                    $messageType = 'error';
                }
                break;
                
            case 'delete_dpia':
                try {
                    $stmt = $pdo->prepare("DELETE FROM dpia_records WHERE id = ? AND organization_id = ?");
                    $stmt->execute([$_POST['dpia_id'], $organizationId]);
                    $message = '✅ DPIA deleted!';
                    $messageType = 'success';
                } catch (Exception $e) {
                    $message = '❌ Error: ' . $e->getMessage();
                    $messageType = 'error';
                }
                break;
        }
        
        if (!isset($newId)) {
            header("Location: dpia-automation.php?msg=" . urlencode($message) . "&type=" . $messageType);
            exit;
        }
    }
}

if (isset($_GET['msg'])) {
    $message = $_GET['msg'];
    $messageType = $_GET['type'] ?? 'success';
}

// Fetch DPIAs
$dpiaRecords = [];
$pendingCount = $approvedCount = $draftCount = 0;
try {
    $stmt = $pdo->prepare("SELECT * FROM dpia_records WHERE organization_id = ? ORDER BY created_at DESC");
    $stmt->execute([$organizationId]);
    $dpiaRecords = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($dpiaRecords as $d) {
        if ($d['status'] === 'pending_review') $pendingCount++;
        if ($d['status'] === 'approved') $approvedCount++;
        if ($d['status'] === 'draft') $draftCount++;
    }
} catch (Exception $e) {}

$theme = getTheme();

// =============================================
// REPORT DISPLAY FUNCTION
// =============================================
function displayDpiaReport($dpia, $org, $user) {
    $reportDate = date('F j, Y');
    $reportRef = $dpia['dpia_reference'] ?? 'DPIA-' . $dpia['id'];
    $riskColor = $dpia['risk_level'] === 'High' ? '#ef4444' : ($dpia['risk_level'] === 'Medium' ? '#f59e0b' : '#10b981');
    $riskScore = (!empty($dpia['risk_identification']) ? 30 : 0) + (!empty($dpia['risk_assessment']) ? 30 : 0) + (!empty($dpia['mitigation_measures']) ? 40 : 0);
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>DPIA Report - <?php echo htmlspecialchars($reportRef); ?></title>
        <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <style>
            :root{--primary:#0f3b5c;--secondary:#2c7da0;--success:#10b981;--warning:#f59e0b;--danger:#ef4444;--dark:#1e293b;--gray:#64748b;--light:#f8fafc}
            *{margin:0;padding:0;box-sizing:border-box}
            body{font-family:'Inter',sans-serif;background:#f1f5f9;color:var(--dark);line-height:1.7;font-size:12px}
            @media print{body{background:white;font-size:11px}.no-print{display:none!important}}
            .report-container{max-width:900px;margin:20px auto;background:white;box-shadow:0 4px 20px rgba(0,0,0,0.1)}
            .cover-page{background:linear-gradient(135deg,var(--primary),#0a2538);color:white;padding:60px 50px;text-align:center;min-height:70vh;display:flex;flex-direction:column;justify-content:center;align-items:center;position:relative;overflow:hidden}
            .cover-page::before{content:'';position:absolute;top:-50%;right:-20%;width:400px;height:400px;background:radial-gradient(circle,rgba(255,255,255,0.05),transparent);border-radius:50%}
            .cover-page *{position:relative;z-index:1}
            .cover-logo{font-size:40px;margin-bottom:16px;font-weight:800}
            .cover-title{font-size:24px;font-weight:700;margin-bottom:8px}
            .cover-subtitle{font-size:14px;opacity:0.8;margin-bottom:30px}
            .cover-divider{width:80px;height:3px;background:var(--success);margin:0 auto 24px}
            .content-section{padding:30px}
            .content-section h2{font-size:16px;color:var(--primary);border-bottom:2px solid var(--secondary);padding-bottom:8px;margin-bottom:16px}
            .content-section h3{font-size:13px;color:var(--secondary);margin:16px 0 8px}
            .info-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px}
            .info-item{padding:12px;background:var(--light);border-radius:8px}
            .info-label{font-size:9px;color:var(--gray);text-transform:uppercase;letter-spacing:1px}
            .info-value{font-size:13px;font-weight:600;margin-top:2px}
            .finding-box{padding:16px;border-radius:8px;margin-bottom:12px;border-left:4px solid}
            .finding-risk{background:rgba(<?php echo $riskColor; ?>,0.05);border-color:<?php echo $riskColor; ?>}
            .finding-mitigation{background:rgba(16,185,129,0.05);border-color:#10b981}
            .score-display{text-align:center;padding:24px;margin:20px 0;border-radius:12px;background:rgba(255,255,255,0.1);border:1px solid rgba(255,255,255,0.2)}
            .score-big{font-size:48px;font-weight:800;color:white}
            .report-footer{background:var(--dark);color:white;padding:24px 30px;text-align:center;font-size:10px}
            .btn-group{display:flex;gap:10px;flex-wrap:wrap;padding:16px;justify-content:center;background:white;border-bottom:1px solid #e2e8f0;position:sticky;top:0;z-index:100}
            .btn{display:inline-flex;align-items:center;gap:6px;padding:10px 20px;border:none;border-radius:8px;font-weight:600;font-size:12px;cursor:pointer;text-decoration:none;font-family:inherit}
            .btn-primary{background:var(--primary);color:white}
            .btn-success{background:var(--success);color:white}
            .btn:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,0.15)}
            @media(max-width:768px){.info-grid{grid-template-columns:1fr}.cover-page{padding:30px 20px}}
        </style>
    </head>
    <body>
        <div class="btn-group no-print">
            <button class="btn btn-primary" onclick="window.print()"><i class="fas fa-print"></i> Print / Save as PDF</button>
            <button class="btn btn-success" onclick="window.location.href='dpia-automation.php'"><i class="fas fa-arrow-left"></i> Back</button>
            <a href="dashboard.php" class="btn" style="background:var(--secondary);color:white;"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
        </div>
        <div class="report-container">
            <div class="cover-page">
                <div class="cover-logo"><i class="fas fa-shield-alt"></i> Soul Guard</div>
                <div class="cover-divider"></div>
                <h1 class="cover-title">Data Protection Impact Assessment</h1>
                <p class="cover-subtitle">Kenya Data Protection Act, 2019 - Section 31</p>
                <div style="margin-top:24px"><p style="font-size:18px;font-weight:600"><?php echo htmlspecialchars($dpia['project_name']); ?></p><p style="font-size:12px;opacity:0.7">Ref: <?php echo htmlspecialchars($reportRef); ?></p><p style="font-size:12px;opacity:0.7"><?php echo htmlspecialchars($org['name']??'N/A'); ?></p></div>
                <div class="score-display" style="margin-top:30px"><div class="score-big"><?php echo $riskScore; ?>%</div><div style="font-size:12px;opacity:0.8">Risk Score</div><div style="font-size:14px;font-weight:600;margin-top:4px;color:<?php echo $riskColor; ?>"><?php echo $dpia['risk_level']; ?> Risk</div></div>
                <p style="font-size:12px;opacity:0.7;margin-top:40px"><?php echo $reportDate; ?></p>
                <p style="font-size:10px;opacity:0.6">Prepared by: Christopher Khayere | 0799874578</p>
            </div>
            <div class="content-section" style="page-break-before:always">
                <h2>1. DPIA Overview</h2>
                <div class="info-grid">
                    <div class="info-item"><div class="info-label">Project</div><div class="info-value"><?php echo htmlspecialchars($dpia['project_name']); ?></div></div>
                    <div class="info-item"><div class="info-label">Reference</div><div class="info-value"><?php echo htmlspecialchars($reportRef); ?></div></div>
                    <div class="info-item"><div class="info-label">Risk Level</div><div class="info-value" style="color:<?php echo $riskColor; ?>"><?php echo $dpia['risk_level']; ?></div></div>
                    <div class="info-item"><div class="info-label">Status</div><div class="info-value"><?php echo ucfirst(str_replace('_',' ',$dpia['status'])); ?></div></div>
                    <div class="info-item"><div class="info-label">Date</div><div class="info-value"><?php echo date('M j, Y', strtotime($dpia['created_at']??'now')); ?></div></div>
                    <div class="info-item"><div class="info-label">Retention</div><div class="info-value"><?php echo htmlspecialchars($dpia['retention_period']??'N/S'); ?></div></div>
                </div>
                <?php if(!empty($dpia['project_description'])): ?><h3>Description</h3><p><?php echo nl2br(htmlspecialchars($dpia['project_description'])); ?></p><?php endif; ?>
                <h3>Processing Activity</h3><p><?php echo nl2br(htmlspecialchars($dpia['processing_activity']??'N/S')); ?></p>
            </div>
            <div class="content-section" style="page-break-before:always">
                <h2>2. Risk Analysis</h2>
                <div class="finding-box finding-risk"><h3 style="margin-top:0">🔍 Identified Risks</h3><p><?php echo !empty($dpia['risk_identification'])?nl2br(htmlspecialchars($dpia['risk_identification'])):'<em>None specified</em>'; ?></p></div>
                <div class="finding-box finding-risk"><h3 style="margin-top:0">📊 Assessment</h3><p><?php echo !empty($dpia['risk_assessment'])?nl2br(htmlspecialchars($dpia['risk_assessment'])):'<em>None specified</em>'; ?></p></div>
                <div class="finding-box finding-mitigation"><h3 style="margin-top:0">🛡️ Mitigation</h3><p><?php echo !empty($dpia['mitigation_measures'])?nl2br(htmlspecialchars($dpia['mitigation_measures'])):'<em>None specified</em>'; ?></p></div>
            </div>
            <div class="content-section">
                <h2>3. Recommendations</h2>
                <div class="finding-box finding-mitigation"><p><?php echo $dpia['risk_level']==='High'?'<strong>⚠️ High Risk:</strong> Immediate mitigation required. Consider ODPC consultation.':($dpia['risk_level']==='Medium'?'<strong>📋 Medium Risk:</strong> Implement mitigation before processing. Monitor regularly.':'<strong>✅ Low Risk:</strong> Risks manageable. Continue monitoring.'); ?></p></div>
                <div style="margin-top:16px;padding:12px;background:var(--light);border-radius:8px;font-size:11px"><strong>📜 Legal:</strong> Kenya DPA 2019 Section 31<br><strong>⏰ Review:</strong> <?php echo date('F j, Y', strtotime('+12 months')); ?><br><strong>👤 By:</strong> <?php echo htmlspecialchars($user['full_name']??$user['username']); ?></div>
            </div>
            <div class="report-footer"><p><strong>Soul Guard</strong></p><p>DPIA Report per Kenya DPA 2019</p><p style="margin-top:8px">Ref: <?php echo htmlspecialchars($reportRef); ?> | <?php echo $reportDate; ?></p><p>Christopher Khayere | 0799874578</p><p style="margin-top:12px;font-size:9px;opacity:0.5">Disclaimer: Automated report. Review before ODPC submission.</p></div>
        </div>
        <div class="btn-group no-print" style="margin:20px 0 40px"><button class="btn btn-primary" onclick="window.print()"><i class="fas fa-print"></i> Print / PDF</button><button class="btn btn-success" onclick="window.location.href='dpia-automation.php'"><i class="fas fa-arrow-left"></i> Back</button></div>
    </body>
    </html>
    <?php
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DPIA Automation - Soul Guard</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root{--primary:#0f3b5c;--secondary:#2c7da0;--success:#10b981;--warning:#f59e0b;--danger:#ef4444;--gray:#64748b;--border-radius:16px}
        *{margin:0;padding:0;box-sizing:border-box}
        body{font-family:'Inter',sans-serif;background:#f1f5f9;color:#1e293b;line-height:1.5}
        body.dark{background:#0f172a;color:#e2e8f0}
        .navbar{background:linear-gradient(135deg,#082c44,var(--primary));padding:0 24px;position:sticky;top:0;z-index:100}
        .nav-container{max-width:1400px;margin:0 auto;display:flex;justify-content:space-between;align-items:center;min-height:60px}
        .logo{color:white;font-weight:800;font-size:18px;text-decoration:none}
        .nav-links{display:flex;gap:2px;align-items:center;flex-wrap:wrap}
        .nav-links a{color:rgba(255,255,255,0.85);text-decoration:none;padding:6px 12px;border-radius:8px;font-size:12px;transition:all 0.2s;white-space:nowrap}
        .nav-links a:hover,.nav-links a.active{background:rgba(255,255,255,0.2);color:white}
        .theme-toggle{background:rgba(255,255,255,0.2);border:2px solid rgba(255,255,255,0.3);border-radius:50%;width:36px;height:36px;cursor:pointer;font-size:16px;color:white;display:flex;align-items:center;justify-content:center}
        .container{max-width:1400px;margin:0 auto;padding:24px}
        .header{background:linear-gradient(135deg,var(--primary),var(--secondary));border-radius:var(--border-radius);padding:28px;margin-bottom:24px;color:white}
        .header h1{font-size:24px;margin-bottom:4px}
        .stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px}
        .stat-card{background:white;border-radius:14px;padding:20px;text-align:center;border:1px solid #e2e8f0}
        body.dark .stat-card{background:#1e293b;border-color:#334155}
        .stat-value{font-size:28px;font-weight:800}
        .stat-label{font-size:11px;color:var(--gray);margin-top:4px}
        .dpia-card{background:white;border-radius:var(--border-radius);margin-bottom:16px;border:1px solid #e2e8f0;overflow:hidden}
        body.dark .dpia-card{background:#1e293b;border-color:#334155}
        .dpia-header{padding:16px 20px;border-bottom:1px solid #e2e8f0;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px;cursor:pointer}
        body.dark .dpia-header{border-bottom-color:#334155}
        .dpia-body{padding:20px;display:none}
        .status-badge{padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
        .status-approved{background:rgba(16,185,129,0.12);color:#10b981}
        .status-pending_review{background:rgba(245,158,11,0.12);color:#f59e0b}
        .status-draft{background:rgba(100,116,139,0.12);color:#64748b}
        .risk-badge{padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
        .risk-High{background:rgba(239,68,68,0.12);color:#ef4444}
        .risk-Medium{background:rgba(245,158,11,0.12);color:#f59e0b}
        .risk-Low{background:rgba(16,185,129,0.12);color:#10b981}
        .btn{display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;font-weight:500;font-size:12px;border:none;cursor:pointer;transition:all 0.2s;text-decoration:none;font-family:inherit;white-space:nowrap}
        .btn:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,0.15)}
        .btn-primary{background:var(--primary);color:white}
        .btn-success{background:var(--success);color:white}
        .btn-danger{background:var(--danger);color:white}
        .btn-report{background:#8b5cf6;color:white}
        .btn-outline{background:transparent;border:2px solid var(--secondary);color:var(--secondary)}
        .btn-outline:hover{background:var(--secondary);color:white}
        .btn-sm{padding:5px 10px;font-size:11px}
        .btn-white{background:rgba(255,255,255,0.2);color:white}
        .modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);z-index:1000;justify-content:center;align-items:center;backdrop-filter:blur(5px)}
        .modal-content{background:white;border-radius:var(--border-radius);max-width:750px;width:90%;max-height:85vh;overflow-y:auto}
        body.dark .modal-content{background:#1e293b}
        .modal-header{padding:18px 24px;border-bottom:1px solid #e2e8f0;display:flex;justify-content:space-between;align-items:center;background:var(--primary);color:white;border-radius:var(--border-radius) var(--border-radius) 0 0}
        .modal-body{padding:24px}
        .close{cursor:pointer;font-size:24px;color:white;opacity:0.8}
        .form-group{margin-bottom:16px}
        .form-group label{display:block;margin-bottom:6px;font-weight:500;font-size:13px}
        .form-group input,.form-group select,.form-group textarea{width:100%;padding:10px 14px;border:2px solid #e2e8f0;border-radius:8px;font-family:inherit;font-size:13px;background:white;color:var(--dark)}
        body.dark .form-group input,body.dark .form-group select,body.dark .form-group textarea{background:#0f172a;border-color:#334155;color:#e2e8f0}
        .form-group input:focus,.form-group select:focus,.form-group textarea:focus{outline:none;border-color:var(--secondary)}
        .form-row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
        .alert{padding:14px 20px;border-radius:12px;margin-bottom:20px;font-size:13px}
        .alert-success{background:rgba(16,185,129,0.1);border:1px solid rgba(16,185,129,0.3);color:#10b981}
        .alert-error{background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.3);color:#ef4444}
        .empty-state{text-align:center;padding:60px;background:white;border-radius:var(--border-radius)}
        body.dark .empty-state{background:#1e293b}
        @media(max-width:768px){.container{padding:12px}.stats-grid{grid-template-columns:repeat(2,1fr)}.form-row{grid-template-columns:1fr}}
    </style>
</head>
<body class="<?php echo $theme; ?>">
    <nav class="navbar"><div class="nav-container"><a href="dashboard.php" class="logo"><i class="fas fa-shield-alt"></i> Soul Guard</a><div class="nav-links"><a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a><a href="compliance-assessment.php"><i class="fas fa-clipboard-check"></i> Assessment</a><a href="dpia-automation.php" class="active"><i class="fas fa-file-alt"></i> DPIA</a><a href="organization.php"><i class="fas fa-building"></i> Org</a><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a><button class="theme-toggle" onclick="toggleTheme()"><?php echo $theme==='dark'?'☀️':'🌙'; ?></button></div></div></nav>
    
    <div class="container">
        <div class="header"><h1><i class="fas fa-file-alt"></i> DPIA Automation</h1><p>Data Protection Impact Assessment - Kenya DPA 2019 Section 31</p><button class="btn btn-white" style="margin-top:16px" onclick="openModal()"><i class="fas fa-plus"></i> Start New DPIA</button></div>
        
        <?php if($message): ?><div class="alert alert-<?php echo $messageType; ?>"><i class="fas <?php echo $messageType==='success'?'fa-check-circle':'fa-exclamation-circle'; ?>"></i> <?php echo htmlspecialchars($message); ?></div><?php endif; ?>
        
        <div class="stats-grid"><div class="stat-card"><div class="stat-value"><?php echo count($dpiaRecords); ?></div><div class="stat-label">Total DPIAs</div></div><div class="stat-card"><div class="stat-value"><?php echo $draftCount; ?></div><div class="stat-label">Draft</div></div><div class="stat-card"><div class="stat-value"><?php echo $pendingCount; ?></div><div class="stat-label">Pending</div></div><div class="stat-card"><div class="stat-value"><?php echo $approvedCount; ?></div><div class="stat-label">Approved</div></div></div>
        
        <?php if(empty($dpiaRecords)): ?>
        <div class="empty-state"><i class="fas fa-file-alt" style="font-size:48px;color:var(--gray);opacity:0.5;margin-bottom:16px"></i><p>No DPIAs yet.</p><button class="btn btn-primary" style="margin-top:16px" onclick="openModal()"><i class="fas fa-plus"></i> Start First DPIA</button></div>
        <?php else: foreach($dpiaRecords as $dpia): ?>
        <div class="dpia-card"><div class="dpia-header" onclick="toggleDPIA(<?php echo $dpia['id']; ?>)"><div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap"><strong><?php echo htmlspecialchars($dpia['dpia_reference']??'DPIA-'.$dpia['id']); ?></strong><span class="status-badge status-<?php echo $dpia['status']; ?>"><?php echo ucfirst(str_replace('_',' ',$dpia['status'])); ?></span><span class="risk-badge risk-<?php echo $dpia['risk_level']; ?>"><?php echo $dpia['risk_level']; ?></span></div><div style="display:flex;gap:6px" onclick="event.stopPropagation()"><a href="dpia-automation.php?report=<?php echo $dpia['id']; ?>" class="btn btn-report btn-sm" target="_blank"><i class="fas fa-file-pdf"></i> Report</a><button class="btn btn-outline btn-sm" onclick='editDPIA(<?php echo json_encode($dpia); ?>)'><i class="fas fa-edit"></i></button><button class="btn btn-danger btn-sm" onclick="deleteDPIA(<?php echo $dpia['id']; ?>)"><i class="fas fa-trash"></i></button></div></div><div class="dpia-body" id="dpia-<?php echo $dpia['id']; ?>"><p><strong>Project:</strong> <?php echo htmlspecialchars($dpia['project_name']); ?></p><p><strong>Processing:</strong> <?php echo htmlspecialchars(substr($dpia['processing_activity']??'',0,200)); ?></p><div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:12px"><a href="dpia-automation.php?report=<?php echo $dpia['id']; ?>" class="btn btn-report btn-sm" target="_blank"><i class="fas fa-file-pdf"></i> View Report</a><?php if($dpia['status']==='draft'): ?><form method="POST" style="display:inline"><input type="hidden" name="action" value="submit_review"><input type="hidden" name="dpia_id" value="<?php echo $dpia['id']; ?>"><button class="btn btn-primary btn-sm">Submit</button></form><?php elseif($dpia['status']==='pending_review'): ?><form method="POST" style="display:inline"><input type="hidden" name="action" value="approve_dpia"><input type="hidden" name="dpia_id" value="<?php echo $dpia['id']; ?>"><button class="btn btn-success btn-sm">Approve</button></form><?php endif; ?></div></div></div>
        <?php endforeach; endif; ?>
    </div>
    
    <div id="dpiaModal" class="modal"><div class="modal-content"><div class="modal-header"><h3><i class="fas fa-file-alt"></i> DPIA Form</h3><span class="close" onclick="closeModal()">&times;</span></div><div class="modal-body"><form method="POST" id="dpiaForm"><input type="hidden" name="action" id="formAction" value="create_dpia"><input type="hidden" name="dpia_id" id="dpia_id"><div class="form-group"><label>Project Name *</label><input type="text" name="project_name" id="project_name" required></div><div class="form-group"><label>Description</label><textarea name="project_description" id="project_description" rows="2"></textarea></div><div class="form-group"><label>Processing Activity *</label><textarea name="processing_activity" id="processing_activity" rows="3" required></textarea></div><div class="form-group"><label>Retention Period</label><input type="text" name="retention_period" id="retention_period"></div><div class="form-row"><div class="form-group"><label>Third Party Sharing</label><select name="third_party_sharing" id="third_party_sharing"><option value="0">No</option><option value="1">Yes</option></select></div><div class="form-group"><label>Risk Level</label><select name="risk_level" id="risk_level"><option value="Low">Low</option><option value="Medium" selected>Medium</option><option value="High">High</option></select></div></div><div class="form-group"><label>Identified Risks</label><textarea name="risk_identification" id="risk_identification" rows="3"></textarea></div><div class="form-group"><label>Risk Assessment</label><textarea name="risk_assessment" id="risk_assessment" rows="3"></textarea></div><div class="form-group"><label>Mitigation Measures</label><textarea name="mitigation_measures" id="mitigation_measures" rows="3"></textarea></div><div class="form-group"><label>Notes</label><textarea name="notes" id="notes" rows="2"></textarea></div><div style="display:flex;gap:10px;justify-content:flex-end"><button type="button" class="btn btn-outline" onclick="closeModal()">Cancel</button><button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save DPIA</button></div></form></div></div></div>
    
    <script>
        function toggleTheme(){const b=document.body;const d=b.classList.contains('dark');b.classList.remove('dark','light');b.classList.add(d?'light':'dark');document.cookie='soulguard_theme='+(d?'light':'dark')+';path=/;max-age=31536000';location.reload()}
        function toggleDPIA(id){const e=document.getElementById('dpia-'+id);e.style.display=(e.style.display==='none'||e.style.display==='')?'block':'none'}
        function openModal(){document.getElementById('dpiaModal').style.display='flex';document.getElementById('formAction').value='create_dpia';document.getElementById('dpiaForm').reset();document.getElementById('dpia_id').value=''}
        function closeModal(){document.getElementById('dpiaModal').style.display='none'}
        function editDPIA(d){document.getElementById('formAction').value='update_dpia';document.getElementById('dpia_id').value=d.id;document.getElementById('project_name').value=d.project_name||'';document.getElementById('project_description').value=d.project_description||'';document.getElementById('processing_activity').value=d.processing_activity||'';document.getElementById('retention_period').value=d.retention_period||'';document.getElementById('third_party_sharing').value=d.third_party_sharing||0;document.getElementById('risk_level').value=d.risk_level||'Medium';document.getElementById('risk_identification').value=d.risk_identification||'';document.getElementById('risk_assessment').value=d.risk_assessment||'';document.getElementById('mitigation_measures').value=d.mitigation_measures||'';document.getElementById('notes').value=d.notes||'';document.getElementById('dpiaModal').style.display='flex'}
        function deleteDPIA(id){if(confirm('Delete this DPIA?')){const f=document.createElement('form');f.method='POST';f.innerHTML='<input type="hidden" name="action" value="delete_dpia"><input type="hidden" name="dpia_id" value="'+id+'">';document.body.appendChild(f);f.submit()}}
        window.onclick=function(e){if(e.target.classList.contains('modal'))e.target.style.display='none'}
    </script>
</body>
</html>