<?php

namespace App\Services;

class LanguageService {
    private static $translations = [];
    private static $lang = 'id';

    public static function init() {
        if (isset($_SESSION['lang']) && is_string($_SESSION['lang'])) {
            self::$lang = $_SESSION['lang'];
        } elseif (isset($_COOKIE['lang']) && is_string($_COOKIE['lang'])) {
            self::$lang = $_COOKIE['lang'];
        }

        if (!is_string(self::$lang)) {
            self::$lang = 'id';
        }

        $langFile = __DIR__ . '/../../lang/' . self::$lang . '.php';
        if (file_exists($langFile)) {
            self::$translations = require $langFile;
        } else {
            // Default to English if the translation file doesn't exist
            self::$lang = 'en';
            $langFile = __DIR__ . '/../../lang/' . self::$lang . '.php';
            if (file_exists($langFile)) {
                self::$translations = require $langFile;
            }
        }
    }

    public static function translate($key, $default = null) {
        if (empty(self::$translations)) {
            self::init();
        }
        return self::$translations[$key] ?? ($default ?? $key);
    }

    public static function setLang($lang) {
        if (!is_string($lang)) {
            return;
        }
        self::$lang = $lang;
        $_SESSION['lang'] = $lang;
        setcookie('lang', $lang, time() + (86400 * 30), "/");
    }

    public static function getLang() {
        return self::$lang;
    }
}