<?php
/**
 * processor-assessment.php - MySQL Compatible Version
 */

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

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

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

// =============================================
// CREATE TABLE IF NOT EXISTS (MySQL syntax)
// =============================================
try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS processor_assessments (
            id INT PRIMARY KEY AUTO_INCREMENT,
            user_id INT NOT NULL,
            organization_id INT,
            processor_name VARCHAR(255) NOT NULL,
            processor_contact_person VARCHAR(255),
            processor_email VARCHAR(255),
            processor_phone VARCHAR(50),
            processing_location VARCHAR(255),
            processing_purpose TEXT,
            contract_reviewed TINYINT DEFAULT 0,
            breach_notification_process TINYINT DEFAULT 0,
            audit_rights TINYINT DEFAULT 0,
            data_deletion_process TINYINT DEFAULT 0,
            risk_level VARCHAR(20) DEFAULT 'Medium',
            status VARCHAR(20) DEFAULT 'pending',
            assessment_notes TEXT,
            next_review_date DATE,
            approved_by INT,
            approval_date TIMESTAMP NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP
        )
    ");
} catch (Exception $e) {
    // Table might already exist
}

// =============================================
// CHECK IF USER HAS 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>You need to set up your organization before managing data processors.</p>
            <a href="organization.php?create=1" class="btn">Create Organization</a>
        </div>
    </body>
    </html>';
    exit;
}

// =============================================
// HANDLE FORM SUBMISSIONS
// =============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create_processor':
                try {
                    $stmt = $pdo->prepare("
                        INSERT INTO processor_assessments (
                            user_id, organization_id, processor_name, 
                            processor_contact_person, processor_email, processor_phone,
                            processing_location, processing_purpose,
                            contract_reviewed, breach_notification_process,
                            audit_rights, data_deletion_process,
                            risk_level, assessment_notes, next_review_date,
                            status
                        ) VALUES (
                            :user_id, :org_id, :processor_name,
                            :contact_person, :email, :phone,
                            :location, :purpose,
                            :contract, :breach,
                            :audit, :deletion,
                            :risk, :notes, :review_date,
                            'pending'
                        )
                    ");
                    
                    $stmt->execute([
                        ':user_id' => $userId,
                        ':org_id' => $organizationId,
                        ':processor_name' => $_POST['processor_name'],
                        ':contact_person' => $_POST['processor_contact_person'] ?? null,
                        ':email' => $_POST['processor_email'] ?? null,
                        ':phone' => $_POST['processor_phone'] ?? null,
                        ':location' => $_POST['processing_location'] ?? null,
                        ':purpose' => $_POST['processing_purpose'],
                        ':contract' => isset($_POST['contract_reviewed']) ? 1 : 0,
                        ':breach' => isset($_POST['breach_notification_process']) ? 1 : 0,
                        ':audit' => isset($_POST['audit_rights']) ? 1 : 0,
                        ':deletion' => isset($_POST['data_deletion_process']) ? 1 : 0,
                        ':risk' => $_POST['risk_level'] ?? 'Medium',
                        ':notes' => $_POST['assessment_notes'] ?? null,
                        ':review_date' => $_POST['next_review_date'] ?? null
                    ]);
                    
                    $message = '✅ Processor added successfully!';
                    $messageType = 'success';
                } catch (Exception $e) {
                    $message = '❌ Error: ' . $e->getMessage();
                    $messageType = 'error';
                }
                break;
                
            case 'update_processor':
                try {
                    $stmt = $pdo->prepare("
                        UPDATE processor_assessments SET
                            processor_name = :processor_name,
                            processor_contact_person = :contact_person,
                            processor_email = :email,
                            processor_phone = :phone,
                            processing_location = :location,
                            processing_purpose = :purpose,
                            contract_reviewed = :contract,
                            breach_notification_process = :breach,
                            audit_rights = :audit,
                            data_deletion_process = :deletion,
                            risk_level = :risk,
                            assessment_notes = :notes,
                            next_review_date = :review_date
                        WHERE id = :id AND organization_id = :org_id
                    ");
                    
                    $stmt->execute([
                        ':id' => $_POST['processor_id'],
                        ':org_id' => $organizationId,
                        ':processor_name' => $_POST['processor_name'],
                        ':contact_person' => $_POST['processor_contact_person'] ?? null,
                        ':email' => $_POST['processor_email'] ?? null,
                        ':phone' => $_POST['processor_phone'] ?? null,
                        ':location' => $_POST['processing_location'] ?? null,
                        ':purpose' => $_POST['processing_purpose'],
                        ':contract' => isset($_POST['contract_reviewed']) ? 1 : 0,
                        ':breach' => isset($_POST['breach_notification_process']) ? 1 : 0,
                        ':audit' => isset($_POST['audit_rights']) ? 1 : 0,
                        ':deletion' => isset($_POST['data_deletion_process']) ? 1 : 0,
                        ':risk' => $_POST['risk_level'] ?? 'Medium',
                        ':notes' => $_POST['assessment_notes'] ?? null,
                        ':review_date' => $_POST['next_review_date'] ?? null
                    ]);
                    
                    $message = '✅ Processor updated successfully!';
                    $messageType = 'success';
                } catch (Exception $e) {
                    $message = '❌ Error: ' . $e->getMessage();
                    $messageType = 'error';
                }
                break;
                
            case 'delete_processor':
                try {
                    $stmt = $pdo->prepare("DELETE FROM processor_assessments WHERE id = ? AND organization_id = ?");
                    $stmt->execute([$_POST['processor_id'], $organizationId]);
                    $message = '✅ Processor deleted successfully!';
                    $messageType = 'success';
                } catch (Exception $e) {
                    $message = '❌ Error: ' . $e->getMessage();
                    $messageType = 'error';
                }
                break;
                
            case 'approve_processor':
                try {
                    $stmt = $pdo->prepare("
                        UPDATE processor_assessments 
                        SET status = 'approved', approved_by = ?, approval_date = NOW()
                        WHERE id = ? AND organization_id = ?
                    ");
                    $stmt->execute([$userId, $_POST['processor_id'], $organizationId]);
                    $message = '✅ Processor approved successfully!';
                    $messageType = 'success';
                } catch (Exception $e) {
                    $message = '❌ Error: ' . $e->getMessage();
                    $messageType = 'error';
                }
                break;
        }
        
        // Redirect to avoid form resubmission
        header("Location: processor-assessment.php?msg=" . urlencode($message) . "&type=" . $messageType);
        exit;
    }
}

