<?php
require_once __DIR__ . '/../includes/functions.php';
requireLogin();

$db   = getDB();
$rows = $db->query("
    SELECT m.card_code, m.name, m.status, m.created_at,
           COALESCE(SUM(CASE WHEN t.type='earn' THEN t.points ELSE -t.points END), 0) AS points
    FROM members m
    LEFT JOIN transactions t ON t.member_id = m.id
    GROUP BY m.id
    ORDER BY m.created_at ASC
")->fetchAll();

$out = [];
foreach ($rows as $r) {
    $out[] = [
        'card_code'  => $r['card_code'],
        'name'       => $r['name'] ?: null,
        'status'     => $r['status'] ?? 'active',
        'points'     => (int)$r['points'],
        'created_at' => $r['created_at'],
    ];
}
jsonResponse(['success' => true, 'cards' => $out]);
