<?php
namespace App\Models;

class Tenant {
    protected static $file = __DIR__ . '/../../data/tenants.json';

    public static function all() {
        if (!file_exists(self::$file)) {
            return [];
        }
        return json_decode(file_get_contents(self::$file), true) ?: [];
    }

    public static function find($id): ?array {
        $tenants = self::all();
        foreach ($tenants as $t) {
            if ($t['id'] === $id) {
                return $t;
            }
        }
        return null;
    }

    public static function findByHost($host): ?array {
        $tenants = self::all();
        $host = strtolower($host);
        
        // Strip port if exists
        if (($pos = strpos($host, ':')) !== false) {
            $host = substr($host, 0, $pos);
        }

        foreach ($tenants as $t) {
            // Direct domain check
            if (isset($t['domain']) && strtolower($t['domain']) === $host) {
                return $t;
            }
            
            // Subdomains check
            if (isset($t['subdomains'])) {
                foreach ($t['subdomains'] as $sub) {
                    $pattern = strtolower($sub . '.' . (isset($t['domain']) ? $t['domain'] : ''));
                    if ($pattern === $host) {
                        return $t;
                    }
                }
            }
        }

        // Default to the first tenant (main site) if nothing matches
        return isset($tenants[0]) ? $tenants[0] : null;
    }

    public static function save(array $tenantsList) {
        $content = json_encode($tenantsList, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        return file_put_contents(self::$file, $content) !== false;
    }
}
