<?php

namespace App\Helpers;

class ModularLanguageLoader
{
    protected static $cache = [];
    protected static $basePath = 'assets/languages/';

    /**
     * Load a specific language section
     *
     * @param string $language Language code (e.g., 'en', 'ar')
     * @param string $section Section name (e.g., 'common', 'authentication')
     * @return array
     */
    public static function loadSection($language, $section)
    {
        $cacheKey = "{$language}.{$section}";

        if (isset(static::$cache[$cacheKey])) {
            return static::$cache[$cacheKey];
        }

        $filePath = public_path(static::$basePath . "{$language}/{$section}.json");

        if (!file_exists($filePath)) {
            // Fallback to English if section not found
            $fallbackPath = public_path(static::$basePath . "en/{$section}.json");
            if (file_exists($fallbackPath)) {
                $filePath = $fallbackPath;
            } else {
                return [];
            }
        }

        $content = file_get_contents($filePath);
        $data = json_decode($content, true) ?: [];

        static::$cache[$cacheKey] = $data;

        return $data;
    }

    /**
     * Load complete language with all sections
     *
     * @param string $language Language code
     * @return array
     */
    public static function loadLanguage($language)
    {
        $cacheKey = "full.{$language}";

        if (isset(static::$cache[$cacheKey])) {
            return static::$cache[$cacheKey];
        }

        $indexPath = public_path(static::$basePath . "{$language}/index.json");

        if (!file_exists($indexPath)) {
            // Fallback to monolithic file
            return static::loadMonolithicLanguage($language);
        }

        $indexContent = file_get_contents($indexPath);
        $index = json_decode($indexContent, true);

        if (!isset($index['files'])) {
            return static::loadMonolithicLanguage($language);
        }

        $completeData = [];

        foreach ($index['files'] as $file) {
            $section = str_replace('.json', '', $file);
            $sectionData = static::loadSection($language, $section);
            $completeData = array_merge_recursive($completeData, $sectionData);
        }

        static::$cache[$cacheKey] = $completeData;

        return $completeData;
    }

    /**
     * Load monolithic language file (fallback)
     *
     * @param string $language
     * @return array
     */
    protected static function loadMonolithicLanguage($language)
    {
        $filePath = public_path(static::$basePath . "{$language}.json");

        if (!file_exists($filePath)) {
            $filePath = public_path(static::$basePath . "en.json");
        }

        if (!file_exists($filePath)) {
            return [];
        }

        $content = file_get_contents($filePath);
        return json_decode($content, true) ?: [];
    }

    /**
     * Get a specific translation key
     *
     * @param string $language
     * @param string $key Dot notation key (e.g., 'common.loading')
     * @param string $default Default value if not found
     * @return string
     */
    public static function get($language, $key, $default = '')
    {
        $keys = explode('.', $key);
        $section = $keys[0];

        $data = static::loadSection($language, $section);

        // Navigate through the array using dot notation
        $current = $data;
        foreach ($keys as $keyPart) {
            if (is_array($current) && isset($current[$keyPart])) {
                $current = $current[$keyPart];
            } else {
                return $default;
            }
        }

        return is_string($current) ? $current : $default;
    }

    /**
     * Clear cache for specific language or all
     *
     * @param string|null $language
     */
    public static function clearCache($language = null)
    {
        if ($language) {
            foreach (static::$cache as $key => $value) {
                if (strpos($key, $language) === 0) {
                    unset(static::$cache[$key]);
                }
            }
        } else {
            static::$cache = [];
        }
    }

    /**
     * Check if modular files exist for a language
     *
     * @param string $language
     * @return bool
     */
    public static function hasModularFiles($language)
    {
        $indexPath = public_path(static::$basePath . "{$language}/index.json");
        return file_exists($indexPath);
    }

    /**
     * Get available sections for a language
     *
     * @param string $language
     * @return array
     */
    public static function getAvailableSections($language)
    {
        $indexPath = public_path(static::$basePath . "{$language}/index.json");

        if (!file_exists($indexPath)) {
            return [];
        }

        $indexContent = file_get_contents($indexPath);
        $index = json_decode($indexContent, true);

        return $index['files'] ?? [];
    }
}
