<?php
if (!isset($data_admin['agent_level']) || $data_admin['agent_level'] !== "admin") {
    header("Location: ./");
    exit();
}

$pendingTopupCount = 0;
$pendingTopupAmount = 0;
$successTopupCount = 0;
$successTopupAmount = 0;

$pendingSummaryQuery = mysqli_query($call, "SELECT COUNT(*) AS total, COALESCE(SUM(amount), 0) AS amount FROM tb_balance WHERE status = 'Pending'");
if ($pendingSummaryQuery) {
    $pendingSummary = mysqli_fetch_assoc($pendingSummaryQuery) ?: [];
    $pendingTopupCount = (int)($pendingSummary['total'] ?? 0);
    $pendingTopupAmount = (float)($pendingSummary['amount'] ?? 0);
}

$successSummaryQuery = mysqli_query($call, "SELECT COUNT(*) AS total, COALESCE(SUM(harga), 0) AS amount FROM tb_topup WHERE status = 'Success' AND COALESCE(metode, '') <> 'INJECTED'");
if ($successSummaryQuery) {
    $successSummary = mysqli_fetch_assoc($successSummaryQuery) ?: [];
    $successTopupCount = (int)($successSummary['total'] ?? 0);
    $successTopupAmount = (float)($successSummary['amount'] ?? 0);
}
?>

