<?php

function agent_public_name(array $agent): string
{
    $name = trim((string)($agent['agent_name'] ?? ''));
    if ($name !== '') {
        return $name;
    }

    return trim((string)($agent['agent_code'] ?? ''));
}

function agent_identity_values(array $agent): array
{
    $values = [];

    foreach (['agent_name', 'agent_code'] as $field) {
        $value = trim((string)($agent[$field] ?? ''));
        if ($value !== '' && !in_array($value, $values, true)) {
            $values[] = $value;
        }
    }

    return $values;
}

function agent_sql_values(mysqli $db, array $values): string
{
    $escaped = [];

    foreach ($values as $value) {
        $value = trim((string)$value);
        if ($value === '') {
            continue;
        }

        $escaped[] = "'" . mysqli_real_escape_string($db, $value) . "'";
    }

    return $escaped !== [] ? implode(',', array_unique($escaped)) : "''";
}

function agent_reference_condition(mysqli $db, string $column, array $agent): string
{
    return $column . ' IN (' . agent_sql_values($db, agent_identity_values($agent)) . ')';
}

function agent_lookup_condition(mysqli $db, string $identifier, string $alias = ''): string
{
    $identifierSql = mysqli_real_escape_string($db, trim($identifier));
    $prefix = $alias !== '' ? $alias . '.' : '';

    return "({$prefix}agent_name = '$identifierSql' OR {$prefix}agent_code = '$identifierSql')";
}

function agent_find_by_identifier(mysqli $db, string $identifier, string $secretKey = ''): ?array
{
    $identifier = trim($identifier);
    if ($identifier === '') {
        return null;
    }

    $identifierSql = mysqli_real_escape_string($db, $identifier);
    $secretWhere = '';

    if ($secretKey !== '') {
        $secretSql = mysqli_real_escape_string($db, trim($secretKey));
        $secretWhere = " AND secret_key = '$secretSql'";
    }

    $query = mysqli_query(
        $db,
        "SELECT *
         FROM tb_agent
         WHERE (agent_name = '$identifierSql' OR agent_code = '$identifierSql')
           $secretWhere
         ORDER BY CASE WHEN agent_name = '$identifierSql' THEN 0 ELSE 1 END
         LIMIT 1"
    );

    if (!$query || mysqli_num_rows($query) === 0) {
        return null;
    }

    return mysqli_fetch_assoc($query) ?: null;
}

function agent_find_by_name(mysqli $db, string $agentName, string $secretKey = ''): ?array
{
    $agentName = trim($agentName);
    if ($agentName === '') {
        return null;
    }

    $agentNameSql = mysqli_real_escape_string($db, $agentName);
    $secretWhere = '';

    if ($secretKey !== '') {
        $secretSql = mysqli_real_escape_string($db, trim($secretKey));
        $secretWhere = " AND secret_key = '$secretSql'";
    }

    $query = mysqli_query(
        $db,
        "SELECT *
         FROM tb_agent
         WHERE agent_name = '$agentNameSql'
           AND agent_code <> '$agentNameSql'
           $secretWhere
         LIMIT 1"
    );

    if (!$query || mysqli_num_rows($query) === 0) {
        return null;
    }

    return mysqli_fetch_assoc($query) ?: null;
}

function agent_refresh_session(mysqli $db, string $identifier): void
{
    if (session_status() !== PHP_SESSION_ACTIVE || empty($_SESSION['admin'])) {
        return;
    }

    $agent = agent_find_by_identifier($db, $identifier);
    if ($agent === null) {
        return;
    }

    $_SESSION['admin'] = $agent;
    $_SESSION['agent_level'] = (string)($agent['agent_level'] ?? ($_SESSION['agent_level'] ?? ''));
}

function agent_rewrite_local_references(mysqli $db, string $oldCode, string $oldName, string $newName): bool
{
    $oldValues = array_values(array_unique(array_filter([trim($oldCode), trim($oldName)], static function ($value) {
        return $value !== '';
    })));

    $newName = trim($newName);
    if ($oldValues === [] || $newName === '') {
        return true;
    }

    $oldValuesSql = agent_sql_values($db, $oldValues);
    $newNameSql = mysqli_real_escape_string($db, $newName);

    $updates = [
        "UPDATE tb_user SET agent_code = '$newNameSql' WHERE agent_code IN ($oldValuesSql)",
        "UPDATE tb_transaction SET agent_code = '$newNameSql' WHERE agent_code IN ($oldValuesSql)",
        "UPDATE tb_balance SET agent_code = '$newNameSql' WHERE agent_code IN ($oldValuesSql)",
        "UPDATE tb_topup SET agent_code = '$newNameSql' WHERE agent_code IN ($oldValuesSql)",
        "UPDATE tb_history SET agent_code = '$newNameSql' WHERE agent_code IN ($oldValuesSql)",
        "UPDATE tb_agent SET agent_upline = '$newNameSql' WHERE agent_upline IN ($oldValuesSql)",
        "UPDATE tb_agent_contact SET agent_code = '$newNameSql' WHERE agent_code IN ($oldValuesSql)",
    ];

    foreach ($updates as $sql) {
        if (!mysqli_query($db, $sql)) {
            return false;
        }
    }

    return true;
}
