<?php
/* Copyright (C) 2004-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
 * Copyright (C) 2020      MB Informatique      <info@mb-informatique.fr>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

/**
 * \file    mbisignature/admin/setup.php
 * \ingroup mbisignature
 * \brief   MBISignature setup page.
 */

// Load Dolibarr environment
$res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
// Try main.inc.php using relative path
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
if (!$res) die("Include of main fails");

global $langs, $user, $conf, $db;

// Libraries
require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
require_once '../lib/mbisignature.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
dol_include_once("/mbisignature/core/modules/modMBISignature.class.php");

$langs->loadLangs(array("admin", "mbisignature@mbisignature", "propal", "orders", "contracts", "sendings", "interventions", "withdrawals", "deliveries"));

// Access control
if (!$user->admin) accessforbidden();

// Parameters
$action = GETPOST('action', 'alpha');
$backtopage = GETPOST('backtopage', 'alpha');

$arrayofparameters = array(
    'SIGNATURE_TEMPLATE'=>array('css'=>'minwidth500', 'enabled'=>1),
    'SIGNATURE_TEMPLATE_PROPAL'=>array('css'=>'minwidth500', 'enabled'=>1),
    'SIGNATURE_TEMPLATE_ORDER'=>array('css'=>'minwidth500', 'enabled'=>1),
    'SIGNATURE_TEMPLATE_SUPPLIER_ORDER'=>array('css'=>'minwidth500', 'enabled'=>1),
    'SIGNATURE_TEMPLATE_CONTRACT'=>array('css'=>'minwidth500', 'enabled'=>1),
    'SIGNATURE_TEMPLATE_EXPEDITION'=>array('css'=>'minwidth500', 'enabled'=>1),
    'SIGNATURE_TEMPLATE_DELIVERY'=>array('css'=>'minwidth500', 'enabled'=>1),
    'SIGNATURE_TEMPLATE_EXPENSE_REPORT'=>array('css'=>'minwidth500', 'enabled'=>1),
    'SIGNATURE_TEMPLATE_INTERVENTION'=>array('css'=>'minwidth500', 'enabled'=>1),
    'SIGNATURE_TEMPLATE_SEPA_MANDATE'=>array('css'=>'minwidth500', 'enabled'=>1),
    'SIGNATURE_TEMPLATE_HOLIDAY'=>array('css'=>'minwidth500', 'enabled'=>1)
);

/*
 * Actions
 */

if ((float) DOL_VERSION >= 6) { include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; }

/*
 * View
 */

$page_name = "MBISignatureSetup";
llxHeader('', $langs->trans($page_name));

