<?php
/**
 * breach-workflow.php - Data Breach Management & Reporting System
 * Compliant with DPA 2019 Section 43 (Breach notification requirements)
 */

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

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

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create_breach':
                $message = createBreachReport($pdo, $organizationId, $userId, $_POST);
                $messageType = strpos($message, '✅') !== false ? 'success' : 'error';
                break;
                
            case 'update_status':
                $message = updateBreachStatus($pdo, $_POST['breach_id'], $_POST['status'], $userId);
                $messageType = strpos($message, '✅') !== false ? 'success' : 'error';
                break;
                
            case 'notify_regulator':
                $message = notifyRegulator($pdo, $_POST['breach_id'], $userId);
                $messageType = strpos($message, '✅') !== false ? 'success' : 'error';
                break;
                
            case 'notify_subjects':
                $message = notifyDataSubjects($pdo, $_POST['breach_id'], $userId);
                $messageType = strpos($message, '✅') !== false ? 'success' : 'error';
                break;
                
            case 'add_action':
                $message = addContainmentAction($pdo, $_POST['breach_id'], $userId, $_POST['action_text']);
                $messageType = strpos($message, '✅') !== false ? 'success' : 'error';
                break;
        }
    }
}

// Get all breach reports for this organization
$breaches = [];
$openBreaches = 0;
$criticalBreaches = 0;

