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

$type     = $_GET['type']      ?? 'transactions';
$dateFrom = $_GET['date_from'] ?? date('Y-m-01');
$dateTo   = $_GET['date_to']   ?? date('Y-m-d');

$db = getDB();

// Build CSV
$rows = [];
$filename = 'rewards_export_' . date('Ymd') . '.csv';

if ($type === 'transactions') {
    $stmt = $db->prepare("
        SELECT t.id, t.created_at, m.name, m.card_code,
               t.amount, t.points, t.type, t.notes
        FROM transactions t
        JOIN members m ON m.id = t.member_id
        WHERE DATE(t.created_at) BETWEEN ? AND ?
        ORDER BY t.created_at DESC
    ");
    $stmt->execute([$dateFrom, $dateTo]);
    $rows = $stmt->fetchAll();
    $headers = ['ID','Date','Member','Card Code','Amount','Points','Type','Notes'];
    $mapRow  = fn($r) => [
        $r['id'], $r['created_at'], $r['name'], $r['card_code'],
        $r['amount'], $r['points'], $r['type'], $r['notes'] ?? '',
    ];

} elseif ($type === 'members') {
    $rows = $db->query("
        SELECT m.id, m.card_code, m.name, m.phone, m.address,
               COUNT(t.id) AS txn_count,
               COALESCE(SUM(CASE WHEN t.type='earn' THEN t.amount ELSE 0 END),0) AS total_spend,
               COALESCE(SUM(CASE WHEN t.type='earn' THEN t.points ELSE -t.points END),0) AS balance,
               m.registered_at, m.status
        FROM members m
        LEFT JOIN transactions t ON t.member_id = m.id
        WHERE m.name IS NOT NULL
        GROUP BY m.id
        ORDER BY m.name
    ")->fetchAll();
    $headers = ['ID','Card Code','Name','Phone','Address','Transactions','Total Spend','Points Balance','Registered','Status'];
    $mapRow  = fn($r) => [
        $r['id'], $r['card_code'], $r['name'], $r['phone'], $r['address'],
        $r['txn_count'], $r['total_spend'], max(0,(int)$r['balance']),
        $r['registered_at'], $r['status'],
    ];

} else { // points
    $rows = $db->query("
        SELECT m.name, m.card_code,
               COALESCE(SUM(CASE WHEN t.type='earn' THEN t.points ELSE 0 END),0) AS earned,
               COALESCE(SUM(CASE WHEN t.type='redeem' THEN t.points ELSE 0 END),0) AS redeemed,
               COALESCE(SUM(CASE WHEN t.type='earn' THEN t.points ELSE -t.points END),0) AS balance,
               COALESCE(SUM(CASE WHEN t.type='earn' THEN t.amount ELSE 0 END),0) AS total_spend
        FROM members m
        LEFT JOIN transactions t ON t.member_id = m.id
        WHERE m.name IS NOT NULL
        GROUP BY m.id ORDER BY earned DESC
    ")->fetchAll();
    $headers = ['Name','Card Code','Earned','Redeemed','Balance','Total Spend'];
    $mapRow  = fn($r) => [
        $r['name'], $r['card_code'], $r['earned'], $r['redeemed'],
        max(0,(int)$r['balance']), $r['total_spend'],
    ];
}

// Output CSV
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');

$fh = fopen('php://output', 'w');
// BOM for Excel UTF-8
fputs($fh, "\xEF\xBB\xBF");
fputcsv($fh, $headers);
foreach ($rows as $r) {
    fputcsv($fh, $mapRow($r));
}
fclose($fh);
exit;
