<?php

namespace Core\App\Controllers;

use Core\App\Models\LanguageModel;
use Core\System\Request;
use Core\System\Response;
use Core\System\Language;

class LanguageManagerController
{
    protected LanguageModel $model;

    public function __construct()
    {
        $this->model = new LanguageModel();
    }

    /**
     * قائمة اللغات
     */
    public function index()
    {
        $languages = $this->model->getAll();

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/languages/index.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /**
     * صفحة إنشاء لغة
     */
    public function create()
    {
        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/languages/create.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /**
     * حفظ لغة جديدة
     */
    public function store()
    {
        $code      = strtolower(trim(Request::input('code')));
        $name      = trim(Request::input('name'));
        $direction = Request::input('direction', 'ltr');
        $isDefault = Request::input('is_default') ? 1 : 0;

        // Validation
        if (!$code || !$name || !preg_match('/^[a-z]{2}$/', $code)) {
            Response::redirect('/admin/languages/create?error=invalid');
            return;
        }

        if ($this->model->getByCode($code)) {
            Response::redirect('/admin/languages/create?error=exists');
            return;
        }

        // Save in database
        $this->model->add($code, $name, $direction, $isDefault);

        // Create language JSON (copy from base)
        $this->createLanguageJsonFile($code, $name, $direction, true);

        // Redirect directly to translate page
        Response::redirect("/admin/languages/translate/{$code}");
    }

    /**
     * صفحة تعديل لغة
     */
    public function edit($id)
    {
        $language = $this->model->getById((int)$id);

        if (!$language) {
            Response::redirect('/admin/languages');
            return;
        }

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/languages/edit.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /**
     * تحديث لغة
     */
    public function update($id)
    {
        $code      = strtolower(trim(Request::input('code')));
        $name      = trim(Request::input('name'));
        $direction = Request::input('direction', 'ltr');
        $isDefault = Request::input('is_default') ? 1 : 0;

        if (!$code || !$name) {
            Response::redirect('/admin/languages');
            return;
        }

        $this->model->update((int)$id, $code, $name, $direction, $isDefault);

        // Update metadata only (do not overwrite translations)
        $this->createLanguageJsonFile($code, $name, $direction, false);

        Response::redirect('/admin/languages');
    }

    /**
     * حذف لغة (محمي)
     */
    public function delete($id)
    {
        $language = $this->model->getById((int)$id);

        if (!$language) {
            Response::redirect('/admin/languages');
            return;
        }

        // Protect core languages
        if (
            $language['code'] === 'en' ||
            $language['code'] === 'ar' ||
            !empty($language['is_default'])
        ) {
            Response::redirect('/admin/languages?error=protected');
            return;
        }

        $file = ROOT_PATH . "/lang/{$language['code']}.json";
        if (file_exists($file)) {
            unlink($file);
        }

        $this->model->delete((int)$id);

        Response::redirect('/admin/languages?deleted=1');
    }

    /**
     * صفحة الترجمة
     */
    public function translate($code)
    {
        // Security: validate language code to prevent path traversal
        if (!preg_match('/^[a-z]{2,5}$/', (string)$code)) {
            Response::redirect('/admin/languages');
            return;
        }

        $baseFile = ROOT_PATH . "/lang/en.json";
        $baseStrings = json_decode(@file_get_contents($baseFile), true) ?? [];

        $targetFile = ROOT_PATH . "/lang/{$code}.json";
        $currentStrings = file_exists($targetFile)
            ? (json_decode(@file_get_contents($targetFile), true) ?? [])
            : [];

        $strings = $baseStrings;
        $current = array_merge($strings, $currentStrings);

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/languages/translate.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /**
     * حفظ الترجمة
     */
    public function saveTranslations($code)
    {
        // Security: validate language code to prevent path traversal
        if (!preg_match('/^[a-z]{2,5}$/', (string)$code)) {
            Response::redirect('/admin/languages');
            return;
        }

        $translations = Request::input('translations', []);

        $baseStrings = json_decode(
            @file_get_contents(ROOT_PATH . "/lang/en.json"),
            true
        ) ?? [];

        $result = [];

        foreach ($baseStrings as $key => $value) {
            $val = trim($translations[$key] ?? '');
            $result[$key] = ($val === '') ? $value : $val;
        }

        file_put_contents(
            ROOT_PATH . "/lang/{$code}.json",
            json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
        );

        Response::redirect("/admin/languages/translate/{$code}?saved=1");
    }

    /**
     * تعيين لغة افتراضية
     */
    public function setDefault($id)
    {
        \Core\System\Csrf::check();
        $language = $this->model->getById((int)$id);

        if (!$language) {
            Response::redirect('/admin/languages');
            return;
        }

        $this->model->setDefault((int)$id);
        Language::set($language['code']);

        Response::redirect('/admin/languages');
    }

    /**
     * التبديل من الهيدر
     */
    public function switch($lang)
    {
        $file = ROOT_PATH . "/lang/{$lang}.json";

        Language::set(file_exists($file) ? $lang : 'en');

        // Redirect back to the page the user was on (not always dashboard)
        $referer = $_SERVER['HTTP_REFERER'] ?? '';
        if ($referer !== '' && str_contains($referer, '/admin/')) {
            header('Location: ' . filter_var($referer, FILTER_SANITIZE_URL));
            exit;
        }

        Response::back('/admin/dashboard');
    }

    /**
     * إنشاء / تحديث ملف JSON للغة
     */
    protected function createLanguageJsonFile(
        string $code,
        string $name,
        string $direction,
        bool $copyBase = true
    ): void {
        $file = ROOT_PATH . "/lang/{$code}.json";

        if ($copyBase || !file_exists($file)) {
            $content = json_decode(
                @file_get_contents(ROOT_PATH . "/lang/en.json"),
                true
            ) ?? [];
        } else {
            $content = json_decode(@file_get_contents($file), true) ?? [];
        }

        $content['language.name']      = $name;
        $content['language.direction'] = $direction;

        file_put_contents(
            $file,
            json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
        );
    }
}
