<?php
/**
 * Build per-site env-var injections that customise the cac / cac-fpm image
 * pool sizing. Currently the only knob is FPM_MAX_CHILDREN (overrides
 * detect-memory.sh's pm.max_children calculation when set).
 *
 * Why a helper instead of inlining: there are seven call sites that build
 * docker env-var lists for site containers — create_site, recreate_site,
 * recreate_all_containers, add_container, the bulk recreate worker in
 * scripts/run-bulk-sites.php, the cpanel-import path, and the change-type
 * path. Keeping the override logic in one place avoids the seven-way drift
 * that bit us with mysql.user grants earlier this year.
 *
 * Scope: applies only to PHP / PHP-FPM container types (base_image
 * `(cac|cac-fpm):php<n>`). For Node and static-Apache types we return [],
 * so a leftover override on a re-typed site doesn't leak an irrelevant
 * env var to the new container.
 */

if (!function_exists('whp_build_php_pool_env')) {

    /**
     * @param PDO $db          Live whp PDO (mysqlmgmt::getMySQLConnection)
     * @param int $site_id     whp.sites.id
     * @return string[]        env-var KEY=value strings to merge into the
     *                         caller's $env_vars array (possibly empty)
     */
    function whp_build_php_pool_env(PDO $db, int $site_id): array {
        if ($site_id <= 0) return [];

        try {
            $stmt = $db->prepare(
                "SELECT s.fpm_max_children_override, ct.base_image
                   FROM whp.sites s
                   JOIN whp.container_types ct ON s.container_type_id = ct.id
                  WHERE s.id = ?"
            );
            $stmt->execute([$site_id]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (Throwable $e) {
            // Pre-migration deployments don't have the column. Treat as "no override".
            // The bad alternative — letting the exception bubble — would break the
            // container creation path on day 0 of the migration.
            if (str_contains($e->getMessage(), 'Unknown column')) {
                return [];
            }
            error_log("whp_build_php_pool_env: $e");
            return [];
        }

        if (!$row || $row['fpm_max_children_override'] === null) return [];

        // Restrict to cac / cac-fpm PHP images. Anything else (Node, static
        // Apache) doesn't have a detect-memory.sh + FPM pool to influence.
        if (!preg_match('#/(cac|cac-fpm):php\d+#', (string)$row['base_image'])) {
            return [];
        }

        $n = (int)$row['fpm_max_children_override'];
        // Defensive bounds — mirror detect-memory.sh's floor=2 / cap=50.
        if ($n < 2)  $n = 2;
        if ($n > 50) $n = 50;

        return ['FPM_MAX_CHILDREN=' . $n];
    }
}
