<?php
/**
 * VFM - veno file manager: admin-panel/view/admin-head-translations.php
 * main translations setting process
 *
 * PHP version >= 5.3
 *
 * @category  PHP
 * @package   VenoFileManager
 * @author    Nicola Franchini <support@veno.it>
 * @copyright 2013 Nicola Franchini
 * @license   https://veno.es/shop/help Veno Commercial License
 * @link      http://filemanager.veno.it/
 */
if (!defined('VFM_APP') || !isset($gateKeeper) || !$gateKeeper->canSuperAdmin('superadmin_can_translations')) {
    die('Direct access not allowed or insufficient permissions.');
}

if ($get_action == 'update') {
    if (defined('VFM_DEMO') && VFM_DEMO === true) {
        Utils::setError('Translation changes not available in demo mode');
    } else {

    $postnewlang = filter_input(INPUT_POST, "thenewlang", FILTER_SANITIZE_SPECIAL_CHARS);
    $getremove = filter_input(INPUT_GET, "remove", FILTER_SANITIZE_SPECIAL_CHARS);

    // --- RIMOZIONE ---
    if ($getremove && strlen($getremove) > 0) {
        $getremove = preg_replace('/[^a-zA-Z0-9_\-]/', '', basename($getremove));
        
        if (!isset($translations_index[$getremove])) {
             Utils::setError('Invalid language selection');
        } else {
            // Proviamo a rimuovere da _content (le lingue originali in /translations/ solitamente non si eliminano via web)
            $langtoremove = "_content/translations/" . $getremove . ".php";

            if (!file_exists($langtoremove) || !unlink($langtoremove)) {
                Utils::setError('Custom language "'.$getremove.'" does not exist');
            } else {
                unset($translations_index[$getremove]);
                file_put_contents($jsonindex, json_encode($translations_index, JSON_FORCE_OBJECT));
                Utils::setSuccess($setUp->getString("language_removed"));
            }
        }

    } elseif ($postnewlang && strlen($postnewlang) > 0) {

        $target_lang = preg_replace('/[^a-zA-Z0-9_\-]/', '', basename($postnewlang));
        
        $core_file = 'translations/' . $target_lang . '.php';
        $custom_dir = '_content/translations/';
        $custom_file = $custom_dir . $target_lang . '.php';

        /**
         * LOGICA RICHIESTA:
         * 1. Se il file esiste in /translations/ -> Salva in /_content/translations/
         * 2. Se il file NON esiste in /translations/ -> Salva in /translations/ (Nuova lingua base)
         */
        if (file_exists($core_file)) {
            // Esiste nel core, quindi lavoriamo sulla cartella custom
            if (!is_dir($custom_dir)) {
                mkdir($custom_dir, 0755, true);
            }
            $final_save_path = $custom_file;
        } else {
            // Non esiste nel core, è una lingua nuova: salviamola in translations/
            $final_save_path = $core_file;
        }

        // Prepariamo l'array delle traduzioni
        $_TRANSLATIONSEDIT = array();
        foreach ($baselang as $key => $value) {
            $postkey = filter_input(INPUT_POST, $key, FILTER_SANITIZE_SPECIAL_CHARS);
            $_TRANSLATIONSEDIT[$key] = ($postkey !== null) ? $postkey : $value;
        }

        // Aggiorna l'indice JSON
        $langname = $_TRANSLATIONSEDIT['LANGUAGE_NAME'];
        $translations_index[$target_lang] = $langname;
        file_put_contents($jsonindex, json_encode($translations_index, JSON_FORCE_OBJECT));

        // Prepariamo il file PHP
        $trans_content = "<?php\n\n\$_TRANSLATIONS = " . var_export($_TRANSLATIONSEDIT, true) . ";\n";

        // Salvataggio effettivo nel percorso stabilito
        if (false === file_put_contents($final_save_path, $trans_content)) {
            Utils::setError('Error saving file: ' . $final_save_path);
        } else {
            Utils::setSuccess($setUp->getString("language_updated"));
            $updater->clearCache('translations/' . $target_lang . '.php');
        }
    }
    } // end else !VFM_DEMO
}