<div class="app-page-shell">
<div class="row g-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title mb-1">Proses Topup</h4>
                <p class="text-muted mb-0">Daftar permintaan topup yang masih pending.</p>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="table-member-list" class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>TrxID</th>
                                <th>Agent Name</th>
                                <th>Amount</th>
                                <th>Coin</th>
                                <th>Status</th>
                                <th>Metode</th>
                                <th>Date</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $cek_status = mysqli_query($call, "SELECT * FROM tb_balance WHERE status = 'Pending'");
                            $data_members = [];

                            while ($row = mysqli_fetch_array($cek_status)) {
                                $data_members[] = $row;
                            }

                            foreach ($data_members as $data_member) {
                            ?>
                            <tr>
                                <td><?= htmlspecialchars($data_member['trxid'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td><?= htmlspecialchars(topup_agent_name($call, (string)$data_member['agent_code']), ENT_QUOTES, 'UTF-8') ?></td>
                                <td class="text-end"><?= number_format($data_member['amount']) ?></td>
                                <td class="text-end"><?= number_format($data_member['balance']) ?></td>
                                <?php
                                    $statusValue = strtoupper((string)($data_member['status'] ?? ''));
                                    $statusClass = $statusValue === 'PENDING' ? 'bg-light-warning text-warning' : 'bg-light-secondary text-secondary';
                                ?>
                                <td><span class="badge <?= $statusClass ?>"><?= htmlspecialchars($statusValue, ENT_QUOTES, 'UTF-8') ?></span></td>
                                <td><?= htmlspecialchars($data_member['metode'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td class="text-nowrap"><?= date("d-m-Y H:i:s", strtotime($data_member['created'])) ?></td>
                                <td>
                                    <button class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#updateModal-<?= $data_member['id'] ?>">Update</button>
                                </td>
                            </tr>
                            <?php
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Modal Section -->
<div class="row g-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
                    <div>
                        <h4 class="card-title mb-1">History Topup</h4>
                        <p class="text-muted mb-0">Riwayat transaksi topup.</p>
                    </div>
                    <button class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#totalTransaksiModal">
                        Lihat Total Transaksi
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="dataTableExample" class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>Trx ID</th>
                                <th>Agent Name</th>
                                <th>Amount</th>
                                <th>Harga</th>
                                <th>Metode</th>
                                <th>To Rekening</th>
                                <th>No Rekening</th>
                                <th>Tanggal</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody id="topupTable">
                            <?php
                            $query = "
                                SELECT tb_topup.*, tb_agent.agent_name 
                                FROM tb_topup 
                                LEFT JOIN tb_agent ON tb_topup.agent_code = tb_agent.agent_name OR tb_topup.agent_code = tb_agent.agent_code 
                                WHERE COALESCE(tb_topup.metode, '') <> 'INJECTED'
                                ORDER BY tb_topup.tanggal DESC
                            ";
                            $result = mysqli_query($call, $query);

                            while ($row = mysqli_fetch_assoc($result)) {
                            ?>
                                <tr>
                                    <td><?= htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= htmlspecialchars($row['agent_name'] ?? '-', ENT_QUOTES, 'UTF-8') ?></td>
                                    <td class="amount text-end" data-amount="<?= $row['amount'] ?>">
                                        <?= number_format($row['amount'], 0, ',', '.') ?>
                                    </td>
                                    <td class="harga text-end"><?= number_format($row['harga'], 0, ',', '.') ?></td>
                                    <td><?= htmlspecialchars($row['metode'], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= htmlspecialchars($row['nama_rekening'], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= htmlspecialchars($row['nomor_rekening'], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td class="text-nowrap"><?= htmlspecialchars($row['tanggal'], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td>
                                        <?php
                                        $historyStatus = (string)($row['status'] ?? '');
                                        $historyStatusClass = $historyStatus === 'Success'
                                            ? 'bg-light-success text-success'
                                            : ($historyStatus === 'Cancel' ? 'bg-light-danger text-danger' : 'bg-light-warning text-warning');
                                        ?>
                                        <span class="badge <?= $historyStatusClass ?>"><?= htmlspecialchars($historyStatus, ENT_QUOTES, 'UTF-8') ?></span>
                                    </td>
                                </tr>
                            <?php
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
<div class="modal fade" id="totalTransaksiModal" tabindex="-1" role="dialog" aria-labelledby="totalTransaksiLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="totalTransaksiLabel">Total Transaksi</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="mb-3">
                        <label class="form-label">Dari Tanggal</label>
                        <input type="text" id="startDate" class="form-control datepicker">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Sampai Tanggal</label>
                        <input type="text" id="endDate" class="form-control datepicker">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Total Amount (Coin)</label>
                        <input type="text" id="totalAmount" class="form-control" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Total Harga</label>
                        <input type="text" id="totalHarga" class="form-control" readonly>
                    </div>
                    <button type="button" id="filterButton" class="btn btn-primary">Filter</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php foreach ($data_members as $data_member) { ?>
<div class="modal fade" id="updateModal-<?= $data_member['id'] ?>" tabindex="-1" role="dialog" aria-labelledby="modalLabel-<?= $data_member['id'] ?>" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalLabel-<?= $data_member['id'] ?>">Proses <?= strtoupper(htmlspecialchars(topup_agent_name($call, (string)$data_member['agent_code']), ENT_QUOTES, 'UTF-8')) ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form action="function/prosesTopup.php" method="POST">
                    <input type="hidden" name="id" value="<?= $data_member['id'] ?>">
                    <div class="mb-3">
                        <label for="agent-<?= $data_member['id'] ?>" class="form-label">Agent</label>
                        <input type="text" id="agent-<?= $data_member['id'] ?>" name="agent" class="form-control" value="<?= htmlspecialchars(topup_agent_name($call, (string)$data_member['agent_code']), ENT_QUOTES, 'UTF-8') ?>" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Balance</label>
                        <input type="number" id="<?= $data_member['balance'] ?>" name="balance" class="form-control" value="<?= $data_member['balance'] ?>" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Price</label>
                        <input type="number" id="<?= $data_member['amount'] ?>" name="price" class="form-control" value="<?= $data_member['amount'] ?>" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Bank</label>
                        <input type="text" id="<?= $data_member['metode'] ?>" name="metode" class="form-control" value="<?= $data_member['metode'] ?>" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nama Rekening</label>
                        <input type="text" id="<?= $data_member['nama_rekening'] ?>" name="nama_rekening" class="form-control" value="<?= $data_member['nama_rekening'] ?>" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nomor Rekening</label>
                        <input type="text" id="<?= $data_member['nomor_rekening'] ?>" name="nomor_rekening" class="form-control" value="<?= $data_member['nomor_rekening'] ?>" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Date</label>
                        <input type="text" id="<?= date("d-m-Y H:i:s", strtotime($data_member['created'])) ?>" name="date" class="form-control" value="<?= date("d-m-Y H:i:s", strtotime($data_member['created'])) ?>" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="action-<?= $data_member['id'] ?>" class="form-label">Action</label>
                        <select id="action-<?= $data_member['id'] ?>" name="action" class="form-select">
                            <option value="Success">Success</option>
                            <option value="Cancel">Cancel</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <input type="submit" name="proses" class="btn btn-success w-100" value="Edit">
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php } ?>
