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

$rtpPageAgentLevel = (string)($data_admin['agent_level'] ?? '');
$rtpPageAgentName = agent_public_name((array)$data_admin);

if ($rtpPageAgentName === '' || !in_array($rtpPageAgentLevel, ['admin', 'head_agent', 'agent'], true)) {
    header('Location: ./');
    exit();
}

$rtpFlash = $_SESSION['rtp_control_flash'] ?? null;
if ($rtpFlash !== null) {
    unset($_SESSION['rtp_control_flash']);
}

$allowedFlashTypes = ['success', 'danger', 'warning', 'info'];
$formatRtpNumber = static function ($value): string {
    return number_format((float)$value, 0, ',', '.');
};

if (!function_exists('ensure_agent_rtp_column')) {
    function ensure_agent_rtp_column(mysqli $call): void
    {
        $column = mysqli_query($call, "SHOW COLUMNS FROM tb_agent LIKE 'rtp_control_default'");
        if ($column && mysqli_num_rows($column) > 0) {
            return;
        }

        mysqli_query($call, "ALTER TABLE tb_agent ADD COLUMN rtp_control_default TINYINT UNSIGNED NOT NULL DEFAULT 92");
    }
}

ensure_agent_rtp_column($call);

$rtpAgentRefsSql = agent_sql_values($call, agent_identity_values((array)$data_admin));
$rtpWhereParts = [];
$currentDefaultRtp = 92;
$defaultRtpQuery = mysqli_query($call, "SELECT rtp_control_default FROM tb_agent WHERE agent_name IN ($rtpAgentRefsSql) OR agent_code IN ($rtpAgentRefsSql) LIMIT 1");
if ($defaultRtpQuery && mysqli_num_rows($defaultRtpQuery) > 0) {
    $defaultRtpRow = mysqli_fetch_assoc($defaultRtpQuery) ?: [];
    $currentDefaultRtp = (int)($defaultRtpRow['rtp_control_default'] ?? 92);
}
if ($currentDefaultRtp < 1 || $currentDefaultRtp > 100) {
    $currentDefaultRtp = 92;
}

if ($rtpPageAgentLevel === 'admin') {
    $rtpWhereParts[] = '1=1';
} elseif ($rtpPageAgentLevel === 'head_agent') {
    $rtpWhereParts[] = "(
        u.agent_code IN ($rtpAgentRefsSql)
        OR u.agent_code IN (
            SELECT a.agent_code
            FROM tb_agent a
            WHERE a.agent_upline IN ($rtpAgentRefsSql)
        )
        OR u.agent_code IN (
            SELECT a.agent_name
            FROM tb_agent a
            WHERE a.agent_upline IN ($rtpAgentRefsSql)
        )
    )";
} else {
    $rtpWhereParts[] = "u.agent_code IN ($rtpAgentRefsSql)";
}

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

$rtpWhereSql = implode(' AND ', $rtpWhereParts);
$rtpLimit = legacy_page_limit('rtp_limit', 50);
$rtpPage = legacy_page_number('rtp_page');

$rtpStats = 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 $rtpWhereSql"
);
$rtpTotalMembers = (int)($rtpStats['total_member'] ?? 0);
$memberBalanceTotal = (float)($rtpStats['total_balance'] ?? 0);
$rtpTotalPages = max(1, (int)ceil($rtpTotalMembers / $rtpLimit));
$rtpPage = min($rtpPage, $rtpTotalPages);
$rtpOffset = max(0, ($rtpPage - 1) * $rtpLimit);

$memberQuery = mysqli_query(
    $call,
    "SELECT u.id, u.intUser, u.extUser, u.balance, u.agent_code, u.created, 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 $rtpWhereSql
     ORDER BY u.created DESC
     LIMIT $rtpOffset, $rtpLimit"
);
if (!$memberQuery) {
    die('Query gagal: ' . mysqli_error($call));
}

$memberRows = [];

while ($member = mysqli_fetch_assoc($memberQuery)) {
    $memberRows[] = $member;
}

$rtpShowingStart = $rtpTotalMembers > 0 ? $rtpOffset + 1 : 0;
$rtpShowingEnd = min($rtpOffset + count($memberRows), $rtpTotalMembers);
$rtpPaginationParams = [
    'rtp_search' => $rtpSearch,
    'rtp_limit' => $rtpLimit,
];

