<?php
require_once __DIR__ . '/../config/pagination.php';

$memberPageAgentLevel = (string)($data_admin['agent_level'] ?? '');
$isAdminMemberPage = $memberPageAgentLevel === 'admin';
$isHeadAgentMemberPage = $memberPageAgentLevel === 'head_agent';

$providerResetFlashKeys = [
    'SGX' => 'sgx_reset_flash',
    'NexusGGR' => 'nexus_reset_flash',
];

$providerResetFlashes = [];
foreach ($providerResetFlashKeys as $providerLabel => $sessionKey) {
    $providerResetFlashes[$providerLabel] = $_SESSION[$sessionKey] ?? null;
    if ($providerResetFlashes[$providerLabel] !== null) {
        unset($_SESSION[$sessionKey]);
    }
}

$formatMemberNumber = static function ($value): string {
    return number_format((float)$value, 0, ',', '.');
};

$providerResetActions = [
    'SGX' => [
        'path' => 'function/reset_sgx_balance.php',
        'all_label' => 'Reset Semua SGX',
        'single_label' => 'Reset SGX',
        'all_confirm' => 'Yakin reset semua balance user SGX? Saldo lokal tidak akan diubah.',
        'single_confirm' => 'Reset balance SGX untuk user ini? Saldo lokal tidak akan diubah.',
        'all_button_class' => 'btn btn-outline-primary btn-sm',
        'single_button_class' => 'btn btn-outline-primary btn-sm',
    ],
    'NexusGGR' => [
        'path' => 'function/reset_nexus_balance.php',
        'all_label' => 'Reset Semua NexusGGR',
        'single_label' => 'Reset NexusGGR',
        'all_confirm' => 'Yakin reset semua balance user NexusGGR? Saldo lokal tidak akan diubah.',
        'single_confirm' => 'Reset balance NexusGGR untuk user ini? Saldo lokal tidak akan diubah.',
        'all_button_class' => 'btn btn-outline-danger btn-sm',
        'single_button_class' => 'btn btn-outline-warning btn-sm',
    ],
];

$allowedFlashTypes = ['success', 'danger', 'warning', 'info'];

$memberAgentRefsSql = agent_sql_values($call, agent_identity_values((array)$data_admin));
$memberWhereParts = [];

if ($isAdminMemberPage) {
    $memberWhereParts[] = '1=1';
} elseif ($isHeadAgentMemberPage) {
    $memberWhereParts[] = "(
        u.agent_code IN ($memberAgentRefsSql)
        OR u.agent_code IN (
            SELECT a.agent_code
            FROM tb_agent a
            WHERE a.agent_upline IN ($memberAgentRefsSql)
        )
        OR u.agent_code IN (
            SELECT a.agent_name
            FROM tb_agent a
            WHERE a.agent_upline IN ($memberAgentRefsSql)
        )
    )";
} else {
    $memberWhereParts[] = "u.agent_code IN ($memberAgentRefsSql)";
}

$memberSearch = trim((string)($_GET['member_search'] ?? ''));
if ($memberSearch !== '') {
    $memberSearchSql = legacy_escape_like($call, $memberSearch);
    $memberWhereParts[] = "(
        u.extUser LIKE '%$memberSearchSql%' ESCAPE '\\\\'
        OR u.intUser LIKE '%$memberSearchSql%' ESCAPE '\\\\'
        OR u.agent_code LIKE '%$memberSearchSql%' ESCAPE '\\\\'
        OR a.agent_name LIKE '%$memberSearchSql%' ESCAPE '\\\\'
    )";
}

$memberWhereSql = implode(' AND ', $memberWhereParts);
$memberLimit = legacy_page_limit('member_limit', 50);
$memberPage = legacy_page_number('member_page');

$memberStats = legacy_fetch_stats(
    $call,
    "SELECT COUNT(*) AS total_member, COALESCE(SUM(u.balance), 0) AS total_balance
     FROM tb_user u
     LEFT JOIN tb_agent a ON a.agent_name = u.agent_code OR a.agent_code = u.agent_code
     WHERE $memberWhereSql"
);
$memberTotal = (int)($memberStats['total_member'] ?? 0);
$memberBalanceTotal = (float)($memberStats['total_balance'] ?? 0);
$memberTotalPages = max(1, (int)ceil($memberTotal / $memberLimit));
$memberPage = min($memberPage, $memberTotalPages);
$memberOffset = max(0, ($memberPage - 1) * $memberLimit);

