<?php

use Twig\Environment;

$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;
    // push in site_path to fetch templates that maybe are in an extraordinary directory
    array_push($template_paths_for_false_cache, SITE_PATH."/");
    $temp_loader = new Twig_Loader_Filesystem($template_paths);

    // force auto-reload to always have the latest version of the template
    $temp_twig = new Environment($temp_loader, array(
        '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 $key => $template_directory) {
        foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($template_directory), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
            // force compilation
            if ($file->isFile() && preg_match("/\.twig$/", $file)) {
                try {
                    $temp_twig->loadTemplate($file);
                } catch (Exception $e) { }
                try {
                    $temp_twig->loadTemplate(str_replace($template_directory, '', $file));
                } catch (Exception $e) {}
            }
        }
    }

    $files = array();
    $files = $model_object->iterateThroughTemplates(SITE_PATH);
    $sources = array();
    foreach ($files as $key => $file) {
        $content = file_get_contents($file);
        if ( isset($new_translations) ) {
            $new_translations->mergeWith(
                Language::getTranslatables($content)
            );
        } else {
            $new_translations = Language::getTranslatables($content);
        }
    }

    $result = $new_translations->toPhpArrayString();

    $po_path = $path.Language::$locale_path.'/'.$model_object->localisation.'/LC_MESSAGES/'.$model_object->domain.'.po';
    if ( file_exists($po_path) ) {
        $translations = Gettext\Extractors\Po::fromFile($po_path);
        if ( !empty($new_translations) ) {
            $translations->mergeWith($new_translations);
        }
    } else {

        if ( !is_dir($path.Language::$locale_path.'/'.$model_object->localisation.'/LC_MESSAGES/') ) {
            if ( mkdir($path.Language::$locale_path.'/'.$model_object->localisation.'/LC_MESSAGES/', 0777, true) === false ) {
                echo 'can\'t create dir';
            }
        }

        $translations = $new_translations;
    }

    //Save to a file
    Gettext\Generators\Po::toFile($translations, $po_path);

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

if ( !empty($_POST['action']) && $_POST['action'] === "update" ) {

    $translations = new Gettext\Translations();
    for ($i=0; $i < count($_POST['source']); $i++) {
        $translation = new Gettext\Translation($_POST['context'][$i], $_POST['source'][$i]);
        $translation->setTranslation(clean_page($_POST['translation'][$i]));
        $translations[] = $translation;
    }
    $po_path = $path.Language::$locale_path.'/'.$model_object->localisation.'/LC_MESSAGES/'.$model_object->domain.'.po';
    //Save to a file
    Gettext\Generators\Po::toFile($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 = Gettext\Extractors\Po::fromFile($po_path);
    $translations->setDomain(CMS_TEXT_DOMAIN);
    Gettext\Generators\Mo::toFile($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 = new Gettext\Translations();

            if ( file_exists($po_path) ) {
                $translations = Gettext\Extractors\Po::fromFile($po_path);
            }

            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');
