<?php
if (!function_exists('enrep_surveyor_normalise_email')) {
    function enrep_surveyor_normalise_email($email): string
    {
        return strtolower(trim((string)$email));
    }
}

if (!function_exists('enrep_surveyor_current_client_id')) {
    function enrep_surveyor_current_client_id(mysqli $con): int
    {
        $clientId = 0;
        if ($res = $con->query("SELECT `client_id` FROM `subscription_params` LIMIT 1")) {
            if ($row = $res->fetch_assoc()) {
                $clientId = (int)($row['client_id'] ?? 0);
            }
            $res->free();
        }

        return $clientId;
    }
}

if (!function_exists('enrep_surveyor_current_tenant_prefixes')) {
    function enrep_surveyor_current_tenant_prefixes(): array
    {
        $prefixes = [];
        $candidates = [];

        if (defined('TENANT_URL')) {
            $candidates[] = trim((string)TENANT_URL, "/ \t\n\r\0\x0B");
        }
        if (defined('TENANT_DEFER')) {
            $candidates[] = trim(basename(str_replace('\\', '/', (string)TENANT_DEFER)));
        }
        if (!empty($_SERVER['HTTP_HOST'])) {
            $candidates[] = (string)$_SERVER['HTTP_HOST'];
        }

        foreach ($candidates as $candidate) {
            $candidate = strtolower(trim($candidate));
            if ($candidate === '') {
                continue;
            }

            $candidate = preg_replace('/^https?:\/\//', '', $candidate);
            $candidate = explode('/', $candidate)[0];
            $candidate = explode(':', $candidate)[0];

            if ($candidate !== '') {
                $prefixes[$candidate] = true;
            }

            $firstPart = explode('.', $candidate)[0] ?? '';
            if ($firstPart !== '' && !in_array($firstPart, ['www', 'enrepcore', 'admin'], true)) {
                $prefixes[$firstPart] = true;
            }
        }

        return array_keys($prefixes);
    }
}

if (!function_exists('enrep_surveyor_owner_email_map')) {
    function enrep_surveyor_owner_email_map($admin_con, int $excludeClientId = 0, array $excludePrefixes = []): array
    {
        static $cachedEmails = [];
        if (empty($excludePrefixes)) {
            $excludePrefixes = enrep_surveyor_current_tenant_prefixes();
        }
        $excludePrefixMap = [];
        foreach ($excludePrefixes as $prefix) {
            $prefix = strtolower(trim((string)$prefix));
            if ($prefix !== '') {
                $excludePrefixMap[$prefix] = true;
            }
        }
        $cacheKey = $excludeClientId . '|' . implode(',', array_keys($excludePrefixMap));
        if (isset($cachedEmails[$cacheKey])) {
            return $cachedEmails[$cacheKey];
        }

        $emails = [];
        if (!($admin_con instanceof mysqli)) {
            return $emails;
        }

        $sql = "
            SELECT `client_id`, `subdomain_prefix`, `email`, `primary_admin_email`
            FROM `client_subscriptions`
            WHERE `status` = 'active'
        ";
        if ($res = $admin_con->query($sql)) {
            while ($row = $res->fetch_assoc()) {
                if ($excludeClientId > 0 && (int)($row['client_id'] ?? 0) === $excludeClientId) {
                    continue;
                }
                $rowPrefix = strtolower(trim((string)($row['subdomain_prefix'] ?? '')));
                if ($rowPrefix !== '' && isset($excludePrefixMap[$rowPrefix])) {
                    continue;
                }

                foreach (['email', 'primary_admin_email'] as $field) {
                    $email = enrep_surveyor_normalise_email($row[$field] ?? '');
                    if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $emails[$email] = true;
                    }
                }
            }
            $res->free();
        }

        $cachedEmails[$cacheKey] = $emails;
        return $cachedEmails[$cacheKey];
    }
}

if (!function_exists('enrep_surveyor_email_is_linked_owner')) {
    function enrep_surveyor_email_is_linked_owner($admin_con, $email, int $excludeClientId = 0, array $excludePrefixes = []): bool
    {
        $email = enrep_surveyor_normalise_email($email);
        if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return false;
        }

        $ownerEmails = enrep_surveyor_owner_email_map($admin_con, $excludeClientId, $excludePrefixes);
        return isset($ownerEmails[$email]);
    }
}

if (!function_exists('enrep_surveyor_capacity_snapshot')) {
    function enrep_surveyor_capacity_snapshot(mysqli $con, $admin_con): array
    {
        $tenantClientId = enrep_surveyor_current_client_id($con);
        $ownerEmails = enrep_surveyor_owner_email_map($admin_con, $tenantClientId, enrep_surveyor_current_tenant_prefixes());
        $totalActive = 0;
        $linkedOwnerActive = 0;

        if ($res = $con->query("SELECT `email` FROM `surveyor` WHERE `statuslive` = 1")) {
            while ($row = $res->fetch_assoc()) {
                $totalActive++;
                $email = enrep_surveyor_normalise_email($row['email'] ?? '');
                if ($email !== '' && isset($ownerEmails[$email])) {
                    $linkedOwnerActive++;
                }
            }
            $res->free();
        }

        $slotActive = max(0, $totalActive - $linkedOwnerActive);
        return [
            'active_total' => $totalActive,
            'linked_owner_active' => $linkedOwnerActive,
            'slot_active' => $slotActive,
        ];
    }
}

if (!function_exists('enrep_surveyor_active_slot_count')) {
    function enrep_surveyor_active_slot_count(mysqli $con, $admin_con): int
    {
        $snapshot = enrep_surveyor_capacity_snapshot($con, $admin_con);
        return (int)$snapshot['slot_active'];
    }
}
?>
