<?php

require_once __DIR__ . '/app_runtime.php';
require_once __DIR__ . '/agent_repository.php';

function ua_agent_portal_resolve_id(mysqli $conn, int $requestedId = 0): int {
  if ($requestedId > 0) return $requestedId;
  if (!ua_is_agent_install()) return 0;

  $link = ua_install_link_config();
  $instanceId = trim((string)($link['instance_id'] ?? ''));
  if ($instanceId !== '') {
    $instanceEsc = $conn->real_escape_string($instanceId);
    $rs = @$conn->query("SELECT id FROM agents WHERE linked_instance_id='{$instanceEsc}' AND is_active=1 AND portal_enabled=1 AND archived_at IS NULL LIMIT 1");
    if ($rs && ($row = $rs->fetch_assoc())) return (int)$row['id'];
  }

  $rs = @$conn->query("SELECT id FROM agents WHERE is_active=1 AND portal_enabled=1 AND archived_at IS NULL ORDER BY id ASC LIMIT 2");
  if ($rs && $rs->num_rows === 1 && ($row = $rs->fetch_assoc())) return (int)$row['id'];
  return 0;
}