try {
    $stmt = $pdo->prepare("
        SELECT * FROM breach_reports 
        WHERE organization_id = ? 
        ORDER BY breach_date DESC, created_at DESC
    ");
    $stmt->execute([$organizationId]);
    $breaches = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($breaches as $breach) {
        if (!in_array($breach['status'], ['resolved', 'closed'])) {
            $openBreaches++;
        }
        if ($breach['severity'] === 'Critical') {
            $criticalBreaches++;
        }
    }
} catch (Exception $e) {
    // Table might not exist yet
    createBreachTables($pdo);
}

// Timeline for breach (72-hour notification requirement)
$seventyTwoHours = 72 * 3600;

$theme = getTheme();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Breach Workflow - 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;
            --info: #3b82f6;
            --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: var(--primary);
            padding: 0 32px;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        body.light .navbar { background: white; border-bottom: 1px solid #e2e8f0; }
        
        .nav-container {
            max-width: 1600px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            min-height: 64px;
        }
        
        .logo h2 {
            background: linear-gradient(135deg, #fff, #94a3b8);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            font-size: 22px;
        }
        
        body.light .logo h2 {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .nav-links { display: flex; gap: 8px; align-items: center; }
        .nav-links a {
            color: rgba(255,255,255,0.8);
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.2s;
        }
        body.light .nav-links a { color: #1e293b; }
        .nav-links a:hover, .nav-links a.active { background: rgba(255,255,255,0.15); color: white; }
        body.light .nav-links a:hover, body.light .nav-links a.active { background: var(--primary); color: white; }
        
        .theme-toggle {
            background: rgba(255,255,255,0.15);
            border: none;
            border-radius: 50%;
            width: 36px;
            height: 36px;
            cursor: pointer;
            font-size: 18px;
        }
        body.light .theme-toggle { background: #f1f5f9; }
        
        .container { max-width: 1400px; margin: 0 auto; padding: 32px; }
        
        /* Header */
        .header {
            background: linear-gradient(135deg, var(--danger), #b91c1c);
            border-radius: var(--border-radius);
            padding: 32px;
            margin-bottom: 32px;
            color: white;
        }
        
        .header h1 { font-size: 28px; margin-bottom: 8px; }
        .header p { opacity: 0.9; }
        
        /* Stats */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 32px;
        }
        
        .stat-card {
            background: white;
            border-radius: var(--border-radius);
            padding: 20px;
            text-align: center;
            border: 1px solid #e2e8f0;
        }
        
        body.dark .stat-card { background: #1e293b; border-color: #334155; }
        
        .stat-value { font-size: 36px; font-weight: 800; }
        .stat-card.critical .stat-value { color: var(--danger); }
        .stat-card.open .stat-value { color: var(--warning); }
        .stat-label { font-size: 13px; color: var(--gray); margin-top: 8px; }
        
        /* Buttons */
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 500;
            font-size: 14px;
            border: none;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.2s;
        }
        
        .btn-primary { background: var(--primary); color: white; }
        .btn-danger { background: var(--danger); color: white; }
        .btn-success { background: var(--success); color: white; }
        .btn-outline { background: transparent; border: 1px solid var(--secondary); color: var(--secondary); }
        
        /* Breach Cards */
        .breach-card {
            background: white;
            border-radius: var(--border-radius);
            margin-bottom: 24px;
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }
        
        body.dark .breach-card { background: #1e293b; border-color: #334155; }
        
        .breach-header {
            padding: 20px 24px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }
        
        body.dark .breach-header { border-bottom-color: #334155; }
        
        .breach-title {
            display: flex;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
        }
        
        .breach-title h3 { font-size: 18px; }
        
        .severity {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .severity-critical { background: rgba(239,68,68,0.12); color: #ef4444; }
        .severity-high { background: rgba(245,158,11,0.12); color: #f59e0b; }
        .severity-medium { background: rgba(59,130,246,0.12); color: #3b82f6; }
        .severity-low { background: rgba(16,185,129,0.12); color: #10b981; }
        
        .status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .status-reported { background: rgba(100,116,139,0.12); color: #64748b; }
        .status-investigating { background: rgba(59,130,246,0.12); color: #3b82f6; }
        .status-contained { background: rgba(245,158,11,0.12); color: #f59e0b; }
        .status-notified { background: rgba(139,92,246,0.12); color: #8b5cf6; }
        .status-resolved { background: rgba(16,185,129,0.12); color: #10b981; }
        
        .breach-body { padding: 24px; }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }
        
        .info-item {
            padding: 12px;
            background: #f8fafc;
            border-radius: 8px;
        }
        
        body.dark .info-item { background: #0f172a; }
        
        .info-label { font-size: 11px; color: var(--gray); text-transform: uppercase; letter-spacing: 0.5px; }
        .info-value { font-size: 14px; font-weight: 500; margin-top: 4px; }
        
        .timeline-warning {
            background: rgba(239,68,68,0.08);
            border-left: 3px solid var(--danger);
            padding: 12px;
            margin-bottom: 20px;
            border-radius: 8px;
            font-size: 13px;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .badge-success { background: rgba(16,185,129,0.12); color: #10b981; }
        .badge-warning { background: rgba(245,158,11,0.12); color: #f59e0b; }
        
        .action-list {
            margin-top: 16px;
            padding-top: 16px;
            border-top: 1px solid #e2e8f0;
        }
        
        body.dark .action-list { border-top-color: #334155; }
        
        .action-item {
            padding: 8px 0;
            font-size: 13px;
            display: flex;
            gap: 12px;
            align-items: flex-start;
        }
        
        .action-time { font-size: 11px; color: var(--gray); min-width: 100px; }
        
        /* Modal */
        .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;
        }
        
        .modal-content {
            background: white;
            border-radius: var(--border-radius);
            max-width: 700px;
            width: 90%;
            max-height: 85vh;
            overflow-y: auto;
        }
        
        body.dark .modal-content { background: #1e293b; }
        
        .modal-header {
            padding: 20px 24px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-body { padding: 24px; }
        .close { cursor: pointer; font-size: 28px; font-weight: bold; }
        
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 500; font-size: 14px; }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-family: inherit;
            font-size: 14px;
            background: white;
        }
        body.dark .form-group input, body.dark .form-group select, body.dark .form-group textarea {
            background: #0f172a;
            border-color: #334155;
            color: white;
        }
        
        .alert {
            padding: 16px;
            border-radius: 12px;
            margin-bottom: 24px;
        }
        .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; }
        
        @media (max-width: 768px) {
            .container { padding: 16px; }
            .breach-header { flex-direction: column; align-items: flex-start; }
            .info-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body class="<?php echo $theme; ?>">
    <nav class="navbar">
        <div class="nav-container">
            <div class="logo"><h2><i class="fas fa-shield-alt"></i> Soul Guard</h2></div>
            <div class="nav-links">
                <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
                <a href="odpc-guidance.php"><i class="fas fa-book"></i> ODPC Guidance</a>
                <a href="breach-workflow.php" class="active"><i class="fas fa-bug"></i> Breach Workflow</a>
                <a href="profile.php"><i class="fas fa-user"></i> Profile</a>
                <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
                <div class="theme-toggle" onclick="toggleTheme()"><?php echo $theme === 'dark' ? '☀️' : '🌙'; ?></div>
            </div>
        </div>
    </nav>
    
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-bug"></i> Data Breach Management</h1>
            <p>Report, investigate, and manage data breaches in compliance with DPA 2019 Section 43</p>
            <button class="btn btn-danger" style="margin-top: 20px;" onclick="openModal('createModal')">
                <i class="fas fa-plus"></i> Report New Breach
            </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; ?>
        
        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card open">
                <div class="stat-value"><?php echo $openBreaches; ?></div>
                <div class="stat-label">Open Breaches</div>
            </div>
            <div class="stat-card critical">
                <div class="stat-value"><?php echo $criticalBreaches; ?></div>
                <div class="stat-label">Critical Severity</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo count($breaches); ?></div>
                <div class="stat-label">Total Reported</div>
            </div>
            <div class="stat-card">
                <div class="stat-value">72h</div>
                <div class="stat-label">Notification Deadline</div>
            </div>
        </div>
        
        <!-- Breach List -->
        <?php if (empty($breaches)): ?>
        <div style="text-align: center; padding: 60px; background: white; border-radius: var(--border-radius);">
            <i class="fas fa-shield-alt" style="font-size: 48px; color: var(--gray); margin-bottom: 16px;"></i>
            <p>No breach reports yet. Click "Report New Breach" to get started.</p>
        </div>
        <?php else: ?>
            <?php foreach ($breaches as $breach): 
                $breachDate = strtotime($breach['breach_date']);
                $discoveryDate = strtotime($breach['discovery_date']);
                $now = time();
                $hoursSinceDiscovery = round(($now - $discoveryDate) / 3600);
                $isUrgent = $hoursSinceDiscovery > 48;
                $deadlinePassed = $hoursSinceDiscovery > 72;
            ?>
            <div class="breach-card">
                <div class="breach-header">
                    <div class="breach-title">
                        <h3>#<?php echo htmlspecialchars($breach['breach_reference'] ?? 'BR' . $breach['id']); ?></h3>
                        <span class="severity severity-<?php echo strtolower($breach['severity']); ?>">
                            <i class="fas fa-exclamation-triangle"></i> <?php echo $breach['severity']; ?>
                        </span>
                        <span class="status status-<?php echo $breach['status']; ?>">
                            <?php echo ucfirst($breach['status']); ?>
                        </span>
                    </div>
                    <div>
                        <button class="btn btn-outline" style="margin-right: 8px;" onclick="openModal('actionModal', <?php echo $breach['id']; ?>)">
                            <i class="fas fa-check-circle"></i> Update Status
                        </button>
                        <button class="btn btn-outline" onclick="toggleBreachDetails(<?php echo $breach['id']; ?>)">
                            <i class="fas fa-chevron-down"></i> Details
                        </button>
                    </div>
                </div>
                <div class="breach-body" id="breach-<?php echo $breach['id']; ?>" style="display: none;">
                    <div class="info-grid">
                        <div class="info-item">
                            <div class="info-label">Breach Date</div>
                            <div class="info-value"><?php echo date('M j, Y H:i', strtotime($breach['breach_date'])); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Discovery Date</div>
                            <div class="info-value"><?php echo date('M j, Y H:i', strtotime($breach['discovery_date'])); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Affected Subjects</div>
                            <div class="info-value"><?php echo number_format($breach['affected_data_subjects']); ?> individuals</div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Reported By</div>
                            <div class="info-value"><?php echo htmlspecialchars($breach['created_by_name'] ?? 'System'); ?></div>
                        </div>
                    </div>
                    
                    <?php if ($isUrgent): ?>
                    <div class="timeline-warning">
                        <i class="fas fa-clock"></i> 
                        <strong><?php echo $deadlinePassed ? 'OVERDUE!' : 'Urgent Action Required'; ?></strong><br>
                        <?php if (!$breach['regulator_notified']): ?>
                            ODPC must be notified within 72 hours of discovery. 
                            <?php echo $deadlinePassed ? 'The deadline has passed.' : ($hoursSinceDiscovery . ' hours elapsed. ' . (72 - $hoursSinceDiscovery) . ' hours remaining.'); ?>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    
                    <div class="info-item" style="margin-bottom: 16px;">
                        <div class="info-label">Description</div>
                        <div class="info-value"><?php echo nl2br(htmlspecialchars($breach['description'])); ?></div>
                    </div>
                    
                    <?php if ($breach['containment_actions']): ?>
                    <div class="info-item" style="margin-bottom: 16px;">
                        <div class="info-label">Containment Actions</div>
                        <div class="info-value"><?php echo nl2br(htmlspecialchars($breach['containment_actions'])); ?></div>
                    </div>
                    <?php endif; ?>
                    
                    <div class="action-list">
                        <strong><i class="fas fa-clipboard-list"></i> Actions Taken</strong>
                        <div class="action-item">
                            <span class="action-time"><?php echo date('M j, H:i', strtotime($breach['created_at'])); ?></span>
                            <span>Breach reported and logged</span>
                        </div>
                        <?php if ($breach['regulator_notified']): ?>
                        <div class="action-item">
                            <span class="action-time"><?php echo date('M j, H:i', strtotime($breach['regulator_notification_date'])); ?></span>
                            <span><i class="fas fa-building"></i> ODPC notified</span>
                        </div>
                        <?php endif; ?>
                        <?php if ($breach['data_subjects_notified']): ?>
                        <div class="action-item">
                            <span class="action-time"><?php echo date('M j, H:i', strtotime($breach['subjects_notification_date'])); ?></span>
                            <span><i class="fas fa-users"></i> Affected data subjects notified</span>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div style="margin-top: 20px; display: flex; gap: 12px; flex-wrap: wrap;">
                        <?php if (!$breach['regulator_notified'] && $breach['severity'] !== 'Low'): ?>
                        <form method="POST" style="display: inline;" onsubmit="return confirm('Mark ODPC as notified? This should be done within 72 hours.');">
                            <input type="hidden" name="action" value="notify_regulator">
                            <input type="hidden" name="breach_id" value="<?php echo $breach['id']; ?>">
                            <button type="submit" class="btn btn-primary"><i class="fas fa-building"></i> Mark ODPC Notified</button>
                        </form>
                        <?php endif; ?>
                        
                        <?php if (!$breach['data_subjects_notified']): ?>
                        <form method="POST" style="display: inline;" onsubmit="return confirm('Mark affected data subjects as notified?');">
                            <input type="hidden" name="action" value="notify_subjects">
                            <input type="hidden" name="breach_id" value="<?php echo $breach['id']; ?>">
                            <button type="submit" class="btn btn-primary"><i class="fas fa-users"></i> Mark Subjects Notified</button>
                        </form>
                        <?php endif; ?>
                        
                        <button class="btn btn-outline" onclick="openActionModal(<?php echo $breach['id']; ?>)">
                            <i class="fas fa-plus"></i> Add Action
                        </button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    
    <!-- Create Breach Modal -->
    <div id="createModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-bug"></i> Report Data Breach</h3>
                <span class="close" onclick="closeModal('createModal')">&times;</span>
            </div>
            <div class="modal-body">
                <form method="POST" action="">
                    <input type="hidden" name="action" value="create_breach">
                    
                    <div class="form-group">
                        <label>Breach Date/Time *</label>
                        <input type="datetime-local" name="breach_date" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Discovery Date/Time *</label>
                        <input type="datetime-local" name="discovery_date" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Severity *</label>
                        <select name="severity" required>
                            <option value="Low">Low - Minimal impact, isolated incident</option>
                            <option value="Medium">Medium - Moderate impact, limited data exposure</option>
                            <option value="High">High - Significant impact, sensitive data exposed</option>
                            <option value="Critical">Critical - Severe impact, major data breach</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Number of Affected Data Subjects *</label>
                        <input type="number" name="affected_data_subjects" min="0" value="1" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Affected Data Categories</label>
                        <select name="affected_data_categories[]" multiple style="height: 100px;">
                            <option value="personal_details">Personal Details (Name, DOB, Address)</option>
                            <option value="contact_information">Contact Information (Email, Phone)</option>
                            <option value="identification">Identification (ID, Passport, KRA PIN)</option>
                            <option value="financial">Financial Data (Bank accounts, Cards)</option>
                            <option value="health">Health Information</option>
                            <option value="biometric">Biometric Data</option>
                            <option value="employment">Employment Records</option>
                        </select>
                        <small>Hold Ctrl/Cmd to select multiple</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Breach Description *</label>
                        <textarea name="description" rows="5" placeholder="Describe what happened, how the breach occurred, and what data was affected..." required></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>Immediate Containment Actions</label>
                        <textarea name="containment_actions" rows="3" placeholder="What actions have been taken to contain the breach?"></textarea>
                    </div>
                    
                    <div style="display: flex; gap: 12px; justify-content: flex-end;">
                        <button type="button" class="btn btn-outline" onclick="closeModal('createModal')">Cancel</button>
                        <button type="submit" class="btn btn-danger">Report Breach</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Update Status Modal -->
    <div id="statusModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Update Breach Status</h3>
                <span class="close" onclick="closeModal('statusModal')">&times;</span>
            </div>
            <div class="modal-body">
                <form method="POST" action="">
                    <input type="hidden" name="action" value="update_status">
                    <input type="hidden" name="breach_id" id="status_breach_id">
                    
                    <div class="form-group">
                        <label>New Status</label>
                        <select name="status" required>
                            <option value="reported">Reported - Initial report logged</option>
                            <option value="investigating">Investigating - Under investigation</option>
                            <option value="contained">Contained - Breach contained</option>
                            <option value="notified">Notified - ODPC/subjects notified</option>
                            <option value="resolved">Resolved - Issue resolved</option>
                            <option value="closed">Closed - Case closed</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Resolution Notes</label>
                        <textarea name="action_text" rows="3" placeholder="Add notes about the status change..."></textarea>
                    </div>
                    
                    <div style="display: flex; gap: 12px; justify-content: flex-end;">
                        <button type="button" class="btn btn-outline" onclick="closeModal('statusModal')">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Status</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Add Action Modal -->
    <div id="actionModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Add Containment Action</h3>
                <span class="close" onclick="closeModal('actionModal')">&times;</span>
            </div>
            <div class="modal-body">
                <form method="POST" action="">
                    <input type="hidden" name="action" value="add_action">
                    <input type="hidden" name="breach_id" id="action_breach_id">
                    
                    <div class="form-group">
                        <label>Action Description</label>
                        <textarea name="action_text" rows="4" placeholder="Describe the action taken (e.g., 'Patched vulnerability', 'Reset passwords', 'Notified affected users')" required></textarea>
                    </div>
                    
                    <div style="display: flex; gap: 12px; justify-content: flex-end;">
                        <button type="button" class="btn btn-outline" onclick="closeModal('actionModal')">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Action</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script>
        function toggleTheme() {
            const body = document.body;
            const isDark = body.classList.contains('dark');
            const newTheme = isDark ? 'light' : 'dark';
            body.classList.remove('dark', 'light');
            body.classList.add(newTheme);
            document.cookie = `soulguard_theme=${newTheme}; path=/; max-age=31536000`;
        }
        
        function toggleBreachDetails(id) {
            const details = document.getElementById(`breach-${id}`);
            const btn = details.previousElementSibling.querySelector('.btn-outline:last-child');
            if (details.style.display === 'none') {
                details.style.display = 'block';
                btn.innerHTML = '<i class="fas fa-chevron-up"></i> Details';
            } else {
                details.style.display = 'none';
                btn.innerHTML = '<i class="fas fa-chevron-down"></i> Details';
            }
        }
        
        function openModal(modalId, breachId = null) {
            document.getElementById(modalId).style.display = 'flex';
            if (breachId && modalId === 'statusModal') {
                document.getElementById('status_breach_id').value = breachId;
            }
            if (breachId && modalId === 'actionModal') {
                document.getElementById('action_breach_id').value = breachId;
            }
        }
        
        function openActionModal(breachId) {
            document.getElementById('action_breach_id').value = breachId;
            document.getElementById('actionModal').style.display = 'flex';
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }
    </script>
</body>
</html>

<?php
/**
 * Helper Functions for Breach Workflow
 */

function createBreachTables($pdo) {
    $sql = "CREATE TABLE IF NOT EXISTS breach_reports (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER NOT NULL,
        organization_id INTEGER,
        breach_reference VARCHAR(50),
        breach_date TIMESTAMP,
        discovery_date TIMESTAMP,
        notification_date TIMESTAMP,
        affected_data_subjects INTEGER DEFAULT 0,
        affected_data_categories TEXT,
        description TEXT,
        root_cause TEXT,
        containment_actions TEXT,
        remediation_actions TEXT,
        severity VARCHAR(20) DEFAULT 'Medium',
        status VARCHAR(20) DEFAULT 'reported',
        regulator_notified INTEGER DEFAULT 0,
        regulator_notification_date TIMESTAMP,
        data_subjects_notified INTEGER DEFAULT 0,
        subjects_notification_date TIMESTAMP,
        notification_method VARCHAR(100),
        created_by INTEGER NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP,
        resolved_at TIMESTAMP,
        notes TEXT
    )";
    $pdo->exec($sql);
}

function createBreachReport($pdo, $orgId, $userId, $data) {
    try {
        // Generate breach reference
        $breachRef = 'BR-' . date('Ymd') . '-' . rand(1000, 9999);
        
        $affectedCategories = isset($data['affected_data_categories']) ? json_encode($data['affected_data_categories']) : null;
        
        $stmt = $pdo->prepare("
            INSERT INTO breach_reports (
                user_id, organization_id, breach_reference, breach_date, discovery_date,
                severity, affected_data_subjects, affected_data_categories,
                description, containment_actions, status, created_by, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'reported', ?, datetime('now'))
        ");
        
        $stmt->execute([
            $userId, $orgId, $breachRef, $data['breach_date'], $data['discovery_date'],
            $data['severity'], $data['affected_data_subjects'], $affectedCategories,
            $data['description'], $data['containment_actions'] ?? '', $userId
        ]);
        
        return '✅ Breach report created successfully. Reference: ' . $breachRef;
    } catch (Exception $e) {
        return '❌ Error creating breach report: ' . $e->getMessage();
    }
}

function updateBreachStatus($pdo, $breachId, $status, $userId) {
    try {
        $stmt = $pdo->prepare("
            UPDATE breach_reports 
            SET status = ?, updated_at = datetime('now')
            WHERE id = ?
        ");
        $stmt->execute([$status, $breachId]);
        return '✅ Breach status updated to: ' . ucfirst($status);
    } catch (Exception $e) {
        return '❌ Error updating status: ' . $e->getMessage();
    }
}

function notifyRegulator($pdo, $breachId, $userId) {
    try {
        $stmt = $pdo->prepare("
            UPDATE breach_reports 
            SET regulator_notified = 1, 
                regulator_notification_date = datetime('now'),
                updated_at = datetime('now')
            WHERE id = ?
        ");
        $stmt->execute([$breachId]);
        return '✅ ODPC marked as notified. Keep documentation of this notification.';
    } catch (Exception $e) {
        return '❌ Error updating notification status: ' . $e->getMessage();
    }
}

function notifyDataSubjects($pdo, $breachId, $userId) {
    try {
        $stmt = $pdo->prepare("
            UPDATE breach_reports 
            SET data_subjects_notified = 1, 
                subjects_notification_date = datetime('now'),
                updated_at = datetime('now')
            WHERE id = ?
        ");
        $stmt->execute([$breachId]);
        return '✅ Data subjects marked as notified. Ensure you have proof of notification.';
    } catch (Exception $e) {
        return '❌ Error updating notification status: ' . $e->getMessage();
    }
}

function addContainmentAction($pdo, $breachId, $userId, $actionText) {
    try {
        // Append to existing containment actions
        $stmt = $pdo->prepare("SELECT containment_actions FROM breach_reports WHERE id = ?");
        $stmt->execute([$breachId]);
        $current = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $timestamp = date('Y-m-d H:i:s');
        $newAction = "\n[$timestamp] Action by User #$userId: $actionText";
        $updated = ($current['containment_actions'] ?? '') . $newAction;
        
        $stmt = $pdo->prepare("UPDATE breach_reports SET containment_actions = ?, updated_at = datetime('now') WHERE id = ?");
        $stmt->execute([$updated, $breachId]);
        
        return '✅ Action added successfully.';
    } catch (Exception $e) {
        return '❌ Error adding action: ' . $e->getMessage();
    }
}
?>