$cek_member = mysqli_query(
    $call,
    "SELECT u.id, u.intUser, u.extUser, u.password, u.balance, u.agent_code, u.created, u.status, COALESCE(a.agent_name, u.agent_code) AS agent_name
     FROM tb_user u
     LEFT JOIN tb_agent a ON a.agent_name = u.agent_code OR a.agent_code = u.agent_code
     WHERE $memberWhereSql
     ORDER BY u.created DESC
     LIMIT $memberOffset, $memberLimit"
);
if (!$cek_member) {
    die("Query gagal: " . mysqli_error($call));
}

$memberRows = [];

while ($memberRow = mysqli_fetch_array($cek_member)) {
    $memberRows[] = $memberRow;
}

$memberShowingStart = $memberTotal > 0 ? $memberOffset + 1 : 0;
$memberShowingEnd = min($memberOffset + count($memberRows), $memberTotal);
$memberPaginationParams = [
    'member_search' => $memberSearch,
    'member_limit' => $memberLimit,
];
?>
<div class="app-page-shell">
<div class="row g-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-start flex-wrap gap-3">
                <div>
                    <h4 class="card-title mb-1">Member</h4>
                    <p class="text-muted mb-0">Daftar member terdaftar.</p>
                </div>
                <?php if ($isAdminMemberPage): ?>
                <div class="d-flex flex-wrap gap-2">
                    <?php foreach ($providerResetActions as $providerAction): ?>
                    <form
                        action="<?= htmlspecialchars($providerAction['path'], ENT_QUOTES, 'UTF-8') ?>"
                        method="POST"
                        class="m-0"
                        onsubmit="return confirm('<?= htmlspecialchars($providerAction['all_confirm'], ENT_QUOTES, 'UTF-8') ?>');">
                        <input type="hidden" name="reset_scope" value="all">
                        <button type="submit" class="<?= htmlspecialchars($providerAction['all_button_class'], ENT_QUOTES, 'UTF-8') ?>">
                            <?= htmlspecialchars($providerAction['all_label'], ENT_QUOTES, 'UTF-8') ?>
                        </button>
                    </form>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <?php if ($isAdminMemberPage): ?>
                <div class="alert alert-light mb-4 border">
                    <div class="fw-semibold">Reset balance provider khusus admin</div>
                    <div class="small text-muted mb-0">Tombol reset hanya memengaruhi saldo provider SGX dan NexusGGR. Saldo lokal pada tabel member tidak diubah.</div>
                </div>
                <?php endif; ?>

                <?php foreach ($providerResetFlashes as $providerLabel => $providerResetFlash): ?>
                <?php if (is_array($providerResetFlash)): ?>
                <?php
                $flashType = (string)($providerResetFlash['type'] ?? 'info');
                if (!in_array($flashType, $allowedFlashTypes, true)) {
                    $flashType = 'info';
                }

                $flashScope = (string)($providerResetFlash['scope'] ?? '');
                $flashTarget = is_array($providerResetFlash['target'] ?? null) ? $providerResetFlash['target'] : [];
                $flashUser = is_array($providerResetFlash['user'] ?? null) ? $providerResetFlash['user'] : [];
                $flashUsers = is_array($providerResetFlash['users'] ?? null) ? $providerResetFlash['users'] : [];
                $flashAgentBalance = isset($providerResetFlash['agent_balance']) ? (float)$providerResetFlash['agent_balance'] : null;
                $flashTotalUsers = isset($providerResetFlash['total_users']) ? (int)$providerResetFlash['total_users'] : 0;
                $flashPreviewCount = (int)($providerResetFlash['preview_count'] ?? count($flashUsers));
                $flashUsersProcessed = array_key_exists('users_processed', $providerResetFlash) ? (int)$providerResetFlash['users_processed'] : null;
                $flashSuccessCount = array_key_exists('success_count', $providerResetFlash) ? (int)$providerResetFlash['success_count'] : null;
                $flashFailedCount = array_key_exists('failed_count', $providerResetFlash) ? (int)$providerResetFlash['failed_count'] : null;
                $flashRemaining = array_key_exists('remaining', $providerResetFlash) ? (int)$providerResetFlash['remaining'] : null;
                $flashHasMore = array_key_exists('has_more', $providerResetFlash) ? (bool)$providerResetFlash['has_more'] : null;
                $flashTotalWithdrawn = array_key_exists('total_withdrawn', $providerResetFlash) ? (float)$providerResetFlash['total_withdrawn'] : null;
                ?>
                <div class="alert alert-<?= htmlspecialchars($flashType, ENT_QUOTES, 'UTF-8') ?> mb-4">
                    <div class="fw-semibold">Reset <?= htmlspecialchars($providerLabel, ENT_QUOTES, 'UTF-8') ?></div>
                    <div><?= htmlspecialchars((string)($providerResetFlash['message'] ?? ''), ENT_QUOTES, 'UTF-8') ?></div>

                    <?php if (!empty($flashTarget)): ?>
                    <div class="mt-3 small">
                        <div>User Site: <strong><?= htmlspecialchars((string)($flashTarget['extUser'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></strong></div>
                        <div>User API: <strong><?= htmlspecialchars((string)($flashTarget['intUser'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></strong></div>
                        <div>Saldo lokal saat reset: <strong><?= $formatMemberNumber($flashTarget['local_balance'] ?? 0) ?></strong></div>
                    </div>
                    <?php endif; ?>

                    <?php if ($flashScope === 'single' && !empty($flashUser)): ?>
                    <div class="mt-3 small">
                        <div>Withdraw <?= htmlspecialchars($providerLabel, ENT_QUOTES, 'UTF-8') ?>: <strong><?= $formatMemberNumber($flashUser['withdraw_amount'] ?? 0) ?></strong></div>
                        <div>Balance provider sesudah reset: <strong><?= $formatMemberNumber($flashUser['provider_balance'] ?? 0) ?></strong></div>
                    </div>
                    <?php endif; ?>

                    <?php if ($flashAgentBalance !== null): ?>
                    <div class="mt-3 small">
                        <div>Balance agent <?= htmlspecialchars($providerLabel, ENT_QUOTES, 'UTF-8') ?>: <strong><?= $formatMemberNumber($flashAgentBalance) ?></strong></div>
                    </div>
                    <?php endif; ?>

                    <?php if ($flashTotalWithdrawn !== null): ?>
                    <div class="mt-3 small">
                        <div>Total withdraw <?= htmlspecialchars($providerLabel, ENT_QUOTES, 'UTF-8') ?>: <strong><?= $formatMemberNumber($flashTotalWithdrawn) ?></strong></div>
                    </div>
                    <?php endif; ?>

                    <?php if ($flashScope === 'all'): ?>
                    <div class="mt-3 small">
                        <?php if ($flashTotalUsers > 0): ?>
                        <div>Total user pada response <?= htmlspecialchars($providerLabel, ENT_QUOTES, 'UTF-8') ?>: <strong><?= number_format($flashTotalUsers) ?></strong></div>
                        <?php endif; ?>
                        <?php if ($flashUsersProcessed !== null): ?>
                        <div>User diproses: <strong><?= number_format($flashUsersProcessed) ?></strong></div>
                        <?php endif; ?>
                        <?php if ($flashSuccessCount !== null): ?>
                        <div>Berhasil: <strong><?= number_format($flashSuccessCount) ?></strong></div>
                        <?php endif; ?>
                        <?php if ($flashFailedCount !== null): ?>
                        <div>Gagal: <strong><?= number_format($flashFailedCount) ?></strong></div>
                        <?php endif; ?>
                        <?php if ($flashRemaining !== null): ?>
                        <div>Sisa batch: <strong><?= number_format($flashRemaining) ?></strong></div>
                        <?php endif; ?>
                        <?php if ($flashHasMore !== null): ?>
                        <div>Status batch: <strong><?= $flashHasMore ? 'Masih ada batch lanjutan' : 'Semua batch selesai' ?></strong></div>
                        <?php endif; ?>
                        <?php if ($flashPreviewCount > 0 && $flashTotalUsers > 0 && $flashPreviewCount < $flashTotalUsers): ?>
                        <div>Menampilkan <?= number_format($flashPreviewCount) ?> user pertama dari response.</div>
                        <?php endif; ?>
                    </div>

                    <?php if (!empty($flashUsers)): ?>
                    <div class="table-responsive mt-3">
                        <table class="table table-sm table-striped align-middle mb-0">
                            <thead>
                                <tr>
                                    <th>User API</th>
                                    <th class="text-end">Withdraw</th>
                                    <th class="text-end">Balance Provider</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($flashUsers as $flashUserRow): ?>
                                <tr>
                                    <td><?= htmlspecialchars((string)($flashUserRow['user_code'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td class="text-end"><?= $formatMemberNumber($flashUserRow['withdraw_amount'] ?? 0) ?></td>
                                    <td class="text-end"><?= $formatMemberNumber($flashUserRow['provider_balance'] ?? 0) ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <?php endforeach; ?>

                <form method="get" action="<?= htmlspecialchars(page_url('Member'), ENT_QUOTES, 'UTF-8') ?>" class="row g-2 align-items-end mb-3">
                    <div class="col-12 col-md-6">
                        <label class="form-label small mb-1">Cari Member</label>
                        <input type="text" name="member_search" class="form-control" value="<?= htmlspecialchars($memberSearch, ENT_QUOTES, 'UTF-8') ?>" placeholder="User site, user API, atau agent">
                    </div>
                    <div class="col-6 col-md-2">
                        <label class="form-label small mb-1">Per Halaman</label>
                        <select name="member_limit" class="form-select">
                            <?php foreach ([25, 50, 100, 200] as $limitOption): ?>
                                <option value="<?= $limitOption ?>"<?= $memberLimit === $limitOption ? ' selected' : '' ?>><?= $limitOption ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-6 col-md-2">
                        <button type="submit" class="btn btn-primary w-100">Filter</button>
                    </div>
                    <?php if ($memberSearch !== ''): ?>
                    <div class="col-12 col-md-2">
                        <a href="<?= htmlspecialchars(page_url('Member'), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-outline-secondary w-100">Reset</a>
                    </div>
                    <?php endif; ?>
                </form>

                <div class="d-flex justify-content-between flex-wrap gap-2 text-muted small mb-3">
                    <span>Menampilkan <?= number_format($memberShowingStart) ?>-<?= number_format($memberShowingEnd) ?> dari <?= number_format($memberTotal) ?> member.</span>
                    <span>Total saldo lokal: <?= $formatMemberNumber($memberBalanceTotal) ?></span>
                </div>

                <div class="table-responsive">
                    <table id="dataTableExample" data-datatable="off" class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>User Site</th>
                                <th>User API</th>
                                <th>Password API</th>
                                <th>Balance</th>
                                <th>Created</th>
                                <th>Create With</th>
                                <?php if ($isAdminMemberPage): ?>
                                <th>Action</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($memberRows as $data_member): ?>
                            <tr>
                                <td><?= htmlspecialchars($data_member['extUser'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td><?= htmlspecialchars($data_member['intUser'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td><?= htmlspecialchars($data_member['password'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td class="text-end"><?= number_format($data_member['balance'], 0, ',', '.') ?></td>
                                <td class="text-nowrap"><?= htmlspecialchars($data_member['created'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td><?= htmlspecialchars($data_member['agent_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                <?php if ($isAdminMemberPage): ?>
                                <td>
                                    <div class="d-flex flex-wrap gap-2">
                                        <?php foreach ($providerResetActions as $providerAction): ?>
                                        <form
                                            action="<?= htmlspecialchars($providerAction['path'], ENT_QUOTES, 'UTF-8') ?>"
                                            method="POST"
                                            class="m-0"
                                            onsubmit="return confirm('<?= htmlspecialchars($providerAction['single_confirm'], ENT_QUOTES, 'UTF-8') ?>');">
                                            <input type="hidden" name="reset_scope" value="single">
                                            <input type="hidden" name="user_code" value="<?= htmlspecialchars((string)$data_member['intUser'], ENT_QUOTES, 'UTF-8') ?>">
                                            <button type="submit" class="<?= htmlspecialchars($providerAction['single_button_class'], ENT_QUOTES, 'UTF-8') ?>">
                                                <?= htmlspecialchars($providerAction['single_label'], ENT_QUOTES, 'UTF-8') ?>
                                            </button>
                                        </form>
                                        <?php endforeach; ?>
                                    </div>
                                </td>
                                <?php endif; ?>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php legacy_render_pagination('Member', 'member_page', $memberPage, $memberTotalPages, $memberPaginationParams); ?>
            </div>
        </div>
    </div>
</div>
</div>
