<?php
include_once '../config/connect.php';
require_once __DIR__ . '/../../api/v1/NEXUSGGR.php';

function redirect_control_rtp_page(): void
{
    header('Location: ../index?page=ControlRtp');
    exit();
}

function set_rtp_flash(string $type, string $message, array $payload = []): void
{
    $_SESSION['rtp_control_flash'] = array_merge([
        'type' => $type,
        'message' => $message,
    ], $payload);
}

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");
}

function current_member_scope_where(mysqli $call, array $agent, string $agentLevel): string
{
    $agentRefsSql = agent_sql_values($call, agent_identity_values($agent));

    if ($agentLevel === 'admin') {
        return '1=1';
    }

    if ($agentLevel === 'head_agent') {
        return "(
            u.agent_code IN ($agentRefsSql)
            OR u.agent_code IN (
                SELECT a.agent_code
                FROM tb_agent a
                WHERE a.agent_upline IN ($agentRefsSql)
            )
            OR u.agent_code IN (
                SELECT a.agent_name
                FROM tb_agent a
                WHERE a.agent_upline IN ($agentRefsSql)
            )
        )";
    }

    return "u.agent_code IN ($agentRefsSql)";
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    set_rtp_flash('danger', 'Request RTP tidak valid.');
    redirect_control_rtp_page();
}

$currentAgent = (array)($_SESSION['admin'] ?? []);
$currentAgentName = agent_public_name($currentAgent);
$currentAgentLevel = trim((string)($_SESSION['admin']['agent_level'] ?? ($_SESSION['agent_level'] ?? '')));

if ($currentAgentName === '' || !in_array($currentAgentLevel, ['admin', 'head_agent', 'agent'], true)) {
    set_rtp_flash('danger', 'Akses control RTP ditolak.');
    redirect_control_rtp_page();
}

ensure_agent_rtp_column($call);

$rtp = (int)($_POST['rtp'] ?? 0);
if ($rtp < 1 || $rtp > 100) {
    set_rtp_flash('danger', 'RTP harus angka 1 sampai 100.');
    redirect_control_rtp_page();
}

$scope = trim((string)($_POST['rtp_scope'] ?? ''));
if (!in_array($scope, ['single', 'all'], true)) {
    set_rtp_flash('danger', 'Scope control RTP tidak dikenal.');
    redirect_control_rtp_page();
}

$scopeWhere = current_member_scope_where($call, $currentAgent, $currentAgentLevel);
$userCodes = [];
$targetLabel = 'member';

if ($scope === 'single') {
    $userCode = trim((string)($_POST['user_code'] ?? ''));
    if ($userCode === '') {
        set_rtp_flash('danger', 'User API untuk control RTP tidak ditemukan.');
        redirect_control_rtp_page();
    }

    $userCodeSql = mysqli_real_escape_string($call, $userCode);
    $query = mysqli_query(
        $call,
        "SELECT u.intUser, u.extUser
         FROM tb_user u
         WHERE u.intUser = '$userCodeSql'
           AND $scopeWhere
         LIMIT 1"
    );

    if (!$query || mysqli_num_rows($query) === 0) {
        set_rtp_flash('danger', 'Member tidak ditemukan atau bukan dalam akses akun Anda.');
        redirect_control_rtp_page();
    }

    $member = mysqli_fetch_assoc($query) ?: [];
    $userCodes[] = (string)($member['intUser'] ?? '');
    $targetLabel = (string)($member['extUser'] ?? $userCode);
} else {
    $query = mysqli_query(
        $call,
        "SELECT u.intUser
         FROM tb_user u
         WHERE $scopeWhere
         ORDER BY u.created DESC"
    );

    if ($query) {
        while ($row = mysqli_fetch_assoc($query)) {
            $userCode = trim((string)($row['intUser'] ?? ''));
            if ($userCode !== '') {
                $userCodes[] = $userCode;
            }
        }
    }

    $targetLabel = 'semua member dalam akses Anda';
}

$userCodes = array_values(array_unique($userCodes));
if (count($userCodes) === 0) {
    set_rtp_flash('warning', 'Tidak ada member yang bisa diproses untuk control RTP.');
    redirect_control_rtp_page();
}

try {
    $providerApi = new fiver($call);
    $response = $providerApi->controlUsersRtp($userCodes, $rtp);

    if (!is_array($response)) {
        set_rtp_flash('danger', 'Control RTP gagal: provider tidak memberi response valid.', [
            'scope' => $scope,
            'rtp' => $rtp,
            'total_users' => count($userCodes),
        ]);
        redirect_control_rtp_page();
    }

    if ((int)($response['status'] ?? 0) !== 1) {
        set_rtp_flash('danger', 'Control RTP gagal: ' . (string)($response['msg'] ?? 'UNKNOWN_ERROR'), [
            'scope' => $scope,
            'rtp' => $rtp,
            'total_users' => count($userCodes),
        ]);
        redirect_control_rtp_page();
    }

    if ($scope === 'all') {
        $currentAgentNameSql = mysqli_real_escape_string($call, $currentAgentName);
        mysqli_query($call, "UPDATE tb_agent SET rtp_control_default = '$rtp' WHERE agent_name = '$currentAgentNameSql' LIMIT 1");
    }

    set_rtp_flash('success', 'Control RTP berhasil untuk ' . $targetLabel . '.', [
        'scope' => $scope,
        'rtp' => (int)($response['changed_rtp'] ?? $rtp),
        'total_users' => count($userCodes),
        'users' => array_slice($userCodes, 0, 20),
        'default_saved' => $scope === 'all',
    ]);
} catch (Throwable $exception) {
    set_rtp_flash('danger', 'Control RTP gagal diproses: ' . $exception->getMessage(), [
        'scope' => $scope,
        'rtp' => $rtp,
        'total_users' => count($userCodes),
    ]);
}

redirect_control_rtp_page();
