<?php
/**
 * Get Dashboard Statistics
 * AJAX endpoint for dashboard data
 */

header('Content-Type: application/json');
require_once '../layouts/dbconn.php';
require_once '../includes/auth.php';

// Check authentication
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

try {
    $stats = [];
    
    // Total Schemes
    $schemesSql = "SELECT COUNT(*) as total FROM pension_schemes WHERE is_active = 1";
    $result = $conn->query($schemesSql);
    $stats['total_schemes'] = $result->fetch_assoc()['total'];
    
    // Total Members
    $membersSql = "SELECT COUNT(*) as total FROM members WHERE is_active = 1";
    $result = $conn->query($membersSql);
    $stats['total_members'] = $result->fetch_assoc()['total'];
    
    // Total Life Policies
    $policiesSql = "SELECT COUNT(*) as total FROM life_policies WHERE policy_status = 'ACTIVE'";
    $result = $conn->query($policiesSql);
    $stats['total_policies'] = $result->fetch_assoc()['total'];
    
    // Pending Claims
    $claimsSql = "SELECT COUNT(*) as total FROM life_claims WHERE claim_status = 'PENDING'";
    $result = $conn->query($claimsSql);
    $stats['pending_claims'] = $result->fetch_assoc()['total'];
    
    // Total Contributions (this month)
    $contributionsSql = "SELECT COALESCE(SUM(contribution_amount), 0) as total 
                         FROM contributions 
                         WHERE status = 'PROCESSED' 
                         AND MONTH(contribution_period) = MONTH(CURDATE())
                         AND YEAR(contribution_period) = YEAR(CURDATE())";
    $result = $conn->query($contributionsSql);
    $stats['monthly_contributions'] = $result->fetch_assoc()['total'];
    
    // Total Withdrawals (this month)
    $withdrawalsSql = "SELECT COALESCE(SUM(calculated_amount), 0) as total 
                       FROM withdrawal_requests 
                       WHERE status = 'PROCESSED' 
                       AND MONTH(processed_at) = MONTH(CURDATE())
                       AND YEAR(processed_at) = YEAR(CURDATE())";
    $result = $conn->query($withdrawalsSql);
    $stats['monthly_withdrawals'] = $result->fetch_assoc()['total'];
    
    echo json_encode([
        'success' => true,
        'data' => $stats
    ]);
    
} catch (Exception $e) {
    error_log("get_dashboard_stats Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to load statistics'
    ]);
}
