<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}

/**
 * PlatformSettings — config editable de plataforma (lo NO-secreto).
 * Los secretos (Account SID, Auth Token, Gemini key) viven en .env.
 */
class PlatformSettings {
    public static function get(string $key, $default = null) {
        try {
            $stmt = DB::connect()->prepare("SELECT setting_value FROM platform_settings WHERE setting_key = :k LIMIT 1");
            $stmt->execute([':k' => $key]);
            $v = $stmt->fetchColumn();
            return ($v !== false && $v !== null && $v !== '') ? $v : $default;
        } catch (Throwable $e) {
            return $default; // tabla todavía no migrada
        }
    }

    public static function set(string $key, string $value): void {
        DB::connect()->prepare(
            "INSERT INTO platform_settings (setting_key, setting_value) VALUES (:k, :v)
             ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)"
        )->execute([':k' => $key, ':v' => $value]);
    }

    /** Número oficial de Supraine (solo dígitos): settings -> fallback .env. */
    public static function supraideNumber(): string {
        $n = self::get('supraide_whatsapp', getenv('SUPRAIDE_WHATSAPP') ?: '');
        return preg_replace('/\D+/', '', (string) $n);
    }
}
