<?php
// admin/app_runtime.php
// Runtime installation mode helpers shared by web pages, APIs, cron workers and launchers.

require_once __DIR__ . '/app_paths.php';

if (!defined('UA_INSTALL_CONFIG_FILE')) {
  define('UA_INSTALL_CONFIG_FILE', ua_project_path('install_config.php'));
}

if (!function_exists('ua_default_install_config')) {
  function ua_default_install_config(): array {
    $idleSeconds = (int)(getenv('UA_IDLE_TIMEOUT') ?: 1800);
    if ($idleSeconds < 300) $idleSeconds = 300;
    if ($idleSeconds > 86400) $idleSeconds = 86400;
    return [
      'install_type' => 'server',
      'connection_mode' => 'local',
      'server_url' => 'http://127.0.0.1:8080/',
      'security' => [
        'idle_timeout_enabled' => false,
        'idle_timeout_minutes' => max(5, (int)round($idleSeconds / 60)),
      ],
      'database' => [
        'host' => '127.0.0.1',
        'port' => 3306,
        'name' => 'isp_db',
        'user' => 'root',
        'pass' => '',
        'charset' => 'utf8mb4',
      ],
    ];
  }
}

if (!function_exists('ua_normalize_idle_timeout_config')) {
  function ua_normalize_idle_timeout_config(array $config): array {
    $security = $config['security'] ?? [];
    if (!is_array($security)) $security = [];

    $enabledRaw = $security['idle_timeout_enabled'] ?? false;
    if (is_string($enabledRaw)) {
      $enabled = in_array(strtolower(trim($enabledRaw)), ['1', 'true', 'yes', 'on'], true);
    } else {
      $enabled = (bool)$enabledRaw;
    }

    $minutes = (int)($security['idle_timeout_minutes'] ?? 30);
    if ($minutes < 5) $minutes = 5;
    if ($minutes > 1440) $minutes = 1440;

    $config['security'] = [
      'idle_timeout_enabled' => $enabled,
      'idle_timeout_minutes' => $minutes,
    ];
    return $config;
  }
}

if (!function_exists('ua_valid_install_types')) {
  function ua_valid_install_types(): array {
    return ['server', 'agent', 'branch'];
  }
}

if (!function_exists('ua_install_config')) {
  function ua_install_config(): array {
    if (isset($GLOBALS['UA_INSTALL_CONFIG_OVERRIDE']) && is_array($GLOBALS['UA_INSTALL_CONFIG_OVERRIDE'])) {
      return $GLOBALS['UA_INSTALL_CONFIG_OVERRIDE'];
    }
    static $config = null;
    if (is_array($config)) return $config;

    $config = ua_default_install_config();
    $file = UA_INSTALL_CONFIG_FILE;
    if (is_file($file)) {
      $loaded = include $file;
      if (is_array($loaded)) {
        $config = array_replace_recursive($config, $loaded);
      }
    }

    $mode = strtolower(trim((string)($config['install_type'] ?? 'server')));
    if (!in_array($mode, ua_valid_install_types(), true)) {
      $mode = 'server';
    }
    $config['install_type'] = $mode;
    $config['connection_mode'] = strtolower(trim((string)($config['connection_mode'] ?? 'local'))) === 'internet'
      ? 'internet'
      : 'local';
    $config = ua_normalize_idle_timeout_config($config);

    return $config;
  }
}

if (!function_exists('ua_install_type')) {
  function ua_install_type(): string {
    $config = ua_install_config();
    return (string)$config['install_type'];
  }
}

if (!function_exists('ua_is_server_install')) {
  function ua_is_server_install(): bool {
    return ua_install_type() === 'server';
  }
}

if (!function_exists('ua_is_agent_install')) {
  function ua_is_agent_install(): bool {
    return ua_install_type() === 'agent';
  }
}

if (!function_exists('ua_is_branch_install')) {
  function ua_is_branch_install(): bool {
    return ua_install_type() === 'branch';
  }
}

if (!function_exists('ua_idle_timeout_policy')) {
  function ua_idle_timeout_policy(): array {
    $config = ua_normalize_idle_timeout_config(ua_install_config());
    $mode = (string)($config['install_type'] ?? 'server');
    $security = $config['security'];
    $minutes = (int)$security['idle_timeout_minutes'];

    return [
      'install_type' => $mode,
      'enabled' => !empty($security['idle_timeout_enabled']),
      'minutes' => $minutes,
      'seconds' => $minutes * 60,
    ];
  }
}

