<?php

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

use Gettext\Translations;
use Gettext\Translation;
use Gettext\Loader\PoLoader;
use Gettext\Generator\PoGenerator;
use Gettext\Generator\MoGenerator;


$cms_root_path = "../../";
require_once($cms_root_path."includes/compatibility_includer.php");

require('classes/class.simplemodelmodulebuilder.php'); // MODEL SETTINGS
require('includes/settings.php'); // MODEL SETTINGS

$model_class_name = MODEL_CLASS_NAME;
$new_object = true;
$page_meta['title'] = 'Add '.ucwords(MODEL_SINGULAR);
if ( isset($_GET['id']) && is_numeric($_GET['id']) ) {
    $model_object = $model_class_name::find($_GET['id']);

    if ( $model_object !== null ) {
        $page_meta['title'] = 'Edit '.ucwords(MODEL_SINGULAR);
        $new_object = false;
    } else {
        $model_object = new $model_class_name();
        unset($_GET['id']);
    }
} else {
    $model_object = new $model_class_name();
    unset($_GET['id']);
}

if ( !empty($_GET['action']) && $_GET['action'] === "scan" ) {

    // Cache all twig templates to get a php version of them so we can extract gettext functions
    if (is_dir("cache")) {
        CmsHelper::recursivelyRmdir("cache");
    }
    mkdir("cache");

    $template_paths_for_false_cache = $template_paths;
    $template_paths_for_false_cache[] = rtrim(SITE_PATH, '/').'/';

    $loader = new FilesystemLoader($template_paths_for_false_cache);
    $temp_twig = new Environment($loader, [
            'cache'           => 'cache/',
            'auto_reload'     => true,
            'strict_variables'=> false,
    ]);

    //$temp_twig->addExtension(new Twig_Extensions_Extension_I18n());

    // iterate over all your templates
    foreach ($template_paths_for_false_cache as $template_directory) {
        $it = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($template_directory, \FilesystemIterator::SKIP_DOTS),
                RecursiveIteratorIterator::LEAVES_ONLY
        );

        foreach ($it as $fileInfo) {
            if (!$fileInfo->isFile()) { continue; }
            $path = $fileInfo->getPathname();
            if (!preg_match('/\.twig$/i', $path)) { continue; }

            // Make it a template name relative to its base directory
            $relative = ltrim(str_replace($template_directory, '', $path), DIRECTORY_SEPARATOR);
            $relative = str_replace(DIRECTORY_SEPARATOR, '/', $relative);

            try {
                $temp_twig->load($relative); // compiles to cache
            } catch (\Throwable $e) {
                // swallow; we just want to precompile what we can
            }
        }
    }


    $files = array();
    $files = $model_object->iterateThroughTemplates(SITE_PATH);
    foreach ($files as $file) {
        $content = file_get_contents($file);
        $found = Language::getTranslatables($content, $file);   // ⬅ pass filename
        if (isset($new_translations)) {
            $new_translations->mergeWith($found);
        } else {
            $new_translations = $found;
        }
    }



    $po_path = $path.Language::$locale_path.'/'.$model_object->localisation.'/LC_MESSAGES/'.$model_object->domain.'.po';

    if (file_exists($po_path)) {
        $translations = (new PoLoader())->loadFile($po_path);
        if (!empty($new_translations)) {
            $translations->mergeWith($new_translations);
        }
    } else {
        if (!is_dir(dirname($po_path))) {
            mkdir(dirname($po_path), 0777, true);
        }
        $translations = $new_translations ?? Translations::create($model_object->domain ?? 'messages', $model_object->localisation ?? null);
    }

// Save to file
    (new PoGenerator())->generateFile($translations, $po_path);

    header("Location: edit_gettext.php?id=".$model_object->id);
    exit();
}

    if (!empty($_POST['action']) && $_POST['action'] === "update") {
        $translations = Translations::create();  // factory

        $total = isset($_POST['source']) ? count($_POST['source']) : 0;
        for ($i = 0; $i < $total; $i++) {
            $ctx = $_POST['context'][$i] ?? '';
            $src = $_POST['source'][$i] ?? '';
            $val = clean_page($_POST['translation'][$i] ?? '');
            if ($src === '') continue;

            $t = \Gettext\Translation::create($ctx, $src);
            $t->setTranslation($val);
            $translations->add($t);  // ⬅ use add()
        }

        $po_path = $path.Language::$locale_path.'/'.$model_object->localisation.'/LC_MESSAGES/'.$model_object->domain.'.po';
        (new PoGenerator())->generateFile($translations, $po_path);
        header("Location: edit_gettext.php?id=".$model_object->id); exit();
    }


if ( !empty($_GET['action']) && $_GET['action'] === "commit" ) {
    $po_path = $path.Language::$locale_path.'/'.$model_object->localisation.'/LC_MESSAGES/'.$model_object->domain.'.po';
    $mo_path = $path.Language::$locale_path.'/'.$model_object->localisation.'/LC_MESSAGES/'.$model_object->domain.'.mo';

    $translations = (new PoLoader())->loadFile($po_path);
    $translations->setDomain(CMS_TEXT_DOMAIN);

    (new MoGenerator())->generateFile($translations, $mo_path);
    header("Location: edit_gettext.php?id=".$model_object->id); exit();
}

