<?php
/**
 * Analytics API Endpoints
 * v1/analytics
 */

global $method, $input, $queryParams, $apiResponse, $user, $conn, $segments;

// Only admins and authorized roles can access analytics
if (!in_array($user['role_name'], ['ADMIN', 'TRUSTEE'])) {
    $apiResponse->error('Access denied', 403);
}

switch ($method) {
    case 'GET':
        $type = $queryParams['type'] ?? 'dashboard';
        
        switch ($type) {
            case 'dashboard':
                // Dashboard statistics
                $stats = [
                    'total_members' => $conn->query("SELECT COUNT(*) FROM members WHERE is_active = 1")->fetch_row()[0],
                    'total_schemes' => $conn->query("SELECT COUNT(*) FROM pension_schemes WHERE is_active = 1")->fetch_row()[0],
                    'total_policies' => $conn->query("SELECT COUNT(*) FROM life_policies WHERE policy_status = 'ACTIVE'")->fetch_row()[0],
                    'total_contributions' => $conn->query("SELECT SUM(contribution_amount) FROM contributions WHERE status = 'PROCESSED'")->fetch_row()[0] ?? 0,
                    'total_withdrawals' => $conn->query("SELECT SUM(calculated_amount) FROM withdrawal_requests WHERE status = 'PROCESSED'")->fetch_row()[0] ?? 0,
                    'pending_claims' => $conn->query("SELECT COUNT(*) FROM life_claims WHERE claim_status = 'PENDING'")->fetch_row()[0]
                ];
                
                $apiResponse->success($stats, 'Dashboard statistics retrieved');
                break;
                
            case 'contributions_trend':
                // Contribution trends over time
                $period = $queryParams['period'] ?? '12'; // months
                $sql = "SELECT DATE_FORMAT(contribution_period, '%Y-%m') as period,
                       SUM(contribution_amount) as total
                       FROM contributions
                       WHERE status = 'PROCESSED'
                       AND contribution_period >= DATE_SUB(CURDATE(), INTERVAL ? MONTH)
                       GROUP BY period
                       ORDER BY period";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("i", $period);
                $stmt->execute();
                $trends = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
                
                $apiResponse->success($trends, 'Contribution trends retrieved');
                break;
                
            case 'withdrawal_analysis':
                // Withdrawal analysis
                $sql = "SELECT withdrawal_type, 
                       COUNT(*) as count,
                       SUM(calculated_amount) as total_amount
                       FROM withdrawal_requests
                       WHERE status = 'PROCESSED'
                       GROUP BY withdrawal_type";
                $result = $conn->query($sql);
                $analysis = $result->fetch_all(MYSQLI_ASSOC);
                
                $apiResponse->success($analysis, 'Withdrawal analysis retrieved');
                break;
                
            default:
                $apiResponse->error('Invalid analytics type', 400);
        }
        break;
        
    default:
        $apiResponse->error('Method not allowed', 405);
}