$scopeLabel = 'Member sendiri';
if ($rtpPageAgentLevel === 'admin') {
    $scopeLabel = 'Semua member';
} elseif ($rtpPageAgentLevel === 'head_agent') {
    $scopeLabel = 'Member sendiri dan downline';
}
?>
<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">Control RTP</h4>
                        <p class="text-muted mb-0"><?= htmlspecialchars($scopeLabel, ENT_QUOTES, 'UTF-8') ?>.</p>
                    </div>
                    <form
                        action="function/control_rtp.php"
                        method="POST"
                        class="d-flex flex-wrap align-items-end gap-2"
                        onsubmit="return confirm('Set RTP untuk semua member dalam akses akun ini?');">
                        <input type="hidden" name="rtp_scope" value="all">
                        <div>
                            <label class="form-label small mb-1">RTP Semua Member</label>
                            <input type="number" name="rtp" class="form-control form-control-sm" min="1" max="100" value="<?= htmlspecialchars((string)$currentDefaultRtp, ENT_QUOTES, 'UTF-8') ?>" required style="width: 96px;">
                        </div>
                        <button type="submit" class="btn btn-outline-success btn-sm">Set RTP All</button>
                    </form>
                </div>
                <div class="card-body">
                    <?php if (is_array($rtpFlash)): ?>
                    <?php
                    $rtpFlashType = (string)($rtpFlash['type'] ?? 'info');
                    if (!in_array($rtpFlashType, $allowedFlashTypes, true)) {
                        $rtpFlashType = 'info';
                    }
                    $rtpFlashUsers = is_array($rtpFlash['users'] ?? null) ? $rtpFlash['users'] : [];
                    ?>
                    <div class="alert alert-<?= htmlspecialchars($rtpFlashType, ENT_QUOTES, 'UTF-8') ?> mb-4">
                        <div class="fw-semibold">Control RTP</div>
                        <div><?= htmlspecialchars((string)($rtpFlash['message'] ?? ''), ENT_QUOTES, 'UTF-8') ?></div>
                        <div class="mt-2 small">
                            <?php if (isset($rtpFlash['rtp'])): ?>
                            <div>RTP: <strong><?= number_format((int)$rtpFlash['rtp']) ?>%</strong></div>
                            <?php endif; ?>
                            <?php if (isset($rtpFlash['total_users'])): ?>
                            <div>Total user diproses: <strong><?= number_format((int)$rtpFlash['total_users']) ?></strong></div>
                            <?php endif; ?>
                            <?php if (!empty($rtpFlash['default_saved'])): ?>
                            <div>Default RTP user baru: <strong>tersimpan</strong></div>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($rtpFlashUsers)): ?>
                        <div class="small mt-2">
                            Preview user: <?= htmlspecialchars(implode(', ', array_map('strval', $rtpFlashUsers)), ENT_QUOTES, 'UTF-8') ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                    <form method="get" action="<?= htmlspecialchars(page_url('ControlRtp'), 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="rtp_search" class="form-control" value="<?= htmlspecialchars($rtpSearch, 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="rtp_limit" class="form-select">
                                <?php foreach ([25, 50, 100, 200] as $limitOption): ?>
                                    <option value="<?= $limitOption ?>"<?= $rtpLimit === $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 ($rtpSearch !== ''): ?>
                        <div class="col-12 col-md-2">
                            <a href="<?= htmlspecialchars(page_url('ControlRtp'), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-outline-secondary w-100">Reset</a>
                        </div>
                        <?php endif; ?>
                    </form>

                    <div class="row g-3 mb-4">
                        <div class="col-md-3">
                            <div class="border rounded p-3 h-100">
                                <div class="text-muted small">Total Member</div>
                                <div class="fs-4 fw-semibold"><?= number_format($rtpTotalMembers) ?></div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="border rounded p-3 h-100">
                                <div class="text-muted small">Saldo Lokal Member</div>
                                <div class="fs-4 fw-semibold"><?= $formatRtpNumber($memberBalanceTotal) ?></div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="border rounded p-3 h-100">
                                <div class="text-muted small">Scope Akun</div>
                                <div class="fs-6 fw-semibold"><?= htmlspecialchars($scopeLabel, ENT_QUOTES, 'UTF-8') ?></div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="border rounded p-3 h-100">
                                <div class="text-muted small">Default RTP User Baru</div>
                                <div class="fs-4 fw-semibold"><?= number_format($currentDefaultRtp) ?>%</div>
                            </div>
                        </div>
                    </div>

                    <div class="text-muted small mb-3">
                        Menampilkan <?= number_format($rtpShowingStart) ?>-<?= number_format($rtpShowingEnd) ?> dari <?= number_format($rtpTotalMembers) ?> member.
                    </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 class="text-end">Balance</th>
                                    <th>Agent</th>
                                    <th>Created</th>
                                    <th>Control RTP</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($memberRows as $member): ?>
                                <tr>
                                    <td><?= htmlspecialchars((string)($member['extUser'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= htmlspecialchars((string)($member['intUser'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td class="text-end"><?= $formatRtpNumber($member['balance'] ?? 0) ?></td>
                                    <td><?= htmlspecialchars((string)($member['agent_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td class="text-nowrap"><?= htmlspecialchars((string)($member['created'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td>
                                        <form
                                            action="function/control_rtp.php"
                                            method="POST"
                                            class="d-flex flex-nowrap gap-1 align-items-center"
                                            onsubmit="return confirm('Set RTP untuk user ini?');">
                                            <input type="hidden" name="rtp_scope" value="single">
                                            <input type="hidden" name="user_code" value="<?= htmlspecialchars((string)($member['intUser'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
                                            <input type="number" name="rtp" class="form-control form-control-sm" min="1" max="100" value="<?= htmlspecialchars((string)$currentDefaultRtp, ENT_QUOTES, 'UTF-8') ?>" required style="width: 78px;">
                                            <button type="submit" class="btn btn-outline-success btn-sm text-nowrap">Set RTP</button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php legacy_render_pagination('ControlRtp', 'rtp_page', $rtpPage, $rtpTotalPages, $rtpPaginationParams); ?>
                </div>
            </div>
        </div>
    </div>
</div>
