<?php
/**
 * Feature flags with file-based caching (60s TTL).
 * Include this file to use is_feature_enabled($flag).
 */

require_once __DIR__ . '/../config/database.php';

function _load_feature_flags(): array {
    $cacheFile = '/tmp/el3ab_feature_flags.json';
    $cacheTTL = 60; // seconds

    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTTL) {
        $cached = json_decode(file_get_contents($cacheFile), true);
        if (is_array($cached)) {
            return $cached;
        }
    }

    // Fetch all flags from DB
    $res = supabase_rest('GET', 'feature_flags?select=id,is_enabled', [], SUPABASE_SERVICE_KEY);
    $flags = [];
    if (!empty($res['data']) && is_array($res['data'])) {
        foreach ($res['data'] as $row) {
            $flags[$row['id']] = (bool)$row['is_enabled'];
        }
    }

    // Write cache
    file_put_contents($cacheFile, json_encode($flags));

    return $flags;
}

function is_feature_enabled(string $flag): bool {
    static $flags = null;
    if ($flags === null) {
        $flags = _load_feature_flags();
    }
    return $flags[$flag] ?? false;
}
