<?php
// ============================================================
//  payfast-itn-check.php — diagnostic only, DELETE after use
// ============================================================
//
//  Visit this URL to see:
//    1. Whether payfast-itn.php is reachable
//    2. Recent ITN rows in the payments table
//    3. Recent entries in mailchimp.log
//
//  Only accessible to logged-in admins.
//
// ============================================================

require_once __DIR__ . '/includes/auth.php';
auth_require_admin();

header('Content-Type: text/plain; charset=utf-8');

echo "=== PayFast ITN Diagnostic ===\n\n";
echo "ITN URL: " . SITE_URL . "/payfast-itn.php\n";
echo "Sandbox: " . (PF_SANDBOX ? 'YES' : 'no') . "\n";
echo "Passphrase set: " . (PF_PASSPHRASE ? 'yes (' . strlen(PF_PASSPHRASE) . ' chars)' : 'NO — empty') . "\n\n";

echo "=== Recent rows in payments table ===\n";
try {
    $rows = db_all('SELECT id, pf_payment_id, payment_status, member_id, amount_gross_cents,
                           signature_ok, ip_ok, processed, created_at
                      FROM payments ORDER BY created_at DESC LIMIT 10');
    if (empty($rows)) {
        echo "(no rows — ITN has never reached this server)\n";
    } else {
        foreach ($rows as $r) {
            printf(
                "#%d  %s  status=%-12s  member=%-4s  amount=R%-8s  sig=%s ip=%s processed=%s  %s\n",
                $r['id'],
                $r['pf_payment_id'] ?? '(no pf_id)',
                $r['payment_status'],
                $r['member_id'] ?? '?',
                number_format((int)$r['amount_gross_cents'] / 100, 2),
                $r['signature_ok'] ? 'ok' : 'FAIL',
                $r['ip_ok']        ? 'ok' : 'FAIL',
                $r['processed']    ? 'yes' : 'no',
                $r['created_at']
            );
        }
    }
} catch (Throwable $e) {
    echo "DB error: " . $e->getMessage() . "\n";
}

echo "\n=== Last 20 lines of mailchimp.log ===\n";
$log = __DIR__ . '/mailchimp.log';
if (!file_exists($log)) {
    echo "(mailchimp.log does not exist yet)\n";
} else {
    $lines = file($log);
    $tail  = array_slice($lines, -20);
    foreach ($tail as $line) {
        echo $line;
    }
}

echo "\n=== Recent invoices ===\n";
try {
    $invs = db_all(
        "SELECT id, member_id, number, description, amount_cents, status, issued_at, paid_at
           FROM invoices ORDER BY id DESC LIMIT 10"
    );
    foreach ($invs as $inv) {
        printf(
            "#%d  m=%-3s  %-22s  R%-8s  %-8s  issued=%s  paid=%s\n",
            $inv['id'], $inv['member_id'],
            $inv['number'],
            number_format((int)$inv['amount_cents'] / 100, 2),
            $inv['status'],
            $inv['issued_at'],
            $inv['paid_at'] ?? '—'
        );
    }
} catch (Throwable $e) {
    echo "DB error: " . $e->getMessage() . "\n";
}