<?php
// member/api/calculate-compliance.php
require_once '../../config.php';
requireLogin();

header('Content-Type: application/json');

$userId = $_SESSION['user_id'];
$org = getUserOrganization($userId);
$pdo = getDBConnection();

if (!$org) {
    echo json_encode(['success' => false, 'message' => 'No organization found.']);
    exit;
}

try {
    $orgId = $org['id'];
    
    // =============================================
    // DPIA SCORE (25 points)
    // =============================================
    $dpiaScore = 0;
    try {
        // Simple count - don't try to filter by columns that might not exist
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM dpia_records WHERE organization_id = ?");
        $stmt->execute([$orgId]);
        $totalDpias = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
        
        // Check for completed DPIAs - use status column
        $completedDpias = 0;
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) as completed FROM dpia_records WHERE organization_id = ? AND status IN ('completed', 'reviewed')");
            $stmt->execute([$orgId]);
            $completedDpias = $stmt->fetch(PDO::FETCH_ASSOC)['completed'] ?? 0;
        } catch (Exception $e) {
            // If status column doesn't exist, just count all
            $completedDpias = $totalDpias;
        }
    } catch (Exception $e) {
        $totalDpias = 0;
        $completedDpias = 0;
    }
    
    if ($totalDpias > 0) {
        $dpiaScore += 10;
        if ($completedDpias > 0) $dpiaScore += 10;
        if ($totalDpias > 3) $dpiaScore += 5;
    }
    
    // =============================================
    // BREACH READINESS SCORE (25 points)
    // =============================================
    $breachScore = 25;
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as open FROM breach_reports WHERE organization_id = ? AND status NOT IN ('resolved', 'closed')");
        $stmt->execute([$orgId]);
        $openBreaches = $stmt->fetch(PDO::FETCH_ASSOC)['open'] ?? 0;
        
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM breach_reports WHERE organization_id = ?");
        $stmt->execute([$orgId]);
        $totalBreaches = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    } catch (Exception $e) {
        $openBreaches = 0;
        $totalBreaches = 0;
    }
    
    if ($totalBreaches > 0) {
        $breachScore -= 5;
        if ($openBreaches > 0) $breachScore -= ($openBreaches * 3);
    }
    $breachScore = max(0, min(25, $breachScore));
    
    // =============================================
    // PROCESSOR MANAGEMENT SCORE (25 points)
    // =============================================
    $processorScore = 15;
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM processor_assessments WHERE organization_id = ?");
        $stmt->execute([$orgId]);
        $totalProcessors = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
        
        if ($totalProcessors > 0) {
            $processorScore = 8;
            try {
                $stmt = $pdo->prepare("SELECT COUNT(*) as with_contracts FROM processor_assessments WHERE organization_id = ? AND contract_reviewed = 1");
                $stmt->execute([$orgId]);
                $withContracts = $stmt->fetch(PDO::FETCH_ASSOC)['with_contracts'] ?? 0;
                if ($withContracts > 0) $processorScore += round(($withContracts / $totalProcessors) * 10);
            } catch (Exception $e) {}
            
            try {
                $stmt = $pdo->prepare("SELECT COUNT(*) as approved FROM processor_assessments WHERE organization_id = ? AND status = 'approved'");
                $stmt->execute([$orgId]);
                $approved = $stmt->fetch(PDO::FETCH_ASSOC)['approved'] ?? 0;
                if ($approved > 0) $processorScore += 7;
            } catch (Exception $e) {}
        }
    } catch (Exception $e) {}
    $processorScore = min(25, $processorScore);
    
    // =============================================
    // ODPC ALIGNMENT SCORE (25 points)
    // =============================================
    $odpcScore = 0;
    if (!empty($org['registration_number'])) $odpcScore += 10;
    if (!empty($org['name'])) $odpcScore += 3;
    if (!empty($org['industry'])) $odpcScore += 2;
    
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as has_dpo FROM organization_dpo WHERE organization_id = ? AND status = 'active'");
        $stmt->execute([$orgId]);
        if (($stmt->fetch(PDO::FETCH_ASSOC)['has_dpo'] ?? 0) > 0) $odpcScore += 5;
    } catch (Exception $e) {}
    
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM odpc_compliance_tasks WHERE organization_id = ?");
        $stmt->execute([$orgId]);
        $totalTasks = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
        if ($totalTasks > 0) {
            $stmt = $pdo->prepare("SELECT COUNT(*) as completed FROM odpc_compliance_tasks WHERE organization_id = ? AND is_completed = 1");
            $stmt->execute([$orgId]);
            $completedTasks = $stmt->fetch(PDO::FETCH_ASSOC)['completed'] ?? 0;
            $odpcScore += round(($completedTasks / $totalTasks) * 5);
        }
    } catch (Exception $e) {}
    $odpcScore = min(25, $odpcScore);
    
    // =============================================
    // DATA PROTECTION SCORE (25 points)
    // =============================================
    $dataProtectionScore = 0;
    try {
        $stmt = $pdo->prepare("SELECT * FROM security_measures WHERE organization_id = ? ORDER BY assessment_date DESC LIMIT 1");
        $stmt->execute([$orgId]);
        $security = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($security) {
            if (!empty($security['has_encryption'])) $dataProtectionScore += 8;
            if (!empty($security['has_mfa'])) $dataProtectionScore += 6;
            if (!empty($security['has_backup'])) $dataProtectionScore += 5;
            if (!empty($security['has_access_control'])) $dataProtectionScore += 6;
        }
    } catch (Exception $e) {}
    
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as analyzed FROM file_risk_analyses WHERE organization_id = ? AND status IN ('analyzed', 'anonymized')");
        $stmt->execute([$orgId]);
        $analyzedFiles = $stmt->fetch(PDO::FETCH_ASSOC)['analyzed'] ?? 0;
        if ($analyzedFiles > 0) $dataProtectionScore += min(5, $analyzedFiles);
    } catch (Exception $e) {}
    $dataProtectionScore = min(25, $dataProtectionScore);
    
    // =============================================
    // OVERALL SCORE
    // =============================================
    $overallScore = round($dpiaScore + $breachScore + $processorScore + $odpcScore + $dataProtectionScore);
    
    $riskLevel = 'Critical';
    if ($overallScore >= 80) $riskLevel = 'Low';
    elseif ($overallScore >= 60) $riskLevel = 'Medium';
    elseif ($overallScore >= 40) $riskLevel = 'High';
    
    // Recommendations
    $recommendations = [];
    if ($dpiaScore < 15) $recommendations[] = "Conduct Data Protection Impact Assessments (DPIAs) for high-risk processing activities";
    if ($breachScore < 15) $recommendations[] = "Improve breach response readiness and ensure timely ODPC notifications";
    if ($processorScore < 15) $recommendations[] = "Review and document all data processor contracts and security assessments";
    if ($odpcScore < 15) $recommendations[] = "Complete ODPC registration and appoint a qualified Data Protection Officer";
    if ($dataProtectionScore < 15) $recommendations[] = "Implement essential security measures: encryption, MFA, access controls, and backups";
    if (empty($recommendations)) $recommendations[] = "Your organization shows good compliance. Maintain and review regularly.";
    
    $recText = implode("\n", $recommendations);
    
    // =============================================
    // SAVE TO DATABASE
    // =============================================
    // Ensure table exists
    $pdo->exec("CREATE TABLE IF NOT EXISTS compliance_scores (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        organization_id INTEGER NOT NULL,
        overall_score INTEGER DEFAULT 0,
        dpia_score INTEGER DEFAULT 0,
        breach_readiness_score INTEGER DEFAULT 0,
        processor_management_score INTEGER DEFAULT 0,
        odpc_alignment_score INTEGER DEFAULT 0,
        data_protection_score INTEGER DEFAULT 0,
        risk_level TEXT DEFAULT 'Medium',
        assessment_date TEXT NOT NULL,
        next_assessment_date TEXT,
        recommendations TEXT,
        assessed_by INTEGER,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");
    
    // Delete today's previous score
    $stmt = $pdo->prepare("DELETE FROM compliance_scores WHERE organization_id = ? AND assessment_date = date('now')");
    $stmt->execute([$orgId]);
    
    // Insert new score
    $stmt = $pdo->prepare("INSERT INTO compliance_scores 
        (organization_id, overall_score, dpia_score, breach_readiness_score,
         processor_management_score, odpc_alignment_score, data_protection_score,
         risk_level, assessment_date, next_assessment_date, recommendations, assessed_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, date('now'), date('now', '+3 months'), ?, ?)");
    $stmt->execute([
        $orgId, $overallScore, $dpiaScore, $breachScore,
        $processorScore, $odpcScore, $dataProtectionScore,
        $riskLevel, $recText, $userId
    ]);
    
    // Log activity
    try {
        $pdo->exec("CREATE TABLE IF NOT EXISTS user_activity (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER, action TEXT, details TEXT, ip_address TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )");
        $stmt = $pdo->prepare("INSERT INTO user_activity (user_id, action, details, ip_address, created_at) 
                               VALUES (?, 'compliance_check', ?, ?, datetime('now'))");
        $stmt->execute([$userId, "Compliance assessment: {$overallScore}% - {$riskLevel} Risk", $_SERVER['REMOTE_ADDR'] ?? '']);
    } catch (Exception $e) {}
    
    echo json_encode([
        'success' => true,
        'message' => 'Compliance score calculated successfully',
        'score' => [
            'overall' => $overallScore,
            'dpia' => $dpiaScore,
            'breach' => $breachScore,
            'processor' => $processorScore,
            'odpc' => $odpcScore,
            'data_protection' => $dataProtectionScore,
            'risk_level' => $riskLevel,
            'recommendations' => $recommendations
        ]
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Calculation failed: ' . $e->getMessage()
    ]);
}