<?php
require_once '../config/database.php';
require_once '../config/auth_enhanced.php';

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized access']);
    exit;
}

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

try {
    $database = new Database();
    $pdo = $database->getConnection();
    
    $start_date = $_GET['start_date'] ?? date('Y-m-01');
    $end_date = $_GET['end_date'] ?? date('Y-m-t');
    
    // Get membership data by month and type
    $stmt = $pdo->prepare("
        SELECT 
            DATE_FORMAT(created_at, '%Y-%m') as month,
            membership_type,
            COUNT(*) as count
        FROM members 
        WHERE created_at BETWEEN ? AND ?
        AND status = 'approved'
        GROUP BY DATE_FORMAT(created_at, '%Y-%m'), membership_type
        ORDER BY month ASC, membership_type ASC
    ");
    $stmt->execute([$start_date, $end_date]);
    $membership_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Organize data for chart
    $months = [];
    $individual_counts = [];
    $family_counts = [];
    
    // Get all unique months
    $month_data = [];
    foreach ($membership_data as $row) {
        $month = $row['month'];
        if (!isset($month_data[$month])) {
            $month_data[$month] = ['individual' => 0, 'family' => 0];
        }
        $month_data[$month][strtolower($row['membership_type'])] = (int)$row['count'];
    }
    
    // Format for Chart.js
    foreach ($month_data as $month => $counts) {
        $months[] = date('M Y', strtotime($month . '-01'));
        $individual_counts[] = $counts['individual'];
        $family_counts[] = $counts['family'];
    }
    
    echo json_encode([
        'success' => true,
        'data' => [
            'labels' => $months,
            'values' => array_map(function($i, $f) { return $i + $f; }, $individual_counts, $family_counts)
        ],
        'chart_data' => [
            'labels' => $months,
            'datasets' => [
                [
                    'label' => 'Individual Members',
                    'data' => $individual_counts,
                    'backgroundColor' => 'rgba(54, 162, 235, 0.6)',
                    'borderColor' => 'rgba(54, 162, 235, 1)',
                    'borderWidth' => 2
                ],
                [
                    'label' => 'Family Members',
                    'data' => $family_counts,
                    'backgroundColor' => 'rgba(255, 99, 132, 0.6)',
                    'borderColor' => 'rgba(255, 99, 132, 1)',
                    'borderWidth' => 2
                ]
            ]
        ]
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>
