<?php

namespace Core;

class MultiTenancy
{
    public static function getTenantId()
    {
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $host = explode(':', $host)[0];

        $map = self::getTenantMap();
        if (!empty($map) && isset($map[$host])) {
            return $map[$host];
        }

        $baseDomain = getenv('BASE_DOMAIN') ?: '';
        if ($baseDomain !== '' && self::endsWith($host, $baseDomain)) {
            $prefix = rtrim(substr($host, 0, -strlen($baseDomain)), '.');
            if ($prefix === 'www') {
                $prefix = '';
            }
            return $prefix === '' ? 1 : $prefix;
        }

        return 1;
    }

    public static function getDatabasePath($tenantId)
    {
        $baseDir = __DIR__ . '/../../tenants/';
        if (!is_dir($baseDir)) mkdir($baseDir, 0777, true);
        
        $safeTenantId = preg_replace('/[^a-zA-Z0-9_-]/', '_', (string)$tenantId);
        if ($safeTenantId === '') {
            $safeTenantId = '1';
        }
        return $baseDir . "tenant_{$safeTenantId}.sqlite";
    }

    private static function getTenantMap()
    {
        $raw = getenv('TENANT_MAP');
        if (!$raw) {
            return [];
        }

        $map = json_decode($raw, true);
        return is_array($map) ? $map : [];
    }

    private static function endsWith($haystack, $needle)
    {
        $length = strlen($needle);
        if ($length === 0) {
            return true;
        }
        return substr($haystack, -$length) === $needle;
    }
}
