<?php

use Carbon\Carbon;
use Mtc\Shop\StandardTemplateLetter;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

init_request_values([
    'id' => null,
]);

$display_form = true;
$errors = [];

$standardTemplateLetter = StandardTemplateLetter::query()
    ->findOrNew($_REQUEST['id']);

$addedit = !empty($_REQUEST['id']) ?
    'Update' :
    'Add';

$page_meta['title'] = $addedit . ' Template';

if ($_REQUEST['action'] == 'add') {

    if ($_REQUEST['title'] == '') {
        $errors['title'] = 'You did not enter a title for this letter';
    }

    if (sizeof($errors) == 0) {
        $standardTemplateLetter->fill($_REQUEST);
        $standardTemplateLetter->timestamp = Carbon::now();
        $standardTemplateLetter->save();
    }
}

require_once $path . 'core/admin/templates/adminheader.html.php';
?>

    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>

        <li><a href="manage.letter.templates.php">Default Email Text</a> /</li>

        <li class="end"><?= clean_page($addedit) ?> Email Template</li>
    </ul>

    <h1><?= clean_page($addedit) ?> Email Template</h1>
<?php

include 'tabnav.php';

if ($display_form === true) {

    if (!empty($errors)) {
        showerrors($errors);
    }

    if (empty($errors) && isset($_REQUEST['action'])) {
        echo showmsg("Template updated", "success", $path);
    }

    ?>

    <form action="" method="post" enctype="multipart/form-data" class="style">
        <fieldset class="show">
            <h1>
                <a class="show el">
                    Email Template <i class="fa fa-caret-right"></i>
                </a>
            </h1>
            <div class="row">
                <label for="title">
                    Title
                </label>
                <input type="text"
                       name="title"
                       id="title"
                       value="<?= $standardTemplateLetter->title ?? null ?>"
                       class="INPUT1"
                />
            </div>
            <div class="row">
                <label for="template">
                    Template
                </label>
                <textarea name="template"
                          rows="14"
                          cols="50"
                          class="simpletinymce"
                ><?= $standardTemplateLetter->template ?? null ?></textarea>
            </div>

        </fieldset>

        <div class="row">
            <input type="hidden" name="action" value="add"/>
            <input type="hidden" name="id" value="<?= $_REQUEST['id']; ?>"/>
            <input type="submit" value="Save"/>
        </div>

    </form>
    <?php
} else {
    ?>
    <div>
        Standard Template Letter has been added/updated.
    </div>
    <?php
}
?>

<?php
require_once $path . 'core/admin/templates/adminfooter.html.php';