// Subheader
$linkback = '<a href="'.($backtopage ? $backtopage : DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1').'">'.$langs->trans("BackToModuleList").'</a>';

print load_fiche_titre($langs->trans($page_name), $linkback, 'object_logo@mbisignature');

$mbisignature = new modMBISignature($db);

// Configuration header
$head = mbisignatureAdminPrepareHead();
dol_fiche_head($head, 'mail_templates', '', -1, "mbisignature@mbisignature");

// Setup page goes here
echo '<span class="opacitymedium">'.$langs->trans("MBISignatureSetupPage").'</span><br><br>';

print '<form method="POST" action="' . $_SERVER["PHP_SELF"] . '">';
print '<input type="hidden" name="token" value="' . newToken() . '">';
print '<input type="hidden" name="action" value="update">';

print '<table class="noborder centpercent">';
print '<tr class="liste_titre"><td class="titlefield">' . $langs->trans("Parameter") . '</td><td>' . $langs->trans("Value") . '</td></tr>';

foreach ($arrayofparameters as $key => $val) {
    print '<tr class="oddeven"><td>';
    $tooltiphelp = (($langs->trans($key . 'Tooltip') != $key . 'Tooltip') ? $langs->trans($key . 'Tooltip') : '');

    if ($key == "SIGNATURE_TEMPLATE_PROPAL") {
        print $form->textwithpicto($langs->trans("Proposals"), $tooltiphelp);
    } else if ($key == "SIGNATURE_TEMPLATE_ORDER") {
        print $form->textwithpicto($langs->trans("Orders"), $tooltiphelp);
    } else if ($key == "SIGNATURE_TEMPLATE_SUPPLIER_ORDER") {
        print $form->textwithpicto($langs->trans("SuppliersOrders"), $tooltiphelp);
    } else if ($key == "SIGNATURE_TEMPLATE_CONTRACT") {
        print $form->textwithpicto($langs->trans("Contracts"), $tooltiphelp);
    } else if ($key == "SIGNATURE_TEMPLATE_EXPEDITION") {
        print $form->textwithpicto($langs->trans("Shipments"), $tooltiphelp);
    } else if ($key == "SIGNATURE_TEMPLATE_DELIVERY") {
        print $form->textwithpicto($langs->trans("Receivings"), $tooltiphelp);
    } else if ($key == "SIGNATURE_TEMPLATE_EXPENSE_REPORT") {
        print $form->textwithpicto($langs->trans("ExpenseReports"), $tooltiphelp);
    } else if ($key == "SIGNATURE_TEMPLATE_INTERVENTION") {
        print $form->textwithpicto($langs->trans("Interventions"), $tooltiphelp);
    } else if ($key == "SIGNATURE_TEMPLATE_SEPA_MANDATE") {
        print $form->textwithpicto($langs->trans("SepaMandate"), $tooltiphelp);
    } else if ($key == "SIGNATURE_TEMPLATE_HOLIDAY") {
        print $form->textwithpicto($langs->trans("CPTitreMenu"), $tooltiphelp);
    } else {
        print $form->textwithpicto($langs->trans($key), $tooltiphelp);
    }

    if ($key == "SIGNATURE_TEMPLATE" || $key == "SIGNATURE_TEMPLATE_PROPAL" || $key == "SIGNATURE_TEMPLATE_ORDER" || $key == "SIGNATURE_TEMPLATE_SUPPLIER_ORDER" || $key == "SIGNATURE_TEMPLATE_CONTRACT" || $key == "SIGNATURE_TEMPLATE_EXPEDITION" || $key == "SIGNATURE_TEMPLATE_DELIVERY" || $key == "SIGNATURE_TEMPLATE_EXPENSE_REPORT" || $key == "SIGNATURE_TEMPLATE_INTERVENTION" || $key == "SIGNATURE_TEMPLATE_SEPA_MANDATE" || $key == "SIGNATURE_TEMPLATE_HOLIDAY") {
        include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
        $doleditor = new DolEditor($key, $conf->global->$key, '', 200, 'dolibarr_mailings');
        $subject_key = $key . "_SUBJECT";
        print '</td><td><b>' . $langs->trans("Subject") . ' </b><input type="text" name="' . $subject_key . '" value="' . $conf->global->$subject_key . '" class="flat ' . (empty($val['css']) ? 'minwidth200' : $val['css']) . '"><br>' . $langs->trans("Content") . '<br>';
        print $doleditor->Create();
        print '</td></tr>';
        if ($action == 'update') {
            $db->begin();
            $result = dolibarr_set_const($db, $key, $_POST[$key], 'chaine', 0, '', $conf->entity);
            $result = dolibarr_set_const($db, $key . "_SUBJECT", $_POST[$key . "_SUBJECT"], 'chaine', 0, '', $conf->entity);
            $db->commit();
            echo '<form method="POST" action="' . $_SERVER["PHP_SELF"] . '">';
            echo '<input type="hidden" name="action" value="updated">';
            echo '<input id="submitAfter" style="display: none;" class="button" type="submit">';
            echo '</form>';
            echo "<script>document.getElementById('submitAfter').click();</script>";
        }
        if ($action == 'updated') {
            if (!$error) {
                $db->commit();
                if (empty($nomessageinupdate)) setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
            } else {
                $db->rollback();
                if (empty($nomessageinupdate)) setEventMessages($langs->trans("SetupNotSaved"), null, 'errors');
            }
        }
    }
}
print '</table>';
print '<div class="center"><input class="button" type="submit" value="' . $langs->trans("Save") . '"></div>';

print '</form>';

// Page end
dol_fiche_end();

llxFooter();
$db->close();
