<?php
namespace App\Models;

/**
 * Reads per-branch configuration from the key-value `epos_branch_config` table.
 *
 * Replaces the legacy `epos_branches_ordering_config` wide table. Callers that
 * previously got a row with named columns (ftp_host, smtp_user, docusign_*,
 * etc.) should call BranchConfig::getAll() and receive an associative array
 * with the same keys — so the rest of the codebase doesn't change shape.
 *
 * Cached per request so multiple read sites for the same branch share one DB
 * hit. Call BranchConfig::clearCache() in tests if you need to reset between
 * cases.
 */
class BranchConfig
{
	private static array $cache = [];

	/**
	 * All key-value pairs for a branch as ['key_name' => 'key_value'].
	 * Returns an empty array if no rows match (caller should default fields).
	 */
	public static function getAll($branch, $organizationId = null): array
	{
		if (empty($branch)) return [];

		$cacheKey = ((int) $branch) . ':' . ($organizationId !== null ? (int) $organizationId : 'any');
		if (isset(self::$cache[$cacheKey])) {
			return self::$cache[$cacheKey];
		}

		$db = \Config\Database::connect();
		$builder = $db->table('epos_branch_config')->where('branch', (int) $branch);
		if (!empty($organizationId)) {
			$builder->where('organization_id', (int) $organizationId);
		}
		$rows = $builder->get()->getResult();

		$config = [];
		foreach ($rows as $row) {
			$config[$row->key_name] = $row->key_value;
		}

		return self::$cache[$cacheKey] = $config;
	}

	/**
	 * Single key. Returns $default if the key isn't set on this branch.
	 */
	public static function get($branch, string $key, $organizationId = null, $default = null)
	{
		$all = self::getAll($branch, $organizationId);
		return $all[$key] ?? $default;
	}

	/**
	 * Boolean reading. Treats '1' / 'true' / 'yes' / 'on' as true, anything
	 * else (including missing) as false. Useful for ftp_enable, smtp_used, etc.
	 */
	public static function getBool($branch, string $key, $organizationId = null, bool $default = false): bool
	{
		$value = self::get($branch, $key, $organizationId);
		if ($value === null) return $default;
		return in_array(strtolower(trim((string) $value)), ['1', 'true', 'yes', 'on'], true);
	}

	public static function clearCache(): void
	{
		self::$cache = [];
	}
}
