<?php
/**
 * odpc-guidance.php - ODPC Compliance Guidance & Mapping
 * Maps Kenya Data Protection Act requirements to actionable tasks
 */

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 task completion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'complete_task' && isset($_POST['task_id'])) {
        $taskId = (int)$_POST['task_id'];
        try {
            $stmt = $pdo->prepare("
                UPDATE odpc_compliance_tasks 
                SET is_completed = 1, 
                    completed_date = date('now'),
                    progress_percentage = 100
                WHERE id = ? AND organization_id = ?
            ");
            $stmt->execute([$taskId, $organizationId]);
            $message = '✅ Task marked as complete!';
            $messageType = 'success';
        } catch (Exception $e) {
            $message = '❌ Error updating task: ' . $e->getMessage();
            $messageType = 'error';
        }
    }
    
    if ($_POST['action'] === 'reset_task' && isset($_POST['task_id'])) {
        $taskId = (int)$_POST['task_id'];
        try {
            $stmt = $pdo->prepare("
                UPDATE odpc_compliance_tasks 
                SET is_completed = 0, 
                    completed_date = NULL,
                    progress_percentage = 0
                WHERE id = ? AND organization_id = ?
            ");
            $stmt->execute([$taskId, $organizationId]);
            $message = '🔄 Task reset successfully.';
            $messageType = 'info';
        } catch (Exception $e) {
            $message = '❌ Error resetting task: ' . $e->getMessage();
            $messageType = 'error';
        }
    }
    
    if ($_POST['action'] === 'add_notes' && isset($_POST['task_id']) && isset($_POST['notes'])) {
        $taskId = (int)$_POST['task_id'];
        $notes = trim($_POST['notes']);
        try {
            $stmt = $pdo->prepare("UPDATE odpc_compliance_tasks SET notes = ? WHERE id = ? AND organization_id = ?");
            $stmt->execute([$notes, $taskId, $organizationId]);
            $message = '📝 Notes saved successfully!';
            $messageType = 'success';
        } catch (Exception $e) {
            $message = '❌ Error saving notes: ' . $e->getMessage();
            $messageType = 'error';
        }
    }
}

// Get all ODPC compliance tasks for this organization
$tasks = [];
$completedCount = 0;
$totalCount = 0;
$compliancePercentage = 0;

try {
    // Check if tasks exist for this organization
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM odpc_compliance_tasks WHERE organization_id = ?");
    $stmt->execute([$organizationId]);
    $taskCount = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    if ($taskCount == 0 && $organizationId) {
        // Copy default tasks to organization
        $stmt = $pdo->prepare("
            INSERT INTO odpc_compliance_tasks (organization_id, task_category, task_name, task_description, guidance_reference, legal_basis, is_mandatory, priority)
            SELECT ?, task_category, task_name, task_description, guidance_reference, legal_basis, is_mandatory, priority
            FROM odpc_default_tasks
        ");
        $stmt->execute([$organizationId]);
    }
    
    // Get all tasks
    $stmt = $pdo->prepare("
        SELECT * FROM odpc_compliance_tasks 
        WHERE organization_id = ? 
        ORDER BY 
            CASE priority WHEN 'Urgent' THEN 1 WHEN 'High' THEN 2 WHEN 'Medium' THEN 3 WHEN 'Low' THEN 4 END,
            task_category,
            task_name
    ");
    $stmt->execute([$organizationId]);
    $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $totalCount = count($tasks);
    $completedCount = 0;
    foreach ($tasks as $task) {
        if ($task['is_completed']) $completedCount++;
    }
    $compliancePercentage = $totalCount > 0 ? round(($completedCount / $totalCount) * 100) : 0;
    
} catch (Exception $e) {
    error_log("ODPC tasks error: " . $e->getMessage());
}

// Group tasks by category
$groupedTasks = [];
foreach ($tasks as $task) {
    $category = $task['task_category'] ?? 'General';
    if (!isset($groupedTasks[$category])) {
        $groupedTasks[$category] = [];
    }
    $groupedTasks[$category][] = $task;
}

// Get compliance score
$complianceScore = 0;
$riskLevel = 'Not Assessed';
try {
    $stmt = $pdo->prepare("
        SELECT overall_score, risk_level FROM compliance_scores 
        WHERE organization_id = ? ORDER BY assessment_date DESC LIMIT 1
    ");
    $stmt->execute([$organizationId]);
    $score = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($score) {
        $complianceScore = $score['overall_score'];
        $riskLevel = $score['risk_level'];
    } else {
        $complianceScore = $compliancePercentage;
        $riskLevel = $compliancePercentage >= 80 ? 'Low' : ($compliancePercentage >= 50 ? 'Medium' : 'High');
    }
} catch (Exception $e) {}

$theme = getTheme();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ODPC Guidance - 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: var(--dark); }
        .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(--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 Cards */
        .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; color: var(--primary); }
        .stat-label { font-size: 13px; color: var(--gray); margin-top: 8px; }
        
        /* Compliance Bar */
        .compliance-bar {
            background: white;
            border-radius: var(--border-radius);
            padding: 24px;
            margin-bottom: 32px;
            border: 1px solid #e2e8f0;
        }
        
        body.dark .compliance-bar { background: #1e293b; border-color: #334155; }
        
        .progress-container {
            background: #e2e8f0;
            border-radius: 20px;
            height: 12px;
            overflow: hidden;
            margin: 16px 0;
        }
        
        body.dark .progress-container { background: #334155; }
        
        .progress-fill {
            background: linear-gradient(90deg, var(--success), #34d399);
            height: 100%;
            border-radius: 20px;
            transition: width 0.5s;
        }
        
        /* Category Section */
        .category {
            background: white;
            border-radius: var(--border-radius);
            margin-bottom: 24px;
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }
        
        body.dark .category { background: #1e293b; border-color: #334155; }
        
        .category-header {
            padding: 20px 24px;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        body.dark .category-header { background: #0f172a; border-bottom-color: #334155; }
        
        .category-header h3 {
            font-size: 18px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .category-badge {
            background: var(--secondary);
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
        }
        
        .task-list { padding: 0 24px; }
        
        .task-item {
            padding: 20px 0;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            gap: 16px;
            align-items: flex-start;
        }
        
        body.dark .task-item { border-bottom-color: #334155; }
        
        .task-checkbox { margin-top: 4px; }
        .task-checkbox input {
            width: 22px;
            height: 22px;
            cursor: pointer;
            accent-color: var(--success);
        }
        
        .task-content { flex: 1; }
        .task-title {
            font-weight: 600;
            font-size: 16px;
            margin-bottom: 6px;
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .task-description { font-size: 14px; color: var(--gray); margin-bottom: 8px; }
        
        .task-meta {
            display: flex;
            gap: 16px;
            flex-wrap: wrap;
            font-size: 12px;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .badge-urgent { background: rgba(239,68,68,0.12); color: #ef4444; }
        .badge-high { background: rgba(245,158,11,0.12); color: #f59e0b; }
        .badge-medium { background: rgba(59,130,246,0.12); color: #3b82f6; }
        .badge-low { background: rgba(16,185,129,0.12); color: #10b981; }
        .badge-success { background: rgba(16,185,129,0.12); color: #10b981; }
        .badge-mandatory { background: rgba(100,116,139,0.12); color: #64748b; }
        
        .reference {
            font-family: monospace;
            background: #f1f5f9;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 11px;
        }
        
        body.dark .reference { background: #334155; }
        
        .notes-section {
            margin-top: 12px;
            padding: 12px;
            background: #f8fafc;
            border-radius: 8px;
            display: none;
        }
        
        body.dark .notes-section { background: #0f172a; }
        
        .notes-section textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            background: white;
            font-family: inherit;
            font-size: 13px;
        }
        
        body.dark .notes-section textarea { background: #1e293b; border-color: #334155; color: white; }
        
        .btn-icon {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 14px;
            color: var(--gray);
            padding: 4px;
        }
        
        .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; }
        .alert-info { background: rgba(59,130,246,0.1); border: 1px solid rgba(59,130,246,0.3); color: #3b82f6; }
        
        @media (max-width: 768px) {
            .container { padding: 16px; }
            .task-item { flex-direction: column; }
            .task-checkbox { order: 2; }
        }
    </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" class="active"><i class="fas fa-book"></i> ODPC Guidance</a>
                <a href="profile.php"><i class="fas fa-user"></i> Profile</a>
                <a href="organization.php"><i class="fas fa-building"></i> Organization</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">
        <!-- Header -->
        <div class="header">
            <h1><i class="fas fa-book"></i> ODPC Compliance Guidance</h1>
            <p>Interactive checklist based on Kenya Data Protection Act (DPA) 2019 and ODPC Guidelines</p>
        </div>
        
        <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>">
            <i class="fas <?php echo $messageType === 'success' ? 'fa-check-circle' : ($messageType === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle'); ?>"></i>
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>
        
        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-value"><?php echo $completedCount; ?>/<?php echo $totalCount; ?></div>
                <div class="stat-label">Tasks Completed</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo $compliancePercentage; ?>%</div>
                <div class="stat-label">Compliance Progress</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo $complianceScore; ?>%</div>
                <div class="stat-label">Overall Score</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo $riskLevel; ?></div>
                <div class="stat-label">Risk Level</div>
            </div>
        </div>
        
        <!-- Compliance Progress -->
        <div class="compliance-bar">
            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                <span><strong>Overall Compliance Progress</strong></span>
                <span><strong><?php echo $compliancePercentage; ?>%</strong></span>
            </div>
            <div class="progress-container">
                <div class="progress-fill" style="width: <?php echo $compliancePercentage; ?>%"></div>
            </div>
            <div style="display: flex; justify-content: space-between; margin-top: 16px; font-size: 13px; color: var(--gray);">
                <span><i class="fas fa-flag-checkered"></i> ODPC Registration Required</span>
                <span><i class="fas fa-clock"></i> Last Updated: <?php echo date('M j, Y'); ?></span>
            </div>
        </div>
        
        <!-- Tasks by Category -->
        <?php foreach ($groupedTasks as $category => $categoryTasks): 
            $categoryCompleted = 0;
            foreach ($categoryTasks as $task) {
                if ($task['is_completed']) $categoryCompleted++;
            }
            $categoryTotal = count($categoryTasks);
            $categoryPercent = $categoryTotal > 0 ? round(($categoryCompleted / $categoryTotal) * 100) : 0;
        ?>
        <div class="category">
            <div class="category-header" onclick="toggleCategory(this)">
                <h3>
                    <i class="fas fa-folder"></i> <?php echo htmlspecialchars($category); ?>
                    <span class="badge badge-<?php echo $categoryPercent >= 80 ? 'success' : ($categoryPercent >= 50 ? 'info' : 'warning'); ?>">
                        <?php echo $categoryPercent; ?>%
                    </span>
                </h3>
                <i class="fas fa-chevron-down"></i>
            </div>
            <div class="task-list" style="display: block;">
                <?php foreach ($categoryTasks as $task): 
                    $priorityClass = $task['priority'] === 'Urgent' ? 'badge-urgent' : ($task['priority'] === 'High' ? 'badge-high' : ($task['priority'] === 'Medium' ? 'badge-medium' : 'badge-low'));
                ?>
                <div class="task-item" id="task-<?php echo $task['id']; ?>">
                    <div class="task-checkbox">
                        <input type="checkbox" onchange="toggleTask(<?php echo $task['id']; ?>, this.checked)" <?php echo $task['is_completed'] ? 'checked' : ''; ?>>
                    </div>
                    <div class="task-content">
                        <div class="task-title">
                            <?php echo htmlspecialchars($task['task_name']); ?>
                            <span class="badge <?php echo $priorityClass; ?>"><?php echo $task['priority']; ?></span>
                            <?php if ($task['is_mandatory']): ?>
                            <span class="badge badge-mandatory"><i class="fas fa-gavel"></i> Mandatory</span>
                            <?php endif; ?>
                        </div>
                        <div class="task-description">
                            <?php echo htmlspecialchars($task['task_description'] ?? 'No description available'); ?>
                        </div>
                        <div class="task-meta">
                            <?php if ($task['guidance_reference']): ?>
                            <span class="reference"><i class="fas fa-quote-right"></i> Ref: <?php echo htmlspecialchars($task['guidance_reference']); ?></span>
                            <?php endif; ?>
                            <?php if ($task['legal_basis']): ?>
                            <span><i class="fas fa-gavel"></i> <?php echo htmlspecialchars($task['legal_basis']); ?></span>
                            <?php endif; ?>
                            <?php if ($task['completed_date']): ?>
                            <span class="badge badge-success"><i class="fas fa-check"></i> Completed: <?php echo date('M j, Y', strtotime($task['completed_date'])); ?></span>
                            <?php endif; ?>
                            <button class="btn-icon" onclick="toggleNotes(<?php echo $task['id']; ?>)">
                                <i class="fas fa-pen"></i> Notes
                            </button>
                        </div>
                        <div class="notes-section" id="notes-<?php echo $task['id']; ?>">
                            <form method="POST" action="">
                                <input type="hidden" name="action" value="add_notes">
                                <input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
                                <textarea name="notes" rows="2" placeholder="Add compliance notes, evidence links, or reminders..."><?php echo htmlspecialchars($task['notes'] ?? ''); ?></textarea>
                                <div style="margin-top: 8px; text-align: right;">
                                    <button type="submit" class="btn-sm" style="background: var(--secondary); color: white; padding: 6px 12px; border: none; border-radius: 6px; cursor: pointer;">Save Notes</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>
        
        <!-- Resource Section -->
        <div class="category">
            <div class="category-header" onclick="toggleCategory(this)">
                <h3><i class="fas fa-link"></i> Helpful Resources</h3>
                <i class="fas fa-chevron-down"></i>
            </div>
            <div class="task-list" style="display: block;">
                <div class="task-item">
                    <div class="task-content">
                        <div class="task-title">Kenya Data Protection Act, 2019</div>
                        <div class="task-description">Full text of the DPA 2019 - The primary legislation governing data protection in Kenya.</div>
                        <div class="task-meta">
                            <a href="https://www.odpc.go.ke/data-protection-laws-kenya/" target="_blank" style="color: var(--secondary);">Download PDF →</a>
                        </div>
                    </div>
                </div>
                <div class="task-item">
                    <div class="task-content">
                        <div class="task-title">ODPC Guidance Notes</div>
                        <div class="task-description">Official guidance from the Office of the Data Protection Commissioner.</div>
                        <div class="task-meta">
                            <a href="https://www.odpc.go.ke/access-to-information//" target="_blank" style="color: var(--secondary);">View Resources →</a>
                        </div>
                    </div>
                </div>
                <div class="task-item">
                    <div class="task-content">
                        <div class="task-title">Registration Portal</div>
                        <div class="task-description">Register as a Data Controller or Data Processor with ODPC.</div>
                        <div class="task-meta">
                            <a href="https://dataportal.odpc.go.ke/" target="_blank" style="color: var(--secondary);">Go to Portal →</a>
                        </div>
                    </div>
                </div>
            </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 toggleCategory(header) {
            const taskList = header.nextElementSibling;
            const icon = header.querySelector('.fa-chevron-down, .fa-chevron-up');
            if (taskList.style.display === 'none') {
                taskList.style.display = 'block';
                icon.classList.remove('fa-chevron-up');
                icon.classList.add('fa-chevron-down');
            } else {
                taskList.style.display = 'none';
                icon.classList.remove('fa-chevron-down');
                icon.classList.add('fa-chevron-up');
            }
        }
        
        function toggleNotes(taskId) {
            const notesDiv = document.getElementById(`notes-${taskId}`);
            if (notesDiv.style.display === 'none' || !notesDiv.style.display) {
                notesDiv.style.display = 'block';
            } else {
                notesDiv.style.display = 'none';
            }
        }
        
        function toggleTask(taskId, isChecked) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '';
            form.style.display = 'none';
            
            const actionInput = document.createElement('input');
            actionInput.name = 'action';
            actionInput.value = isChecked ? 'complete_task' : 'reset_task';
            form.appendChild(actionInput);
            
            const taskInput = document.createElement('input');
            taskInput.name = 'task_id';
            taskInput.value = taskId;
            form.appendChild(taskInput);
            
            document.body.appendChild(form);
            form.submit();
        }
        
        // Expand first category by default
        const firstCategory = document.querySelector('.category .category-header');
        if (firstCategory) {
            // Keep expanded
        }
    </script>
</body>
</html>