<?php
session_start();
require_once '../config/config.php';

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

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get total members
    $stmt = $conn->prepare("SELECT COUNT(*) as total FROM members WHERE status = 'active'");
    $stmt->execute();
    $total = $stmt->fetchColumn();
    
    // Get expiring members (within 30 days)
    $stmt = $conn->prepare("
        SELECT COUNT(*) as expiring 
        FROM members 
        WHERE status = 'active' 
        AND membership_expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
    ");
    $stmt->execute();
    $expiring = $stmt->fetchColumn();
    
    // Get expired members
    $stmt = $conn->prepare("
        SELECT COUNT(*) as expired 
        FROM members 
        WHERE status = 'active' 
        AND membership_expiry_date < CURDATE()
    ");
    $stmt->execute();
    $expired = $stmt->fetchColumn();
    
    // Get renewed members this month
    $stmt = $conn->prepare("
        SELECT COUNT(*) as renewed 
        FROM members 
        WHERE status = 'active' 
        AND membership_expiry_date >= CURDATE()
        AND created_at >= DATE_FORMAT(CURDATE(), '%Y-%m-01')
    ");
    $stmt->execute();
    $renewed = $stmt->fetchColumn();
    
    echo json_encode([
        'success' => true,
        'stats' => [
            'total' => $total,
            'expiring' => $expiring,
            'expired' => $expired,
            'renewed' => $renewed
        ]
    ]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
