<?php require_once '../includes/header.php';

$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

$typeFilter = $_GET['type'] ?? '';
$userId = $_GET['user_id'] ?? '';
$search = trim($_GET['search'] ?? '');
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? '';

$where = "WHERE 1=1";
$params = [];

if ($typeFilter !== '') {
    $where .= " AND wt.type = :type";
    $params[':type'] = $typeFilter;
}
if ($userId !== '') {
    $where .= " AND wt.user_id = :uid";
    $params[':uid'] = (int)$userId;
}
if ($search !== '') {
    // search by description or reseller name
    $where .= " AND (wt.description LIKE :search OR u.reseller_name LIKE :search2)";
    $params[':search'] = "%$search%";
    $params[':search2'] = "%$search%";
}
if ($dateFrom) {
    $where .= " AND DATE(wt.created_at) >= :date_from";
    $params[':date_from'] = $dateFrom;
}
if ($dateTo) {
    $where .= " AND DATE(wt.created_at) <= :date_to";
    $params[':date_to'] = $dateTo;
}

$countStmt = $pdo->prepare("
    SELECT COUNT(*) FROM wallet_transactions wt
    LEFT JOIN users u ON wt.user_id = u.id
    $where
");
$countStmt->execute($params);
$total = $countStmt->fetchColumn();
$totalPages = ceil($total / $perPage);

$txnsStmt = $pdo->prepare("
    SELECT wt.*, u.reseller_name, u.phone
    FROM wallet_transactions wt
    LEFT JOIN users u ON wt.user_id = u.id
    $where
    ORDER BY wt.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$txnsStmt->execute($params);
$transactions = $txnsStmt->fetchAll();

// Get user list for filter dropdown
$usersList = $pdo->query("SELECT id, reseller_name FROM users ORDER BY reseller_name")->fetchAll();
?>

<h1 class="h2 mb-4">Wallet Transactions</h1>

<?php $flash = getFlash(); if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show" role="alert">
    <?= htmlspecialchars($flash['message']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="card shadow-sm mb-4">
    <div class="card-body">
        <form method="GET" class="row g-2">
            <div class="col-md-2">
                <label class="form-label">User</label>
                <select name="user_id" class="form-select">
                    <option value="">All</option>
                    <?php foreach ($usersList as $u): ?>
                        <option value="<?= $u['id'] ?>" <?= $userId == $u['id'] ? 'selected' : '' ?>><?= htmlspecialchars($u['reseller_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Type</label>
                <select name="type" class="form-select">
                    <option value="">All</option>
                    <option value="credit" <?= $typeFilter === 'credit' ? 'selected' : '' ?>>Credit</option>
                    <option value="debit" <?= $typeFilter === 'debit' ? 'selected' : '' ?>>Debit</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Date From</label>
                <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($dateFrom) ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Date To</label>
                <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($dateTo) ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Search</label>
                <input type="text" name="search" class="form-control" placeholder="Desc / Name" value="<?= htmlspecialchars($search) ?>">
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100 me-1">Filter</button>
                <a href="wallet.php" class="btn btn-outline-secondary w-100">Reset</a>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Reseller</th>
                        <th>Type</th>
                        <th>Amount</th>
                        <th>Balance After</th>
                        <th>Description</th>
                        <th>Date</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($transactions)): ?>
                    <tr><td colspan="7" class="text-center py-3">No transactions found.</td></tr>
                <?php else: foreach ($transactions as $txn): ?>
                    <tr>
                        <td><?= $txn['id'] ?></td>
                        <td>
                            <?= htmlspecialchars($txn['reseller_name'] ?? 'N/A') ?>
                            <br><small class="text-muted"><?= htmlspecialchars($txn['phone'] ?? '') ?></small>
                        </td>
                        <td>
                            <span class="badge bg-<?= $txn['type'] === 'credit' ? 'success' : 'danger' ?>"><?= $txn['type'] ?></span>
                        </td>
                        <td class="text-<?= $txn['type'] === 'credit' ? 'success' : 'danger' ?>">
                            <?= $txn['type'] === 'debit' ? '-' : '+' ?>৳<?= number_format($txn['amount'], 2) ?>
                        </td>
                        <td>৳<?= number_format($txn['balance_after'], 2) ?></td>
                        <td><?= htmlspecialchars($txn['description'] ?? '') ?></td>
                        <td><?= date('d M Y H:i', strtotime($txn['created_at'])) ?></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if ($totalPages > 1): ?>
<nav class="mt-4">
    <ul class="pagination justify-content-center">
        <li class="page-item <?= $page == 1 ? 'disabled' : '' ?>">
            <a class="page-link" href="?page=<?= $page-1 ?>&type=<?= $typeFilter ?>&user_id=<?= $userId ?>&search=<?= urlencode($search) ?>&date_from=<?= $dateFrom ?>&date_to=<?= $dateTo ?>">&laquo;</a>
        </li>
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                <a class="page-link" href="?page=<?= $i ?>&type=<?= $typeFilter ?>&user_id=<?= $userId ?>&search=<?= urlencode($search) ?>&date_from=<?= $dateFrom ?>&date_to=<?= $dateTo ?>"><?= $i ?></a>
            </li>
        <?php endfor; ?>
        <li class="page-item <?= $page == $totalPages ? 'disabled' : '' ?>">
            <a class="page-link" href="?page=<?= $page+1 ?>&type=<?= $typeFilter ?>&user_id=<?= $userId ?>&search=<?= urlencode($search) ?>&date_from=<?= $dateFrom ?>&date_to=<?= $dateTo ?>">&raquo;</a>
        </li>
    </ul>
</nav>
<?php endif; ?>

<?php require_once '../includes/footer.php'; ?>