// Check for message from redirect
if (isset($_GET['msg'])) {
    $message = $_GET['msg'];
    $messageType = $_GET['type'] ?? 'success';
}

// =============================================
// FETCH PROCESSORS
// =============================================
$processors = [];
$highRiskCount = 0;
$pendingCount = 0;
$approvedCount = 0;

try {
    $stmt = $pdo->prepare("
        SELECT * FROM processor_assessments 
        WHERE organization_id = ? 
        ORDER BY 
            CASE risk_level 
                WHEN 'Critical' THEN 1 
                WHEN 'High' THEN 2 
                WHEN 'Medium' THEN 3 
                WHEN 'Low' THEN 4 
                ELSE 5 
            END,
            created_at DESC
    ");
    $stmt->execute([$organizationId]);
    $processors = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($processors as $p) {
        if ($p['risk_level'] === 'High' || $p['risk_level'] === 'Critical') {
            $highRiskCount++;
        }
        if ($p['status'] === 'pending') {
            $pendingCount++;
        }
        if ($p['status'] === 'approved') {
            $approvedCount++;
        }
    }
} catch (Exception $e) {
    error_log("Error fetching processors: " . $e->getMessage());
}

$theme = getTheme();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Processor Assessment - 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: 1400px;
            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; flex-wrap: wrap; }
        .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 {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            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-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.processors .stat-value { color: var(--primary); }
        .stat-card.high-risk .stat-value { color: var(--danger); }
        .stat-card.pending .stat-value { color: var(--warning); }
        .stat-card.approved .stat-value { color: var(--success); }
        .stat-label { font-size: 13px; color: var(--gray); margin-top: 8px; }
        
        .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;
            transition: all 0.2s;
        }
        
        .btn-primary { background: var(--primary); color: white; }
        .btn-success { background: var(--success); color: white; }
        .btn-danger { background: var(--danger); color: white; }
        .btn-outline { background: transparent; border: 1px solid var(--secondary); color: var(--secondary); }
        .btn-sm { padding: 6px 12px; font-size: 12px; }
        
        .processor-card {
            background: white;
            border-radius: var(--border-radius);
            margin-bottom: 20px;
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }
        
        body.dark .processor-card { background: #1e293b; border-color: #334155; }
        
        .processor-header {
            padding: 20px 24px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
            cursor: pointer;
        }
        
        body.dark .processor-header { border-bottom-color: #334155; }
        
        .processor-title { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
        .processor-title h3 { font-size: 18px; }
        
        .risk-badge { padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .risk-critical { background: rgba(239,68,68,0.12); color: #ef4444; }
        .risk-high { background: rgba(245,158,11,0.12); color: #f59e0b; }
        .risk-medium { background: rgba(59,130,246,0.12); color: #3b82f6; }
        .risk-low { background: rgba(16,185,129,0.12); color: #10b981; }
        
        .status-badge { padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .status-approved { background: rgba(16,185,129,0.12); color: #10b981; }
        .status-pending { background: rgba(245,158,11,0.12); color: #f59e0b; }
        
        .processor-body { padding: 24px; display: none; }
        
        .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; }
        .info-value { font-size: 14px; font-weight: 500; margin-top: 4px; }
        
        .checklist {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #e2e8f0;
        }
        
        .checklist-item { display: flex; align-items: center; gap: 12px; padding: 8px 0; }
        .checklist-item i.fa-check-circle { color: var(--success); }
        .checklist-item i.fa-times-circle { color: var(--danger); }
        
        .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: 800px;
            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;
        }
        
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        
        .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; }
        
        .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: 16px; }
            .form-row { grid-template-columns: 1fr; }
            .processor-header { flex-direction: column; align-items: flex-start; }
        }
    </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"><i class="fas fa-bug"></i> Breach Workflow</a>
                <a href="processor-assessment.php" class="active"><i class="fas fa-microchip"></i> Processors</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-microchip"></i> Data Processor Assessment</h1>
            <p>Manage and assess third-party data processors in compliance with DPA 2019 Section 39</p>
            <button class="btn btn-primary" style="margin-top: 20px;" onclick="openModal()">
                <i class="fas fa-plus"></i> Add Data Processor
            </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 processors">
                <div class="stat-value"><?php echo count($processors); ?></div>
                <div class="stat-label">Total Processors</div>
            </div>
            <div class="stat-card high-risk">
                <div class="stat-value"><?php echo $highRiskCount; ?></div>
                <div class="stat-label">High/Critical Risk</div>
            </div>
            <div class="stat-card pending">
                <div class="stat-value"><?php echo $pendingCount; ?></div>
                <div class="stat-label">Pending Assessment</div>
            </div>
            <div class="stat-card approved">
                <div class="stat-value"><?php echo $approvedCount; ?></div>
                <div class="stat-label">Approved</div>
            </div>
        </div>
        
        <?php if (empty($processors)): ?>
        <div class="empty-state">
            <i class="fas fa-microchip" style="font-size: 48px; color: var(--gray); margin-bottom: 16px;"></i>
            <p>No data processors added yet. Click "Add Data Processor" to begin.</p>
            <p style="font-size: 13px; margin-top: 8px;">Section 39 of DPA requires data controllers to assess and contractually bind data processors.</p>
        </div>
        <?php else: ?>
            <?php foreach ($processors as $processor): ?>
            <div class="processor-card">
                <div class="processor-header" onclick="toggleProcessor(<?php echo $processor['id']; ?>)">
                    <div class="processor-title">
                        <h3><i class="fas fa-building"></i> <?php echo htmlspecialchars($processor['processor_name']); ?></h3>
                        <span class="risk-badge risk-<?php echo strtolower($processor['risk_level']); ?>">
                            <?php echo $processor['risk_level']; ?> Risk
                        </span>
                        <span class="status-badge status-<?php echo $processor['status']; ?>">
                            <?php echo ucfirst($processor['status']); ?>
                        </span>
                    </div>
                    <div onclick="event.stopPropagation()">
                        <button class="btn btn-sm btn-outline" onclick='editProcessor(<?php echo json_encode($processor); ?>)'>
                            <i class="fas fa-edit"></i> Edit
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteProcessor(<?php echo $processor['id']; ?>, '<?php echo addslashes($processor['processor_name']); ?>')">
                            <i class="fas fa-trash"></i> Delete
                        </button>
                    </div>
                </div>
                <div class="processor-body" id="processor-<?php echo $processor['id']; ?>">
                    <div class="info-grid">
                        <div class="info-item">
                            <div class="info-label">Contact Person</div>
                            <div class="info-value"><?php echo htmlspecialchars($processor['processor_contact_person'] ?? 'N/A'); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Email</div>
                            <div class="info-value"><?php echo htmlspecialchars($processor['processor_email'] ?? 'N/A'); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Phone</div>
                            <div class="info-value"><?php echo htmlspecialchars($processor['processor_phone'] ?? 'N/A'); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Processing Location</div>
                            <div class="info-value"><?php echo htmlspecialchars($processor['processing_location'] ?? 'N/A'); ?></div>
                        </div>
                    </div>
                    
                    <div class="info-item" style="margin-bottom: 16px;">
                        <div class="info-label">Processing Purpose</div>
                        <div class="info-value"><?php echo nl2br(htmlspecialchars($processor['processing_purpose'])); ?></div>
                    </div>
                    
                    <div class="checklist">
                        <strong><i class="fas fa-clipboard-list"></i> Compliance Checklist</strong>
                        <div class="checklist-item">
                            <?php if ($processor['contract_reviewed']): ?>
                                <i class="fas fa-check-circle"></i> Contract reviewed and compliant
                            <?php else: ?>
                                <i class="fas fa-times-circle"></i> Contract not yet reviewed
                            <?php endif; ?>
                        </div>
                        <div class="checklist-item">
                            <?php if ($processor['breach_notification_process']): ?>
                                <i class="fas fa-check-circle"></i> Breach notification process in place
                            <?php else: ?>
                                <i class="fas fa-times-circle"></i> Missing breach notification process
                            <?php endif; ?>
                        </div>
                        <div class="checklist-item">
                            <?php if ($processor['audit_rights']): ?>
                                <i class="fas fa-check-circle"></i> Audit rights reserved
                            <?php else: ?>
                                <i class="fas fa-times-circle"></i> Missing audit rights clause
                            <?php endif; ?>
                        </div>
                        <div class="checklist-item">
                            <?php if ($processor['data_deletion_process']): ?>
                                <i class="fas fa-check-circle"></i> Data deletion process defined
                            <?php else: ?>
                                <i class="fas fa-times-circle"></i> Missing data deletion process
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <?php if ($processor['status'] !== 'approved'): ?>
                    <div style="margin-top: 20px;">
                        <form method="POST" style="display: inline;" onsubmit="return confirm('Approve this processor?');">
                            <input type="hidden" name="action" value="approve_processor">
                            <input type="hidden" name="processor_id" value="<?php echo $processor['id']; ?>">
                            <button type="submit" class="btn btn-success"><i class="fas fa-check"></i> Approve Processor</button>
                        </form>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    
    <!-- Modal -->
    <div id="processorModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle"><i class="fas fa-microchip"></i> Add Data Processor</h3>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>
            <div class="modal-body">
                <form method="POST" action="" id="processorForm">
                    <input type="hidden" name="action" id="formAction" value="create_processor">
                    <input type="hidden" name="processor_id" id="processor_id">
                    
                    <div class="form-group">
                        <label>Processor Name *</label>
                        <input type="text" name="processor_name" id="processor_name" required>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Contact Person</label>
                            <input type="text" name="processor_contact_person" id="processor_contact_person">
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input type="email" name="processor_email" id="processor_email">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Phone</label>
                            <input type="text" name="processor_phone" id="processor_phone">
                        </div>
                        <div class="form-group">
                            <label>Processing Location</label>
                            <input type="text" name="processing_location" id="processing_location" placeholder="e.g., Kenya, Ireland">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Processing Purpose *</label>
                        <textarea name="processing_purpose" id="processing_purpose" rows="3" required></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>Risk Level</label>
                        <select name="risk_level" id="risk_level">
                            <option value="Low">Low</option>
                            <option value="Medium">Medium</option>
                            <option value="High">High</option>
                            <option value="Critical">Critical</option>
                        </select>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label><input type="checkbox" name="contract_reviewed" value="1" id="contract_reviewed"> Contract Reviewed</label>
                        </div>
                        <div class="form-group">
                            <label><input type="checkbox" name="breach_notification_process" value="1" id="breach_notification_process"> Breach Notification Process</label>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label><input type="checkbox" name="audit_rights" value="1" id="audit_rights"> Audit Rights Reserved</label>
                        </div>
                        <div class="form-group">
                            <label><input type="checkbox" name="data_deletion_process" value="1" id="data_deletion_process"> Data Deletion Process</label>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Assessment Notes</label>
                        <textarea name="assessment_notes" id="assessment_notes" rows="3"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>Next Review Date</label>
                        <input type="date" name="next_review_date" id="next_review_date">
                    </div>
                    
                    <div style="display: flex; gap: 12px; justify-content: flex-end;">
                        <button type="button" class="btn btn-outline" onclick="closeModal()">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Processor</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`;
            location.reload();
        }
        
        function toggleProcessor(id) {
            const el = document.getElementById(`processor-${id}`);
            if (el.style.display === 'none' || el.style.display === '') {
                el.style.display = 'block';
            } else {
                el.style.display = 'none';
            }
        }
        
        function openModal() {
            document.getElementById('processorModal').style.display = 'flex';
            document.getElementById('modalTitle').innerHTML = '<i class="fas fa-microchip"></i> Add Data Processor';
            document.getElementById('formAction').value = 'create_processor';
            document.getElementById('processorForm').reset();
            document.getElementById('processor_id').value = '';
        }
        
        function closeModal() {
            document.getElementById('processorModal').style.display = 'none';
        }
        
        function editProcessor(processor) {
            document.getElementById('modalTitle').innerHTML = '<i class="fas fa-edit"></i> Edit Data Processor';
            document.getElementById('formAction').value = 'update_processor';
            document.getElementById('processor_id').value = processor.id;
            document.getElementById('processor_name').value = processor.processor_name || '';
            document.getElementById('processor_contact_person').value = processor.processor_contact_person || '';
            document.getElementById('processor_email').value = processor.processor_email || '';
            document.getElementById('processor_phone').value = processor.processor_phone || '';
            document.getElementById('processing_location').value = processor.processing_location || '';
            document.getElementById('processing_purpose').value = processor.processing_purpose || '';
            document.getElementById('risk_level').value = processor.risk_level || 'Medium';
            document.getElementById('contract_reviewed').checked = processor.contract_reviewed == 1;
            document.getElementById('breach_notification_process').checked = processor.breach_notification_process == 1;
            document.getElementById('audit_rights').checked = processor.audit_rights == 1;
            document.getElementById('data_deletion_process').checked = processor.data_deletion_process == 1;
            document.getElementById('assessment_notes').value = processor.assessment_notes || '';
            document.getElementById('next_review_date').value = processor.next_review_date || '';
            document.getElementById('processorModal').style.display = 'flex';
        }
        
        function deleteProcessor(id, name) {
            if (confirm(`Delete "${name}"? This action cannot be undone.`)) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = '<input type="hidden" name="action" value="delete_processor"><input type="hidden" name="processor_id" value="' + id + '">';
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }
    </script>
</body>
</html>