<?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 {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $start_date = $_GET['start_date'] ?? date('Y-m-01');
    $end_date = $_GET['end_date'] ?? date('Y-m-t');
    
    // Members summary
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_members,
            COUNT(CASE WHEN created_at BETWEEN ? AND ? THEN 1 END) as new_members,
            COUNT(CASE WHEN status = 'approved' THEN 1 END) as active_members,
            COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_members
        FROM members
    ");
    $stmt->execute([$start_date, $end_date]);
    $memberStats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Events summary
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_events,
            COUNT(CASE WHEN date BETWEEN ? AND ? THEN 1 END) as events_in_period,
            COALESCE(SUM(CASE WHEN date BETWEEN ? AND ? THEN 1 ELSE 0 END), 0) as completed_events
        FROM events
    ");
    $stmt->execute([$start_date, $end_date, $start_date, $end_date]);
    $eventStats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Financial summary
    $stmt = $pdo->prepare("
        SELECT 
            COALESCE(SUM(CASE WHEN type = 'income' AND created_at BETWEEN ? AND ? THEN amount ELSE 0 END), 0) as total_income,
            COALESCE(SUM(CASE WHEN type = 'expense' AND created_at BETWEEN ? AND ? THEN amount ELSE 0 END), 0) as total_expenses,
            COUNT(CASE WHEN created_at BETWEEN ? AND ? THEN 1 END) as total_transactions
        FROM transactions
    ");
    $stmt->execute([$start_date, $end_date, $start_date, $end_date, $start_date, $end_date]);
    $financialStats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Event registrations summary
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_registrations,
            COUNT(CASE WHEN er.created_at BETWEEN ? AND ? THEN 1 END) as new_registrations,
            COALESCE(SUM(CASE WHEN er.payment_status = 'paid' AND er.created_at BETWEEN ? AND ? THEN er.amount_paid ELSE 0 END), 0) as registration_revenue
        FROM event_registrations er
    ");
    $stmt->execute([$start_date, $end_date, $start_date, $end_date]);
    $registrationStats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $netIncome = $financialStats['total_income'] - $financialStats['total_expenses'];
    
    echo json_encode([
        'period' => [
            'start_date' => $start_date,
            'end_date' => $end_date
        ],
        'members' => $memberStats,
        'events' => $eventStats,
        'finances' => array_merge($financialStats, ['net_income' => $netIncome]),
        'registrations' => $registrationStats
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>
