<?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 renewal statistics for the last 12 months
    $stmt = $conn->prepare("
        SELECT 
            DATE_FORMAT(renewed_by, '%Y-%m') as month,
            COUNT(*) as count
        FROM membership_renewals
        WHERE created_at >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH)
        GROUP BY DATE_FORMAT(created_at, '%Y-%m')
        ORDER BY month ASC
    ");
    $stmt->execute();
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format the data for Chart.js
    $labels = [];
    $data = [];
    
    // Create an array of all months in the last year
    $date = new DateTime();
    $date->modify('-11 months');
    
    for ($i = 0; $i < 12; $i++) {
        $month_key = $date->format('Y-m');
        $month_label = $date->format('M Y');
        
        $labels[] = $month_label;
        
        // Find if we have data for this month
        $month_data = array_filter($results, function($item) use ($month_key) {
            return $item['month'] === $month_key;
        });
        
        if (!empty($month_data)) {
            $month_data = reset($month_data);
            $data[] = (int)$month_data['count'];
        } else {
            $data[] = 0;
        }
        
        $date->modify('+1 month');
    }
    
    echo json_encode([
        'success' => true,
        'labels' => $labels,
        'data' => $data
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