if (!function_exists('ua_install_home_page')) {
  function ua_install_home_page(): string {
    return ua_is_agent_install() ? 'agent_portal.php' : 'dashboard.php';
  }
}

if (!function_exists('ua_install_server_url')) {
  function ua_install_server_url(): string {
    $config = ua_install_config();
    return rtrim((string)($config['server_url'] ?? ''), '/');
  }
}

if (!function_exists('ua_install_connection_mode')) {
  function ua_install_connection_mode(): string {
    $config = ua_install_config();
    return ($config['connection_mode'] ?? 'local') === 'internet' ? 'internet' : 'local';
  }
}

if (!function_exists('ua_install_database_config')) {
  function ua_install_database_config(): array {
    $config = ua_install_config();
    $db = $config['database'] ?? [];
    return is_array($db) ? $db : [];
  }
}

if (!function_exists('ua_save_install_config')) {
  function ua_save_install_config(array $config, string &$error = ''): bool {
    $file = UA_INSTALL_CONFIG_FILE;
    $dir = dirname($file);
    if (!is_dir($dir) || !is_writable($dir)) {
      $error = 'Install config directory is not writable.';
      return false;
    }

    $base = ua_install_config();
    $config = array_replace_recursive($base, $config);
    $mode = strtolower(trim((string)($config['install_type'] ?? 'server')));
    if (!in_array($mode, ua_valid_install_types(), true)) $mode = 'server';
    $config['install_type'] = $mode;
    $config['connection_mode'] = strtolower(trim((string)($config['connection_mode'] ?? 'local'))) === 'internet'
      ? 'internet'
      : 'local';
    $config = ua_normalize_idle_timeout_config($config);

    $php = "<?php\n";
    $php .= "// Runtime install configuration.\n";
    $php .= "// Generated at " . date('Y-m-d H:i:s') . "\n\n";
    $php .= "return " . var_export($config, true) . ";\n";

    $tmp = $file . '.tmp';
    if (@file_put_contents($tmp, $php, LOCK_EX) === false) {
      $error = 'Could not write temporary install config.';
      return false;
    }
    if (!@rename($tmp, $file)) {
      @unlink($tmp);
      $error = 'Could not replace install config.';
      return false;
    }
    $GLOBALS['UA_INSTALL_CONFIG_OVERRIDE'] = $config;
    return true;
  }
}

if (!function_exists('ua_install_link_config')) {
  function ua_install_link_config(): array {
    $config = ua_install_config();
    $link = $config['link'] ?? [];
    return is_array($link) ? $link : [];
  }
}

if (!function_exists('ua_install_instance_key')) {
  /**
   * Stable local scope for settings that belong to the physical installation
   * rather than to the shared main database (printers, scanners, etc.).
   */
  function ua_install_instance_key(): string {
    $link = ua_install_link_config();
    $linkedId = trim((string)($link['instance_id'] ?? ''));
    if ($linkedId !== '') return substr('linked:' . $linkedId, 0, 100);

    $machine = trim((string)(getenv('COMPUTERNAME') ?: php_uname('n')));
    $project = function_exists('ua_project_path') ? ua_project_path() : dirname(__DIR__);
    return substr('local:' . ua_install_type() . ':' . hash('sha256', strtolower($machine . '|' . $project)), 0, 100);
  }
}

if (!function_exists('ua_install_link_status')) {
  function ua_install_link_status(): string {
    $link = ua_install_link_config();
    $status = strtolower(trim((string)($link['status'] ?? 'unlinked')));
    return in_array($status, ['unlinked', 'pending', 'approved', 'rejected', 'blocked', 'error'], true) ? $status : 'unlinked';
  }
}

if (!function_exists('ua_install_link_required')) {
  function ua_install_link_required(): bool {
    return ua_is_agent_install() || ua_is_branch_install();
  }
}

if (!function_exists('ua_install_link_approved')) {
  function ua_install_link_approved(): bool {
    if (!ua_install_link_required()) return true;
    $link = ua_install_link_config();
    return ua_install_link_status() === 'approved'
      && trim((string)($link['instance_id'] ?? '')) !== ''
      && trim((string)($link['secret'] ?? '')) !== ''
      && trim((string)($link['server_url'] ?? ua_install_server_url())) !== '';
  }
}
