<?php
// member/api/get-dashboard-metrics.php
require_once '../../config.php';
requireLogin();

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

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

try {
    $orgId = $org['id'] ?? 0;
    
    $complianceScore = 0;
    $totalDpias = 0;
    $openBreaches = 0;
    $totalProcessors = 0;
    $pendingTasks = 0;
    $recentFiles = 0;
    $maturityScore = 0;
    
    // Get compliance score
    try {
        $stmt = $pdo->prepare("SELECT overall_score FROM compliance_scores WHERE organization_id = ? ORDER BY assessment_date DESC LIMIT 1");
        $stmt->execute([$orgId]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($result) $complianceScore = $result['overall_score'] ?? 0;
    } catch (Exception $e) {}
    
    // Get DPIAs count - using correct column names
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM dpia_records WHERE organization_id = ?");
        $stmt->execute([$orgId]);
        $totalDpias = $stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
    } catch (Exception $e) {}
    
    // Get open breaches
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM breach_reports WHERE organization_id = ? AND status NOT IN ('resolved', 'closed')");
        $stmt->execute([$orgId]);
        $openBreaches = $stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
    } catch (Exception $e) {}
    
    // Get processor assessments
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM processor_assessments WHERE organization_id = ?");
        $stmt->execute([$orgId]);
        $totalProcessors = $stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
    } catch (Exception $e) {}
    
    // Get pending tasks
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM odpc_compliance_tasks WHERE organization_id = ? AND is_completed = 0");
        $stmt->execute([$orgId]);
        $pendingTasks = $stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
    } catch (Exception $e) {}
    
    // Get files analyzed
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM file_risk_analyses WHERE user_id = ?");
        $stmt->execute([$userId]);
        $recentFiles = $stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
    } catch (Exception $e) {}
    
    // Calculate maturity score
    if ($complianceScore > 0) {
        $maturityScore = min(100, ($complianceScore * 0.4) + 
                                 ($totalDpias > 0 ? 15 : 0) + 
                                 ($totalProcessors > 0 ? 15 : 0) + 
                                 ($openBreaches == 0 ? 20 : 10) + 
                                 ($pendingTasks == 0 ? 10 : 5));
    }
    
    echo json_encode([
        'success' => true,
        'metrics' => [
            'compliance_score' => $complianceScore,
            'total_dpias' => $totalDpias,
            'open_breaches' => $openBreaches,
            'total_processors' => $totalProcessors,
            'pending_tasks' => $pendingTasks,
            'recent_files_count' => $recentFiles,
            'maturity_score' => $maturityScore,
            'last_updated' => date('Y-m-d H:i:s')
        ]
    ]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch metrics'
    ]);
}