<?php

namespace App\Core;

/**
 * إدارة سياق المختبر (Tenant) في نظام Multi-Tenant
 */
class Tenant
{
    private static ?int $currentId = null;
    private static ?array $settings = null;

    public static function setId(int $id): void
    {
        self::$currentId = $id;
        self::$settings = null;
    }

    public static function id(): int
    {
        if (self::$currentId !== null) {
            return self::$currentId;
        }
        return (int)($_SESSION['tenant_id'] ?? 1);
    }

    public static function resolve(\PDO $db): int
    {
        if (self::$currentId !== null) {
            return self::$currentId;
        }
        if (isset($_SESSION['tenant_id'])) {
            self::$currentId = (int)$_SESSION['tenant_id'];
            return self::$currentId;
        }
        try {
            $subdomain = self::extractSubdomain();
            if ($subdomain) {
                $stmt = $db->prepare('SELECT id FROM tenants WHERE slug = ? AND status IN (?, ?) LIMIT 1');
                $stmt->execute([$subdomain, 'active', 'trial']);
                $row = $stmt->fetch();
                if ($row) {
                    self::$currentId = (int)$row['id'];
                    $_SESSION['tenant_id'] = self::$currentId;
                    return self::$currentId;
                }
            }
        } catch (\Throwable $e) {
        }
        self::$currentId = 1;
        $_SESSION['tenant_id'] = 1;
        return 1;
    }

    private static function extractSubdomain(): ?string
    {
        $host = $_SERVER['HTTP_HOST'] ?? '';
        $parts = explode('.', $host);
        // subdomain فقط عندما يكون هنالك 3 أجزاء فأكثر (مثل lab.a-manara.com)
        if (count($parts) >= 3 && $parts[0] !== 'www' && strlen($parts[0]) > 1) {
            return strtolower($parts[0]);
        }
        return null;
    }

    public static function getSettings(\PDO $db): array
    {
        if (self::$settings !== null) {
            return self::$settings;
        }
        $tid = self::id();
        $settings = [
            'lab_name' => 'مختبر تحاليل',
            'lab_phone' => '',
            'lab_address' => '',
            'logo_url' => '',
            'primary_color' => '#0d9488',
        ];
        try {
            $stmt = $db->prepare('SELECT setting_key, setting_value FROM settings WHERE tenant_id = ? AND setting_key IN ("lab_name","lab_phone","lab_address")');
            $stmt->execute([$tid]);
            foreach ($stmt->fetchAll() as $r) {
                $settings[$r['setting_key']] = (string)$r['setting_value'];
            }
            $stmt = $db->prepare('SELECT logo_url, primary_color FROM tenants WHERE id = ?');
            $stmt->execute([$tid]);
            $t = $stmt->fetch();
            if ($t) {
                $settings['logo_url'] = (string)($t['logo_url'] ?? '');
                $settings['primary_color'] = (string)($t['primary_color'] ?? '#0d9488');
            }
        } catch (\Throwable $e) {
        }
        self::$settings = $settings;
        return $settings;
    }

    public static function whereClause(string $table): string
    {
        $cols = ['users','patients','doctors','branches','tests','test_categories','inventory_items','lab_orders','settings'];
        $alias = in_array($table, $cols) ? $table : null;
        if ($alias) {
            return " $table.tenant_id = " . self::id();
        }
        return " 1=1 ";
    }
}
