<?php

namespace App\Libraries;

use Modules\Localize\Models\LocalizeModel;
use Modules\Localize\Models\LangstringModel;
use Modules\Localize\Models\LngstngvalueModel;

class Language
{
    public $localizeModel;
    protected $lngStringModel;
    protected $langstringvalueModel;

    public function __construct()
    {
        $this->localizeModel = new LocalizeModel();
        $this->lngStringModel = new LangstringModel();
        $this->langstringvalueModel = new LngstngvalueModel();
    }

    /**
     * Path to the canonical English Localize file (fallback chain for case-sensitive servers).
     */
    public static function baselineLocalizePath(): string
    {
        $base = rtrim(APPPATH, '/') . '/Language/';
        foreach (['en/Localize.php', 'Default/Localize.php', 'default/Localize.php'] as $relative) {
            $path = $base . $relative;
            if (is_file($path)) {
                return $path;
            }
        }

        return $base . 'en/Localize.php';
    }

    /**
     * Load baseline strings shipped with the app (usually English).
     *
     * @return array<string, string>
     */
    public static function loadBaselineLocalizeArray(): array
    {
        $path = self::baselineLocalizePath();
        if (! is_file($path)) {
            return [];
        }

        $data = include $path;

        return is_array($data) ? $data : [];
    }

    /**
     * Overlay DB translations on the baseline. Empty DB values keep the baseline text
     * so admin saves do not strip keys that exist only in PHP.
     *
     * @param array<string, string> $baseline
     * @param array<string, string> $dbPairs
     *
     * @return array<string, string>
     */
    public static function mergeBaselineWithDatabase(array $baseline, array $dbPairs): array
    {
        $merged = $baseline;
        foreach ($dbPairs as $key => $value) {
            if ($value === null) {
                continue;
            }
            if (trim((string) $value) !== '') {
                $merged[$key] = $value;
            }
        }

        return $merged;
    }

    public static function boot()
    {
        $currentLang = session('lang');
        if ($currentLang === null || $currentLang === '') {
            return;
        }

        $langFile = sprintf('%s/Language/%s/Localize.php', rtrim(APPPATH, '/'), $currentLang);

        if (! file_exists($langFile)) {
            try {
                $dir = dirname($langFile);
                ! is_dir($dir) && mkdir($dir, 0777, true);
                $src = self::baselineLocalizePath();
                if (is_file($src)) {
                    copy($src, $langFile);
                }
            } catch (\Throwable $e) {
                die('System couldn\'t find language file! exited.');
            }
        }
    }

    public function getAllLanguage()
    {
        $this->localizeModel = new LocalizeModel();
        $data['languagelist']  =  $this->localizeModel->orderBy('id', 'DESC')->findAll();
        return view('common/getLanguage', $data);
    }

    public function testdata()
    {
        $kye =  "'apples dfdfd'";
        $sam = "=>";
        $value =  'I have';

        $return = 'return [';
        $return .= $kye;
        $return .= $sam;
        $return .= $value;
        $return .= '];';

        return $return;
    }

    public function writeLanguage($lngid)
    {
        $lngStrDtail = $this->langstringvalueModel
            ->select('lngstngvalues.id,lngstngvalues.value,langstrings.name')
            ->join('langstrings', 'langstrings.id = lngstngvalues.string_id', 'left')
            ->where('localize_id', $lngid)
            ->orderBy('langstrings.id', 'ASC')
            ->asArray()
            ->findAll();

        $dbPairs = [];
        foreach ($lngStrDtail as $row) {
            if (! isset($row['name']) || $row['name'] === '') {
                continue;
            }
            $dbPairs[$row['name']] = $row['value'] ?? '';
        }

        $baseline = self::loadBaselineLocalizeArray();
        $lgnStrArray = self::mergeBaselineWithDatabase($baseline, $dbPairs);

        $lgnStrOutArray = var_export($lgnStrArray, true);

        return sprintf("<?php\n\nreturn %s;", $lgnStrOutArray);
    }

    /**
     * Write merged Localize.php for one localize row (same as saving strings in admin).
     */
    public function persistLocalizePhp(int $localizeId, string $folderName): bool
    {
        $folderName = trim(str_replace(['/', '\\', '..'], '', $folderName));
        if ($folderName === '' || $localizeId < 1) {
            return false;
        }

        $filepath = rtrim(APPPATH, '/') . '/Language/' . $folderName . '/';
        if (! is_dir($filepath) && ! mkdir($filepath, 0777, true) && ! is_dir($filepath)) {
            return false;
        }

        $content = $this->writeLanguage($localizeId);

        return write_file($filepath . 'Localize.php', $content, 'w+') !== false;
    }
}
