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

try {
    // Include database connection
    require_once '../config/database.php';
    
    // Get database connection
    $database = new Database();
    $pdo = $database->getConnection();

    $filter = $_GET['filter'] ?? '';

    // Check if finance table exists (we use finance instead of transactions)
    $stmt = $pdo->query("SHOW TABLES LIKE 'finance'");
    if ($stmt->rowCount() == 0) {
        // Return empty data, don't create dummy data
        echo json_encode([
            'success' => true,
            'data' => [],
            'note' => 'Finance table not found'
        ]);
        exit;
    }

    // Query finance table with correct column names
    $query = "SELECT 
        id,
        member_id,
        transaction_type,
        amount,
        payment_method,
        receipt_number,
        description,
        status,
        payment_date,
        created_at
    FROM finance 
    ORDER BY created_at DESC 
    LIMIT 50";
    
    $stmt = $pdo->query($query);
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Add member names if available
    if (!empty($transactions)) {
        foreach ($transactions as &$transaction) {
            // Get member name if member_id exists
            if ($transaction['member_id']) {
                $memberStmt = $pdo->prepare("SELECT first_name, last_name FROM members WHERE id = ?");
                $memberStmt->execute([$transaction['member_id']]);
                $member = $memberStmt->fetch(PDO::FETCH_ASSOC);
                if ($member) {
                    $transaction['member_name'] = $member['first_name'] . ' ' . $member['last_name'];
                } else {
                    $transaction['member_name'] = 'Unknown Member';
                }
            } else {
                $transaction['member_name'] = 'N/A';
            }
        }
    }

    echo json_encode([
        'success' => true,
        'data' => $transactions,
        'count' => count($transactions)
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage(),
        'data' => []
    ]);
}
?>