include("includes/edit__after-model_object-init.php");

$form_messages = array(
    'success' => array(),
    'error' => array(),
    'alert' => array()
);

include("includes/edit__before-output.php");

/*************************************************************************************************************************************
 *                                                      OUTPUT
*************************************************************************************************************************************/

include($core_root_path.'admin/templates/adminheader.html.php');

?>

<!-- MODULE JS FILES -->
<script type="text/javascript" src="js/script.js"></script>
<!-- end of MODULE JS FILES -->


<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <?php /* ANY PARENT PAGES */ ?>
    <li><a href="manage.php"><?='Manage '.ucwords(MODEL_PRULAR);?></a> /</li>
    <li class="end"><?= $page_meta['title'] ?></li>
</ul>

<h1><?= $page_meta['title'] ?></h1>

<ul class="tabnav el">
    <li><a href="/cms/admin/<?=MODEL_FOLDER?>/manage.php">Manage</a></li>
    <li class="selected"><a href="/cms/admin/<?=MODEL_FOLDER?>/edit.php<?=$new_object ? '' : '?id='.clean_page($_GET['id'])?>"><?=$new_object ? 'Add' : 'Edit'?></a></li>
</ul>

<?php

/* ALERTS */
if ( isset($_SESSION['model_form']['success']) && !empty($_SESSION['model_form']['success']) ) {
    $form_messages['success'] = array_merge($form_messages['success'], $_SESSION['model_form']['success']);
    unset($_SESSION['model_form']['success']);
}
if ( isset($_SESSION['model_form']['error']) && !empty($_SESSION['model_form']['error']) ) {
    $form_messages['error'] = array_merge($form_messages['error'], $_SESSION['model_form']['error']);
    unset($_SESSION['model_form']['error']);
}
if ( isset($_SESSION['model_form']['alert']) && !empty($_SESSION['model_form']['alert']) ) {
    $form_messages['alert'] = array_merge($form_messages['alert'], $_SESSION['model_form']['alert']);
    unset($_SESSION['model_form']['alert']);
}

foreach ($form_messages as $class => $messages) {
    if ( empty($messages) ) {
        continue;
    }
    echo '<div class="el msg '.$class.'">';
    foreach ($messages as $key => $message) {
        echo "<p>".$message."</p>";
    }
    echo '</div>';
}

?>
<form action="edit_gettext.php<?=(!$new_object?'?id='.clean_page($_GET['id']):'')?>" method="POST" enctype="multipart/form-data" class="style moduleBuilder">
    <fieldset class="show">

        <div class="row">
            <button class="button btn">Save</button>
            <a href="edit_gettext.php?id=<?=$model_object->id?>&action=scan"><button class="button btn" type="button">Scan Files For More Translatables</button></a>
            <a href="edit_gettext.php?id=<?=$model_object->id?>&action=commit"><button class="button btn" type="button">Commit</button></a>
        </div>

        <table class="manage-items">

          <thead>
            <tr>
              <th>Context</th>
              <th>Source</th>
              <th>Translation</th>
            </tr>
          </thead>

          <tbody class="tabular">

            <?php

                $po_path = $path.Language::$locale_path.'/'.$model_object->localisation.'/LC_MESSAGES/'.$model_object->domain.'.po';

                $translations = file_exists($po_path)
                        ? (new PoLoader())->loadFile($po_path)
                        : Translations::create($model_object->domain ?? 'messages', $model_object->localisation ?? null);

                if (!empty($new_translations)) {
                    $translations->mergeWith($new_translations);
                }


                foreach ($translations as $key => $translation) {

                ?>
                <tr>
                  <td style="">
                    <input type="text" name="context[]" value="<?=$translation->getContext()?>" style="width:85%">
                  </td>
                  <td style="width:37%">
                    <?=$translation->getOriginal()?>
                    <input type="hidden" name="source[]" value="<?=$translation->getOriginal()?>" >
                    </td>
                  <td style="width:53%">
                    <input type="text" name="translation[]" value="<?=$translation->getTranslation()?>" style="width:95%">
                  </td>
                </tr>
                <?php

            }

            ?>


          </tbody>

        </table>

        <input type="hidden" name="action" value="update"/>
        <input type="hidden" name="data[<?=MODEL_CLASS_NAME?>][id]" value="<?=clean_page($_GET['id'])?>"/>

        <div class="row">
            <button class="button btn">Save</button>
            <a href="edit_gettext.php?id=<?=$model_object->id?>&action=scan"><button class="button btn" type="button">Scan Files For More Translatables</button></a>
            <a href="edit_gettext.php?id=<?=$model_object->id?>&action=commit"><button class="button btn" type="button">Commit</button></a>
        </div>

    </fieldset>
</form>

<?php
include($core_root_path.'admin/templates/adminfooter.html.php');
