<?php
$pageTitle  = 'Transactions';
$activePage = 'transactions';

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/../db.php';

$perPage    = 25;
$page       = max(1, (int)($_GET['page'] ?? 1));
$typeFilter = $_GET['type'] ?? '';
$chatFilter = trim($_GET['chat'] ?? '');
$offset     = ($page - 1) * $perPage;

$where  = [];
$params = [];
if ($typeFilter) {
    $where[]  = 'ct.type = ?';
    $params[] = $typeFilter;
}
if ($chatFilter) {
    $where[]  = 'ct.chat_id = ?';
    $params[] = $chatFilter;
}
$whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// Total count
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM credit_transactions ct {$whereSQL}");
$countStmt->execute($params);
$total      = (int)$countStmt->fetchColumn();
$totalPages = (int)ceil($total / $perPage);

// Rows
$listStmt = $pdo->prepare("
    SELECT ct.*, u.first_name
    FROM credit_transactions ct
    LEFT JOIN users u ON u.chat_id = ct.chat_id
    {$whereSQL}
    ORDER BY ct.id DESC
    LIMIT ? OFFSET ?
");
$listStmt->execute(array_merge($params, [$perPage, $offset]));
$txns = $listStmt->fetchAll(PDO::FETCH_ASSOC);

// Summary stats (for the current filter)
$sumStmt = $pdo->prepare("
    SELECT
        SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) AS total_in,
        ABS(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END)) AS total_out
    FROM credit_transactions ct {$whereSQL}
");
$sumStmt->execute($params);
$summary = $sumStmt->fetch(PDO::FETCH_ASSOC);

$types = ['signup_bonus', 'plan_generation', 'manual_topup', 'admin_grant'];

$badgeClass = [
    'signup_bonus'    => 'bg-success-subtle text-success',
    'plan_generation' => 'bg-danger-subtle text-danger',
    'admin_grant'     => 'bg-primary-subtle text-primary',
    'manual_topup'    => 'bg-info-subtle text-info',
];

$pageQuery = http_build_query(['type' => $typeFilter, 'chat' => $chatFilter]);

require_once __DIR__ . '/_header.php';
?>

<div class="page-header d-flex justify-content-between align-items-center">
    <h4 class="fw-bold mb-0">
        Transactions
        <span class="badge bg-primary ms-1" style="font-size:.65rem;vertical-align:middle"><?= number_format($total) ?></span>
    </h4>
</div>

<!-- Summary mini-cards -->
<div class="row g-3 mb-3">
    <div class="col-sm-6 col-md-3">
        <div class="card stat-card">
            <div class="card-body py-3 d-flex align-items-center gap-3">
                <div class="icon-box bg-success bg-opacity-10 text-success">➕</div>
                <div>
                    <div class="fw-bold fs-5 lh-1 text-success">+<?= number_format($summary['total_in'] ?? 0) ?></div>
                    <div class="text-muted" style="font-size:.75rem">Credits In</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-md-3">
        <div class="card stat-card">
            <div class="card-body py-3 d-flex align-items-center gap-3">
                <div class="icon-box bg-danger bg-opacity-10 text-danger">➖</div>
                <div>
                    <div class="fw-bold fs-5 lh-1 text-danger">-<?= number_format($summary['total_out'] ?? 0) ?></div>
                    <div class="text-muted" style="font-size:.75rem">Credits Out</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="card table-card mb-3">
    <div class="card-body py-2">
        <form method="GET" class="d-flex gap-2 flex-wrap align-items-end">
            <div>
                <label class="form-label small mb-1">Chat ID</label>
                <input type="text" name="chat" class="form-control" placeholder="Filter by chat ID…"
                       value="<?= htmlspecialchars($chatFilter) ?>" style="width:180px">
            </div>
            <div>
                <label class="form-label small mb-1">Type</label>
                <select name="type" class="form-select" style="width:180px">
                    <option value="">All Types</option>
                    <?php foreach ($types as $t): ?>
                    <option value="<?= $t ?>" <?= $typeFilter === $t ? 'selected' : '' ?>><?= $t ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button class="btn btn-primary px-3" type="submit"><i class="bi bi-funnel me-1"></i>Filter</button>
            <?php if ($typeFilter || $chatFilter): ?>
            <a href="transactions.php" class="btn btn-outline-secondary">Clear</a>
            <?php endif; ?>
        </form>
    </div>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover mb-0">
            <thead>
                <tr>
                    <th>#</th>
                    <th>User</th>
                    <th>Amount</th>
                    <th>Type</th>
                    <th>Description</th>
                    <th>Date</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($txns as $tx): ?>
            <tr>
                <td class="text-muted" style="font-size:.75rem"><?= $tx['id'] ?></td>
                <td>
                    <a href="user.php?id=<?= $tx['chat_id'] ?>" class="text-decoration-none fw-semibold text-dark">
                        <?= htmlspecialchars($tx['first_name'] ?? 'User') ?>
                    </a>
                    <div class="text-muted" style="font-size:.7rem"><?= $tx['chat_id'] ?></div>
                </td>
                <td class="fw-bold <?= $tx['amount'] > 0 ? 'text-success' : 'text-danger' ?>">
                    <?= $tx['amount'] > 0 ? '+' : '' ?><?= $tx['amount'] ?>
                </td>
                <td>
                    <span class="badge <?= $badgeClass[$tx['type']] ?? 'bg-secondary-subtle text-secondary' ?>" style="font-size:.7rem">
                        <?= htmlspecialchars($tx['type']) ?>
                    </span>
                </td>
                <td class="text-muted" style="font-size:.8rem"><?= htmlspecialchars($tx['description'] ?? '') ?></td>
                <td class="text-muted" style="font-size:.75rem"><?= date('d M Y, H:i', strtotime($tx['created_at'])) ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($txns)): ?>
            <tr><td colspan="6" class="text-center text-muted py-4">No transactions match the current filter.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="card-footer bg-white border-0 py-2">
        <nav>
            <ul class="pagination pagination-sm mb-0 justify-content-end flex-wrap gap-1">
            <?php for ($i = 1; $i <= min($totalPages, 30); $i++): ?>
                <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                    <a class="page-link" href="?<?= $pageQuery ?>&page=<?= $i ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
</div>

<?php require_once __DIR__ . '/_footer.php'; ?>
