<?php
/* Copyright (C) 2001-2002	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
 * Copyright (C) 2006-2017	Laurent Destailleur		<eldy@users.sourceforge.net>
 * Copyright (C) 2009-2012	Regis Houssin			<regis.houssin@inodbox.com>
 * Copyright (C) 2020-2021  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/newonlinesign.php
 *		\ingroup    mbisignature
 *		\brief      File to offer a way to make an online signature
 */

if (!defined('NOLOGIN'))		define("NOLOGIN", 1); // This means this output page does not require to be logged.
if (!defined('NOCSRFCHECK'))	define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
if (!defined('NOIPCHECK'))		define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip

// TODO This should be useless. Because entity must be retreive from object ref and not from url.
$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
if (is_numeric($entity)) define("DOLENTITY", $entity);

try {
    if (!file_exists('../../main.inc.php'))
        throw new Exception ('Does not exist');
    else
        require '../../main.inc.php';
}
catch(Exception $e) {
    require '../main.inc.php';
}
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';

$langs->loadLangs(array("main", "other", "dict", "bills", "companies", "errors", "paybox", "mbisignature@mbisignature", "propal", "holiday"));

$suffix = GETPOST("suffix", 'aZ09');
$source = GETPOST("source", 'alpha');
$ref = GETPOST("ref", 'alpha');
$company = GETPOST("company", 'alpha');

global $user;
$urlwithroot = DOL_MAIN_URL_ROOT;
$creditor = $mysoc->name;

// View

$head = '';
if (!empty($conf->global->MAIN_SIGN_CSS_URL)) $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MAIN_SIGN_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n";
$head .= '<link rel="stylesheet" type="text/css" href="scripts/materialize.css">'."\n";

$conf->dol_hide_topmenu = 1;
$conf->dol_hide_leftmenu = 1;

$replacemainarea = (empty($conf->dol_hide_leftmenu) ? '<div>' : '').'<div>';
llxHeader($head, $langs->trans("ONLINESIGNATUREPAGETITLE"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea);

if (!empty($conf->global->SIGNATURE_CUSTOM_CSS) && $conf->global->SIGNATURE_CUSTOM_CSS !== "") {
    echo "<style>" . $conf->global->SIGNATURE_CUSTOM_CSS . "</style>";
}

print '<div class="center">';
print '<table id="dolpaymenttable" class="center">';

// Show logo (search order: logo defined by ONLINE_SIGN_LOGO_suffix, then ONLINE_SIGN_LOGO_, then small company logo, large company logo, theme logo, common logo)
$width = 0;
// Define logo and logosmall
$logosmall = $mysoc->logo_small;
$logo = $mysoc->logo;
$paramlogo = 'ONLINE_SIGN_LOGO_'.$suffix;
if (!empty($conf->global->$paramlogo)) $logosmall = $conf->global->$paramlogo;
elseif (!empty($conf->global->ONLINE_SIGN_LOGO)) $logosmall = $conf->global->ONLINE_SIGN_LOGO;
//print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n";
// Define urllogo
$urllogo = '';
$urllogofull = '';
if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) {
    $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall);
    $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall);
    $height = 130;
}
else if (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) {
    $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo);
    $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo);
    $height = 130;
}
// Output html code for logo
if ($urllogo) {
    print '<div class="backgreypublicpayment" style="background-color: #fcfcfc; padding: 12px;">';
    print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
    if ($height) print ' style="height:'.$height.'px;"';
    print '>';
    print '</div>';
}

// Output introduction text
$text = '';
if (!empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT)) {
    $langs->load("members");
    if (preg_match('/^\((.*)\)$/', $conf->global->ONLINE_SIGN_NEWFORM_TEXT, $reg)) $text .= $langs->trans($reg[1])."<br>";
    else $text .= $conf->global->ONLINE_SIGN_NEWFORM_TEXT."<br>";
    $text = '<tr><td><br>'.$text.'<br></td></tr>';
}
if ($source == "proposal") {
    $welcomeMessage = $langs->trans("PAGESIGNPROPOSALWELCOME");
    $allowMessage = $langs->trans("PAGESIGNPROPOSALALLOW");
} else if ($source == "order") {
    $welcomeMessage = $langs->trans("PAGESIGNORDERWELCOME");
    $allowMessage = $langs->trans("PAGESIGNORDERALLOW");
}  else if ($source == "ordersupplier") {
    $welcomeMessage = $langs->trans("PAGESIGNORDERWELCOME");
    $allowMessage = $langs->trans("PAGESIGNORDERALLOW");
} else if ($source == "expedition") {
    $welcomeMessage = $langs->trans("PAGESIGNEXPEDITIONWELCOME");
    $allowMessage = $langs->trans("PAGESIGNEXPEDITIONALLOW");
} else if ($source == "delivery") {
    $welcomeMessage = $langs->trans("PAGESIGNDELIVERYWELCOME");
    $allowMessage = $langs->trans("PAGESIGNDELIVERYALLOW");
} else if ($source == "intervention") {
    $welcomeMessage = $langs->trans("PAGESIGNINTERVENTIONWELCOME");
    $allowMessage = $langs->trans("PAGESIGNINTERVENTIONALLOW");
} else if ($source == "contract") {
    $welcomeMessage = $langs->trans("PAGESIGNCONTRACTWELCOME");
    $allowMessage = $langs->trans("PAGESIGNCONTRACTALLOW");
} else if ($source == "sepamandate") {
    $welcomeMessage = $langs->trans("PAGESIGNSEPAMANDATEWELCOME");
    $allowMessage = $langs->trans("PAGESIGNSEPAMANDATEALLOW");
} else if ($source == "holiday") {
    $welcomeMessage = $langs->trans("PAGESIGNHOLIDAYWELCOME");
    $allowMessage = $langs->trans("PAGESIGNHOLIDAYALLOW");
} else if ($source == "expensereport") {
    $welcomeMessage = $langs->trans("PAGESIGNEXPENSEREPORTWELCOME");
    $allowMessage = $langs->trans("PAGESIGNEXPENSEREPORTALLOW");
} else if ($source == "agefodd_convention") {
    $langs->load("agefodd@agefodd");
    $agsession = new Agsession($db);
    $agsession->fetch($ref);
    $welcomeMessage = $langs->trans("PAGESIGNAGFWELCOME");
    $allowMessage = $langs->trans("PAGESIGNAGFALLOW") . " " . $agsession->ref;
}
if (empty($text)) {
    $text .= '<tr><td class="textpublicpayment"><br><strong>'. $welcomeMessage . ' ' . $mysoc->name.'</strong></td></tr>';
    $text .= '<tr><td class="textpublicpayment">' . $allowMessage . '<br><br></td></tr>';
}
print $text;

// Output payment summary form
print '<tr><td align="center">';
print '<table with="100%" id="tablepublicpayment">';
print '<tr><td style="text-align: left;" colspan="2" class="opacitymedium">'.$langs->trans("PAGESIGNINFO").'</td></tr>';

$found = false;
$error = 0;

if ($source == 'proposal') {
    $found = true;
    require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
    $object = new Propal($db);
    $result = $object->fetch('', $ref);
    $objectOfSignature = $langs->trans("PAGESIGNPROPOSAL");
    if ($result <= 0) {
        $mesg = $object->error;
        $error++;
    } else {
        $result = $object->fetch_thirdparty($object->socid);
    }
}

if ($source == 'order') {
    $found = true;
    require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
    $object = new Commande($db);
    $result = $object->fetch('', $ref);
    $objectOfSignature = $langs->trans("PAGESIGNORDER");
    if ($result <= 0) {
        $mesg = $object->error;
        $error++;
    } else {
        $result = $object->fetch_thirdparty($object->socid);
    }
}

if ($source == 'ordersupplier') {
    $found = true;
    require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
    $object = new CommandeFournisseur($db);
    $result = $object->fetch('', $ref);
    $objectOfSignature = $langs->trans("PAGESIGNORDER");
    if ($result <= 0) {
        $mesg = $object->error;
        $error++;
    } else {
        $result = $object->fetch_thirdparty($object->socid);
    }
}

if ($source == 'expedition') {
    $found = true;
    require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
    $object = new Expedition($db);
    $result = $object->fetch('', $ref);
    $objectOfSignature = $langs->trans("PAGESIGNEXPEDITION");
    if ($result <= 0) {
        $mesg = $object->error;
        $error++;
    } else {
        $result = $object->fetch_thirdparty($object->socid);
    }
}

if ($source == 'delivery') {
    $found = true;
    require_once DOL_DOCUMENT_ROOT.'/delivery/class/delivery.class.php';
    $object = new Delivery($db);
    $resql=$db->query("SELECT rowid FROM " . MAIN_DB_PREFIX . "delivery WHERE ref = '" . $ref . "'");
    if ($resql) {
        $num = $db->num_rows($resql);
        if ($num) {
            $obj = $db->fetch_object($resql);
            if ($obj) {
                $result = $object->fetch($obj->rowid);
            }
        }
    }
    $objectOfSignature = $langs->trans("PAGESIGNDELIVERY");
    if ($result <= 0) {
        $mesg = $object->error;
        $error++;
    } else {
        $result = $object->fetch_thirdparty($object->socid);
    }
}

if ($source == 'intervention') {
    $found = true;
    require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
    $object = new Fichinter($db);
    $result = $object->fetch('', $ref);
    $objectOfSignature = $langs->trans("PAGESIGNINTERVENTION");
    if ($result <= 0) {
        $mesg = $object->error;
        $error++;
    } else {
        $result = $object->fetch_thirdparty($object->socid);
    }
}

if ($source == 'contract') {
    $found = true;
    require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
    $object = new Contrat($db);
    $result = $object->fetch('', $ref);
    $objectOfSignature = $langs->trans("PAGESIGNCONTRACT");
    if ($result <= 0) {
        $mesg = $object->error;
        $error++;
    } else {
        $result = $object->fetch_thirdparty($object->socid);
    }
}

if ($source == 'sepamandate') {
    $found = true;
    require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
    $object = new Societe($db);
    $result = $object->fetch($ref);

    require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';

    $companybankaccount = new CompanyBankAccount($db);
    $companybankaccount->fetch('', $object->id);

    $objectOfSignature = $langs->trans("PAGESIGNSEPAMANDATE");
    if ($result <= 0) {
        $mesg = $object->error;
        $error++;
    }
}

if ($source == 'holiday') {
    $found = true;
    require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
    $object = new Holiday($db);
    $result = $object->fetch('', $ref);
    $objectOfSignature = $langs->trans("PAGESIGNHOLIDAY");
    if ($result <= 0) {
        $mesg = $object->error;
        $error++;
    } else {
        $result = $object->fetch_thirdparty($object->socid);
    }
}

if ($source == 'expensereport') {
    $found = true;
    require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
    $object = new ExpenseReport($db);
    $result = $object->fetch('', $ref);
    $objectOfSignature = $langs->trans("PAGESIGNEXPENSEREPORT");
    if ($result <= 0) {
        $mesg = $object->error;
        $error++;
    } else {
        $result = $object->fetch_thirdparty($object->socid);
    }
}

if ($source == 'agefodd_convention') {
    $found = true;
    $object = new Agefodd_convention($db);
    $result = $object->fetch("", "", $_GET["nconv"]);
    $objectOfSignature = $langs->trans("AgfConvention");
    if ($result <= 0) {
        $mesg = $object->error;
        $error++;
    }
}

if ($source == "agefodd_convention") {
    $object_ref = $agsession->ref;
} else {
    $object_ref = $object->ref;
}

if (strpos($object->modelpdf, '.odt') !== false && $source == "proposal") {
    // $odt = true;
    $odt = false;
} else {
    $odt = false;
}

if ($entity == 1) {
    if ($source == 'proposal') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/propale';
    } else if ($source == 'order') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/commande';
    } else if ($source == 'ordersupplier') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/fournisseur/commande';
    }  else if ($source == 'expedition') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/expedition/sending';
    } else if ($source == 'delivery') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/expedition/receipt';
    } else if ($source == 'intervention') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/ficheinter';
    } else if ($source == 'contract') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/contract';
    } else if ($source == 'holiday') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/holiday';
    } else if ($source == 'expensereport') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/expensereport';
    } else if ($source == 'agefodd_convention') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/agefodd';
    }
} else {
    if ($source == 'proposal') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/propale';
    } else if ($source == 'order') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/commande';
    } else if ($source == 'ordersupplier') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/fournisseur/commande';
    }  else if ($source == 'expedition') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/expedition/sending';
    } else if ($source == 'delivery') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/expedition/receipt';
    } else if ($source == 'intervention') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/ficheinter';
    } else if ($source == 'contract') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/contract';
    } else if ($source == 'holiday') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/holiday';
    } else if ($source == 'expensereport') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/expensereport';
    } else if ($source == 'expensereport') {
        $documentFolderName = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/agefodd';
    }
}
if ($source == "holiday" || $source == "expensereport") {
    $langs->load("holiday");
    print '<tr><td>'.$langs->trans("ReviewedByCP"); // Validator
} else {
    print '<tr><td>'.$langs->trans("Creditor"); // Creditor
}
if ($source == "holiday") {
    $holiday_validator = new User($db);
    $holiday_validator->fetch($object->fk_validator);
    print '</td><td><b>' . $holiday_validator->firstname . ' ' . $holiday_validator->lastname . '</b>';
} else if ($source == "expensereport") {
    $expensereport_validator = new User($db);
    $expensereport_validator->fetch($object->fk_user_validator);
    print '</td><td><b>' . $expensereport_validator->firstname . ' ' . $expensereport_validator->lastname . '</b>';
} else {
    print '</td><td><b>'.$creditor.'</b>';
}
print '<input type="hidden" name="creditor" value="'.$creditor.'"></td></tr>';

if ($source == "holiday" || $source == "expensereport") {
    print '<tr><td>' . $langs->trans("RequestByCP"); // Employee
} else {
    print '<tr><td>' . $langs->trans("ThirdParty"); // Debitor
}
if ($source == 'sepamandate') {
    print '</td><td><b>' . $object->name . '</b></td></tr>';
} else if ($source == 'holiday') {
    $holiday_user = new User($db);
    $holiday_user->fetch($object->fk_user);
    print '</td><td><b>' . $holiday_user->firstname . ' ' . $holiday_user->lastname . '</b></td></tr>';
} else if ($source == 'expensereport') {
    $expensereport_user = new User($db);
    $expensereport_user->fetch($object->fk_user_author);
    print '</td><td><b>' . $expensereport_user->firstname . ' ' . $expensereport_user->lastname . '</b></td></tr>';
} else if ($source == "agefodd_convention") {
    $resqlagf=$db->query("SELECT * FROM " . MAIN_DB_PREFIX . "agefodd_convention WHERE rowid = " . $object->id);
    if ($resqlagf) {
        $numagf = $db->num_rows($resqlagf);
        if ($numagf) {
            $objagf = $db->fetch_object($resqlagf);
            if ($objagf) {
                $conv_fk_societe = new Societe($db);
                $conv_fk_societe->fetch($objagf->fk_societe);
                print '</td><td><b>' . $conv_fk_societe->name . '</b></td></tr>';
            }
        }
    }
} else {
    print '</td><td><b>' . $object->thirdparty->name . '</b></td></tr>';
}

print '<tr><td>'.$langs->trans("Designation"); // Object
if ($source == 'sepamandate') {
    print '</td><td><b>' . $objectOfSignature . ' ' . $object_ref . ' (' . $object->display_rib() . ')</b></td></tr>';
} else {
    if (!empty($conf->global->SIGNATURE_CUSTOM_BUTTON_COLOR) && $conf->global->SIGNATURE_CUSTOM_BUTTON_COLOR !== "" && $conf->global->SIGNATURE_CUSTOM_BUTTON_COLOR !== NULL) {
        $button_color = "background-color: #" . $conf->global->SIGNATURE_CUSTOM_BUTTON_COLOR;
    } else {
        $button_color = "";
    }
    print '</td><td><b>' . $objectOfSignature . ' ' . $object_ref . '</b></td></tr>';
    if ($conf->global->SIGNATURE_DOCUMENT_PREVIEW == "true" && $source !== "holiday" && !$odt) {
        $resqlhash = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_hash WHERE ref = '" . $object_ref . "' AND entity = '" . $entity . "'");
        if ($resqlhash) {
            $num = $db->num_rows($resqlhash);
            if ($num === 1) {
                $hash = $db->fetch_object($resqlhash);
                if ($hash->hash == GETPOST("hashp")) {
                    if ($source == "agefodd_convention") {

                        $resqlagf=$db->query("SELECT * FROM " . MAIN_DB_PREFIX . "agefodd_convention WHERE rowid = " . $object->id);
                        if ($resqlagf) {
                            $numagf = $db->num_rows($resqlagf);
                            if ($numagf) {
                                $objagf = $db->fetch_object($resqlagf);
                                if ($objagf) {
                                    $file = 'convention' . '_' . $objagf->fk_agefodd_session . '_' . $objagf->fk_societe . '_' . $objagf->rowid . '.pdf';
                                }
                            }
                        }

                        copy($documentFolderName . "/" . $file, "temp/" . GETPOST("hashp") . "" . $_GET["nconv"] . ".pdf");
                        if (!@copy($documentFolderName . "/" . $file, "temp/" . GETPOST("hashp") . "" . $_GET["nconv"] . ".pdf")) {
                            echo "<p>La convention n'existe pas, elle doit être générée avant de pouvoir être signée</p>";
                            $errors = error_get_last();
                            dol_syslog("ERROR WHILE COPYING PDF DOCUMENT FROM " . $documentFolderName . "/" . $file . " TO " . "temp/" . GETPOST("hashp") . "" . $_GET["nconv"] . ".pdf --> " . $errors['type'] . " --- " . $errors['message']);
                            exit;
                        }
                    } else {
                        copy($documentFolderName . "/" . $object->ref . "/" . $object->ref . ".pdf", "temp/" . GETPOST("hashp") . ".pdf");
                        if (!copy($documentFolderName . "/" . $object->ref . "/" . $object->ref . ".pdf", "temp/" . GETPOST("hashp") . ".pdf")) {
                            $errors = error_get_last();
                            dol_syslog("ERROR WHILE COPYING PDF DOCUMENT FROM " . $documentFolderName . "/" . $object->ref . "/" . $object->ref . ".pdf TO " . "temp/" . GETPOST("hashp") . ".pdf --> " . $errors['type'] . " --- " . $errors['message']);
                        }
                    }
                    if ($source == "agefodd_convention") {
                        print '<tr id="tempDocPreview"><td>' . $langs->trans("Documents2") . '</td><td><a class="pictopreview documentpreview" href="temp/' . GETPOST("hashp") . "" . $_GET["nconv"] . '.pdf" mime="application/pdf" target="_blank"><input class="butAction" type="button" style="margin-left: 0; margin-top: 10px; appearance: none; -moz-appearance: none; -webkit-appearance: none; ' . $button_color . '" value="' . $langs->trans("SignatureDocumentPreviewText") . '"><i class="far fa-file-pdf fa-2x" style="position: relative; top: 7px; color: #ff0000;"></i></a></td></tr>';
                    } else {
                        print '<tr id="tempDocPreview"><td>' . $langs->trans("Documents2") . '</td><td><a class="pictopreview documentpreview" href="temp/' . GETPOST("hashp") . '.pdf" mime="application/pdf" target="_blank"><input class="butAction" type="button" style="margin-left: 0; margin-top: 10px; appearance: none; -moz-appearance: none; -webkit-appearance: none; ' . $button_color . '" value="' . $langs->trans("SignatureDocumentPreviewText") . '"><i class="far fa-file-pdf fa-2x" style="position: relative; top: 7px; color: #ff0000;"></i></a></td></tr>';
                    }
                }
            }
        }
    }
}

if (!$found && !$mesg) $mesg = $langs->trans("ErrorBadParameters");

if ($mesg) print '<tr><td align="center" colspan="2"><br><div class="warning">'.$mesg.'</div></td></tr>';

print '</table></td></tr></table><br>';

///////////////////////////////////////////

// On vérifie que l'adresse email du client existe

if ($source == "proposal" || $source == "order" || $source == "ordersupplier" || $source == "expedition" || $source == "intervention" || $source == "contract" || $source == "delivery") {
    $contactlist = $object->liste_contact(-1, "external");
    if (empty($contactlist[0]["email"]) || $contactlist[0]["email"] == "" || $contactlist[0]["email"] == NULL) {
        if (empty($object->thirdparty->email) || $object->thirdparty->email == NULL || $object->thirdparty->email == "") {
            exit("<br><b>" . $langs->trans("SignatureClientMailDoesNotExist") . "</b>");
        }
    }
} else if ($source == "agefodd_convention") {
    if (empty($conv_fk_societe->email) || $conv_fk_societe->email == NULL || $conv_fk_societe->email == "") {
        exit("<br><b>" . $langs->trans("SignatureClientMailDoesNotExist") . "</b>");
    }
}

// Si c'est le client qui signe

if (empty($company)) {

    $resqlhash = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_hash WHERE ref = '" . $object_ref . "' AND entity = '" . $entity . "'");
    if ($resqlhash) {
        $num = $db->num_rows($resqlhash);
        if ($num === 1) {
            $hash = $db->fetch_object($resqlhash);
            if ($hash->hash == GETPOST("hashp")) {

                // On vérifie si la signature pour ce devis existe déjà dans la BDD

                if ($source == "agefodd_convention") {
                    $resql = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_agefodd WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND convid = '" . $object->id . "' AND entity = '" . $entity . "'");
                } else {
                    $resql = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND entity = '" . $entity . "'");
                }

                if ($resql) {
                    $num = $db->num_rows($resql);

                    if ($num === 1) { // Si y a déjà une signature pour ce devis dans la BDD
                        echo "<strong>" . $langs->trans("DejaSigné") . "</strong>";
                        if ($source !== "sepamandate" && $source !== "holiday") {
                            if ($conf->global->SIGNATURE_DOCUMENT_PREVIEW == "true" && !$odt) {
                                if ($source == "agefodd_convention") {
                                    unlink("temp/" . GETPOST("hashp") . "" . $_GET["nconv"] . ".pdf");
                                } else {
                                    unlink("temp/" . GETPOST("hashp") . ".pdf");
                                }
                                echo "<script>document.getElementById('tempDocPreview').style.display = 'none';</script>";
                            }
                        }
                    }

                    if ($num === 0) { // Si il n'y a pas de signature pour ce devis dans la BDD
                        echo "<style>input {font-size: 14px;} input:required {border-bottom: 1px solid #000;}</style>";
                        if ($source == "holiday" || $source == "expensereport") {
                            showForm($langs, $langs->trans("AskingUserSignButtonFullText"));
                        } else if ($source == "proposal" && $conf->global->SIGNATURE_PROPAL_CAN_BE_REFUSED == "true") {
                            if (!isset($_POST["accepted"]) && !isset($_POST["refused"]) && !isset($_POST["confirmRefused"]) && !isset($_POST["submitSignature"])) {
                                echo "<br><div>";
                                echo "<form method='post' action=''>";
                                echo "<input class='butActionDelete' style='margin-right: 20px; appearance: none; -moz-appearance: none; -webkit-appearance: none;' value='" . $langs->trans("Deny") . "' type='submit' name='refused'>";
                                echo "<input class='butAction' style='margin-left: 20px; appearance: none; -moz-appearance: none; -webkit-appearance: none;' value='" . $langs->trans("Sign") . "' type='submit' name='accepted'>";
                                echo "</form>";
                                echo "</div>";
                            }
                            if (isset($_POST["accepted"])) {
                                showForm($langs, $langs->trans("SignButtonFullText"));
                            }
                            if (isset($_POST["refused"])) {
                                echo "<br><div><b>" . $langs->trans("DetailRefusCP") . " :</b><br><br>";
                                echo "<form method='post' action=''>";
                                echo "<textarea name='reason' rows='10' cols='46'></textarea><br><br>";
                                echo "<input class='butActionDelete' style='margin-right: 20px; appearance: none; -moz-appearance: none; -webkit-appearance: none;' value='" . $langs->trans("Deny") . "' type='submit' name='confirmRefused'>";
                                echo "</form>";
                                echo "</div>";
                            }
                            if (isset($_POST["confirmRefused"])) {
                                $usercloture = new User($db);
                                $usercloture->fetch(1);
                                if (version_compare(DOL_VERSION, '14.0.0', '<')) { // Changement de méthode pour fermer la proposition commerciale à la version 14 de Dolibarr
                                    $object->cloture($usercloture, 3, $_POST["reason"]);
                                } else {
                                    $object->closeProposal($usercloture, 3, $_POST["reason"]);
                                }
                                echo $langs->trans("PropalClosedRefusedInDolibarr");
                                if ($conf->global->SIGNATURE_DOCUMENT_PREVIEW == "true" && !$odt) {
                                    if ($source == "agefodd_convention") {
                                        unlink("temp/" . GETPOST("hashp") . "" . $_GET["nconv"] . ".pdf");
                                    } else {
                                        unlink("temp/" . GETPOST("hashp") . ".pdf");
                                    }
                                    echo "<script>document.getElementById('tempDocPreview').style.display = 'none';</script>";
                                }
                            }
                        } else {
                            showForm($langs, $langs->trans("SignButtonFullText"));
                        }
                        echo "<script src='scripts/signature_pad.min.js'></script>";
                        echo "<script src='index.js'></script>";

                        if (isset($_POST['image']) && isset($_POST['agree']) && $_POST['client'] !== '' && strlen($_POST['image']) > 3000) { // Si on soumet le formulaire et que tout va bien
                            echo "<script>canvasAndForm.style.display = 'none';</script>";
                            echo "<img id='loadingSignature' src='" . DOL_URL_ROOT . "/custom/mbisignature/img/loader.gif'>";
                            ob_flush();
                            flush();

                            // On passe le statut de la proposition commerciale à "signée" - Le champ fk_user_cloture qui doit contenir l'id de l'utilisateur qui change le statut ne peut pas être renseigné comme la page est accessible sans authentification, il faut donc laisser ce champ à 1

                            if ($source == 'proposal') {
                                $usercloture = new User($db);
                                $usercloture->fetch(1);
                                if (version_compare(DOL_VERSION, '14.0.0', '<')) { // Changement de méthode pour fermer la proposition commerciale à la version 14 de Dolibarr
                                    $object->cloture($usercloture, 2);
                                } else {
                                    $object->closeProposal($usercloture, 2);
                                }
                            }

                            // On insert les données relatives à la signature dans la BDD

                            $db->begin();
                            if ($source == "agefodd_convention") {
                                $db->query("INSERT INTO " . MAIN_DB_PREFIX . "mbi_signature_agefodd (object_type, pathoffile, ip, name, object_id, entity, convid) VALUES ('" . $object_ref . "', '" . $_POST['image'] . "', '" . $_SERVER['REMOTE_ADDR'] . "','" . $_POST['client'] . "', 0, " . $entity . ", " . $object->id . ")");
                            } else {
                                $db->query("INSERT INTO " . MAIN_DB_PREFIX . "mbi_signature (object_type, pathoffile, ip, name, object_id, entity) VALUES ('" . $object_ref . "', '" . $_POST['image'] . "', '" . $_SERVER['REMOTE_ADDR'] . "','" . $_POST['client'] . "', 0, " . $entity . ")");
                            }
                            $db->commit();

                            if ($source == "agefodd_convention") {
                                $resql = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_agefodd WHERE object_type = '" . $object_ref . "' AND object_id = 1 AND convid = '" . $object->id . "' AND entity = '" . $entity . "'");
                            } else {
                                $resql = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature WHERE object_type = '" . $object_ref . "' AND object_id = 1 AND entity = '" . $entity . "'");
                            }

                            if ($resql) {
                                $num = $db->num_rows($resql);

                                if ($num === 1 && ($conf->global->DOUBLE_SIGNATURE == "true" || $source == "intervention" || $source == "delivery" || $source == "contract" || $source == "holiday" || $source == "expensereport" || $source == "agefodd_convention") && ($source == "order" || $source == "ordersupplier" || $source == "expedition" || $source == "intervention" || $source == "delivery" || $source == "contract" || $source == "holiday" || $source == "expensereport" || $source == "agefodd_convention")) {

                                    // On génère une seule fois le pdf

                                    generateDocument($langs, $source, $object, $conf, "_double", $db, $odt, $object_ref);

                                    // On envoie le mail

                                    if ($source == "agefodd_convention") {
                                        $resqlmail = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_agefodd WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND convid = '" . $object->id . "' AND entity = '" . $entity . "'");
                                    } else {
                                        $resqlmail = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND entity = '" . $entity . "'");
                                    }
                                    $objmail = $db->fetch_object($resqlmail);
                                    $clientSignataire = $objmail->name;
                                    sendMail($conf, $object, $langs, $user, $source, $clientSignataire, $entity, $db, $odt, $object_ref);

                                    // On remplace l'image de la signature dans la BDD par "document generated"

                                    if ($source == "agefodd_convention") {
                                        $db->begin();
                                        $db->query("UPDATE " . MAIN_DB_PREFIX . "mbi_signature_agefodd SET pathoffile = 'document generated' WHERE object_type = '" . $object_ref . "' AND convid = " . $object->id . " AND object_id = 1");
                                        $db->commit();
                                        $db->begin();
                                        $db->query("UPDATE " . MAIN_DB_PREFIX . "mbi_signature_agefodd SET pathoffile = 'document generated' WHERE object_type = '" . $object_ref . "' AND convid = " . $object->id . " AND object_id = 0");
                                        $db->commit();
                                    } else {
                                        $db->begin();
                                        $db->query("UPDATE " . MAIN_DB_PREFIX . "mbi_signature SET pathoffile = 'document generated' WHERE object_type = '" . $object_ref . "' AND object_id = 1");
                                        $db->commit();
                                        $db->begin();
                                        $db->query("UPDATE " . MAIN_DB_PREFIX . "mbi_signature SET pathoffile = 'document generated' WHERE object_type = '" . $object_ref . "' AND object_id = 0");
                                        $db->commit();
                                    }

                                    echo "<script>document.getElementById('loadingSignature').style.display = 'none';</script>";
                                    echo "<strong>" . $langs->trans('Merci') . "</strong>";

                                } else if (($conf->global->DOUBLE_SIGNATURE == "false" && $source !== "intervention" && $source !== "delivery" && $source !== "contract" && $source !== "holiday" && $source !== "expensereport" && $source !== "agefodd_convention") || ($source !== "order" && $source !== "ordersupplier" && $source !== "expedition" && $source !== "intervention" && $source !== "delivery" && $source !== "contract" && $source !== "holiday" && $source !== "expensereport" && $source !== "agefodd_convention" && $conf->global->DOUBLE_SIGNATURE == "true")) {

                                    // On génère une seule fois le pdf

                                    generateDocument($langs, $source, $object, $conf, "", $db, $odt, $object_ref);

                                    // On envoie le mail

                                    if ($source == "agefodd_convention") {
                                        $resqlmail = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_agefodd WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND convid = '" . $object->id . "' AND entity = '" . $entity . "'");
                                    } else {
                                        $resqlmail = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND entity = '" . $entity . "'");
                                    }
                                    $objmail = $db->fetch_object($resqlmail);
                                    $clientSignataire = $objmail->name;
                                    sendMail($conf, $object, $langs, $user, $source, $clientSignataire, $entity, $db, $odt, $object_ref);

                                    // On remplace l'image de la signature dans la BDD par "document generated"

                                    if ($source == "agefodd_convention") {
                                        $db->begin();
                                        $db->query("UPDATE " . MAIN_DB_PREFIX . "mbi_signature_agefodd SET pathoffile = 'document generated' WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND convid = " . $object->id);
                                        $db->commit();
                                    } else {
                                        $db->begin();
                                        $db->query("UPDATE " . MAIN_DB_PREFIX . "mbi_signature SET pathoffile = 'document generated' WHERE object_type = '" . $object_ref . "' AND object_id = 0");
                                        $db->commit();
                                    }

                                    echo "<script>document.getElementById('loadingSignature').style.display = 'none';</script>";
                                    echo "<strong>" . $langs->trans('Merci') . "</strong>";
                                } else {
                                    echo "<script>document.getElementById('loadingSignature').style.display = 'none';</script>";
                                    echo "<strong>" . $langs->trans('Merci') . "</strong>";
                                }
                            }
                        } // Si on soumet le formulaire mais qu'il manque quelque chose (normalement impossible)

                        else if (isset($_POST['image']) && !isset($_POST['agree']) || isset($_POST['image']) && $_POST['client'] === '' || isset($_POST['image']) && strlen($_POST['image']) < 3000) {
                            echo "<br><i class='fas fa-exclamation-triangle fa-2x' style='color: #8a141c;'></i><strong style='font-size: 20px;'> " . $langs->trans('Erreur') . " </strong>";
                        }
                    }
                }
            } else {
                dol_print_error_email('ERRORNEWONLINESIGN');
            }
        }
    }
}

// Si c'est la société qui signe

else if (!empty($company) && $company == 1) {

    $resqlhash = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_hash WHERE ref = '" . $object_ref . "' AND entity = '" . $entity . "'");
    if ($resqlhash) {
        $num = $db->num_rows($resqlhash);
        if ($num === 1) {
            $hash = $db->fetch_object($resqlhash);
            if ($hash->hash == GETPOST("hashp")) {

                // On vérifie si la signature pour ce devis existe déjà dans la BDD

                if ($source == "agefodd_convention") {
                    $resql = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_agefodd WHERE object_type = '" . $object_ref . "' AND object_id = 1 AND convid = '" . $object->id . "' AND entity = '" . $entity . "'");
                } else {
                    $resql = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature WHERE object_type = '" . $object_ref . "' AND object_id = 1 AND entity = '" . $entity . "'");
                }

                if ($resql) {
                    $num = $db->num_rows($resql);

                    if ($num === 1) { // Si y a déjà une signature pour ce devis dans la BDD
                        echo "<strong>" . $langs->trans("DejaSigné") . "</strong>";
                        if ($source !== "sepamandate" && $source !== "holiday") {
                            if ($conf->global->SIGNATURE_DOCUMENT_PREVIEW == "true" && !$odt) {
                                if ($source == "agefodd_convention") {
                                    unlink("temp/" . GETPOST("hashp") . "" . $_GET["nconv"] . ".pdf");
                                } else {
                                    unlink("temp/" . GETPOST("hashp") . ".pdf");
                                }
                                echo "<script>document.getElementById('tempDocPreview').style.display = 'none';</script>";
                            }
                        }
                    }

                    if ($num === 0) { // Si il n'y a pas de signature pour ce devis dans la BDD
                        echo "<style>input {font-size: 14px;} input:required {border-bottom: 1px solid #000;}</style>";
                        if ($source == "holiday" || $source == "expensereport") {
                            showForm($langs, $langs->trans("HierarchicalResponsibleSignButtonFullText"));
                        } else {
                            showForm($langs, $langs->trans("SignButton2FullText"));
                        }
                        echo "<script src='scripts/signature_pad.min.js'></script>";
                        echo "<script src='index.js'></script>";

                        if (isset($_POST['image']) && isset($_POST['agree']) && $_POST['client'] !== '' && strlen($_POST['image']) > 3000) { // Si on soumet le formulaire et que tout va bien
                            echo "<script>canvasAndForm.style.display = 'none';</script>";
                            echo "<img id='loadingSignature' src='" . DOL_URL_ROOT . "/custom/mbisignature/img/loader.gif'>";
                            ob_flush();
                            flush();

                            // On insert les données relatives à la signature dans la BDD

                            if ($source == "agefodd_convention") {
                                $db->begin();
                                $db->query("INSERT INTO " . MAIN_DB_PREFIX . "mbi_signature_agefodd (object_type, pathoffile, ip, name, object_id, entity, convid) VALUES ('" . $object_ref . "', '" . $_POST['image'] . "', '" . $_SERVER['REMOTE_ADDR'] . "','" . $_POST['client'] . "', 1, " . $entity . ", " . $object->id . ")");
                                $db->commit();
                            } else {
                                $db->begin();
                                $db->query("INSERT INTO " . MAIN_DB_PREFIX . "mbi_signature (object_type, pathoffile, ip, name, object_id, entity) VALUES ('" . $object_ref . "', '" . $_POST['image'] . "', '" . $_SERVER['REMOTE_ADDR'] . "','" . $_POST['client'] . "', 1, " . $entity . ")");
                                $db->commit();
                            }

                            if ($source == "agefodd_convention") {
                                $resql = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_agefodd WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND convid = '" . $object->id . "' AND entity = '" . $entity . "'");
                            } else {
                                $resql = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND entity = '" . $entity . "'");
                            }

                            if ($resql) {
                                $num = $db->num_rows($resql);

                                if ($num === 1) {

                                    // On génère une seule fois le pdf

                                    generateDocument($langs, $source, $object, $conf, "_double", $db, $odt, $object_ref);

                                    // On envoie le mail

                                    if ($source == "agefodd_convention") {
                                        $resqlmail = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_agefodd WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND convid = '" . $object->id . "' AND entity = '" . $entity . "'");
                                    } else {
                                        $resqlmail = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND entity = '" . $entity . "'");
                                    }
                                    $objmail = $db->fetch_object($resqlmail);
                                    $clientSignataire = $objmail->name;
                                    sendMail($conf, $object, $langs, $user, $source, $clientSignataire, $entity, $db, $odt, $object_ref);

                                    // On remplace l'image de la signature dans la BDD par "document generated"

                                    if ($source == "agefodd_convention") {
                                        $db->begin();
                                        $db->query("UPDATE " . MAIN_DB_PREFIX . "mbi_signature_agefodd SET pathoffile = 'document generated' WHERE object_type = '" . $object_ref . "' AND object_id = 1 AND convid = " . $object->id);
                                        $db->commit();
                                        $db->begin();
                                        $db->query("UPDATE " . MAIN_DB_PREFIX . "mbi_signature_agefodd SET pathoffile = 'document generated' WHERE object_type = '" . $object_ref . "' AND object_id = 0 AND convid = " . $object->id);
                                        $db->commit();
                                    } else {
                                        $db->begin();
                                        $db->query("UPDATE " . MAIN_DB_PREFIX . "mbi_signature SET pathoffile = 'document generated' WHERE object_type = '" . $object_ref . "' AND object_id = 1");
                                        $db->commit();
                                        $db->begin();
                                        $db->query("UPDATE " . MAIN_DB_PREFIX . "mbi_signature SET pathoffile = 'document generated' WHERE object_type = '" . $object_ref . "' AND object_id = 0");
                                        $db->commit();
                                    }

                                    echo "<script>document.getElementById('loadingSignature').style.display = 'none';</script>";
                                    echo "<strong>" . $langs->trans('Merci') . "</strong>";
                                } else {
                                    echo "<script>document.getElementById('loadingSignature').style.display = 'none';</script>";
                                    echo "<strong>" . $langs->trans('Merci') . "</strong>";
                                }
                            }

                        } // Si on soumet le formulaire mais qu'il manque quelque chose (normalement impossible)

                        else if (isset($_POST['image']) && !isset($_POST['agree']) || isset($_POST['image']) && $_POST['client'] === '' || isset($_POST['image']) && strlen($_POST['image']) < 3000) {
                            echo "<br><i class='fas fa-exclamation-triangle fa-2x' style='color: #8a141c;'></i><strong style='font-size: 20px;'> " . $langs->trans('Erreur') . " </strong>";
                        }
                    }
                }
            } else {
                dol_print_error_email('ERRORNEWONLINESIGN');
            }
        }
    }
}

///////////////////////////////////////////

function sendMail($conf, $object, $langs, $user, $source, $clientSignataire, $entity, $db, $odt, $object_ref) {

    if ($conf->global->SIGNATURE_CONFIRMATION_MAIL == $langs->trans('OPTION1') || $source == "sepamandate") { // Si dans la config on choisit d'envoyer le mail à la société
        $sendto = $conf->global->MAIN_INFO_SOCIETE_MAIL;
    }

    else if ($conf->global->SIGNATURE_CONFIRMATION_MAIL == $langs->trans('OPTION2')) { // Si dans la config on choisit d'envoyer le mail au commercial
        $salereparray = $object->thirdparty->getSalesRepresentatives($user);
        $sendto = $salereparray[0]['email'];
        if ($salereparray[0]['email'] == NULL) {
            $sendto = $conf->global->MAIN_INFO_SOCIETE_MAIL;
        }
    }

    else if ($conf->global->SIGNATURE_CONFIRMATION_MAIL == $langs->trans('OPTION3')) { // Si on envoie à tous les deux
        $salereparray = $object->thirdparty->getSalesRepresentatives($user);
        if ($salereparray[0]['email'] == NULL) {
            $sendto = $conf->global->MAIN_INFO_SOCIETE_MAIL;
        } else {
            $sendto = $conf->global->MAIN_INFO_SOCIETE_MAIL . "," . $salereparray[0]['email'];
        }
    }

    // Paramètrage du mail qu'on envoie

    if ($conf->global->SIGNATURE_TEMPLATE_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_SUBJECT)) {
        $subject = $conf->global->SIGNATURE_TEMPLATE_SUBJECT;
    } else {
        $subject = $langs->trans("Validé") . ' ' . $object_ref;
    }
    $template = $conf->global->SIGNATURE_TEMPLATE;
    if ($source == "proposal") {
        if ($conf->global->SIGNATURE_TEMPLATE_PROPAL !== "" && $conf->global->SIGNATURE_TEMPLATE_PROPAL !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_PROPAL)) {
            $template = $conf->global->SIGNATURE_TEMPLATE_PROPAL;
        }
        if ($conf->global->SIGNATURE_TEMPLATE_PROPAL_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_PROPAL_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_PROPAL_SUBJECT)) {
            $subject = $conf->global->SIGNATURE_TEMPLATE_PROPAL_SUBJECT;
        }
    }
    if ($source == "order") {
        if ($conf->global->SIGNATURE_TEMPLATE_ORDER !== "" && $conf->global->SIGNATURE_TEMPLATE_ORDER !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_ORDER)) {
            $template = $conf->global->SIGNATURE_TEMPLATE_ORDER;
        }
        if ($conf->global->SIGNATURE_TEMPLATE_ORDER_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_ORDER_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_ORDER_SUBJECT)) {
            $subject = $conf->global->SIGNATURE_TEMPLATE_ORDER_SUBJECT;
        }
    }
    if ($source == "ordersupplier") {
        if ($conf->global->SIGNATURE_TEMPLATE_SUPPLIER_ORDER !== "" && $conf->global->SIGNATURE_TEMPLATE_SUPPLIER_ORDER !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_SUPPLIER_ORDER)) {
            $template = $conf->global->SIGNATURE_TEMPLATE_SUPPLIER_ORDER;
        }
        if ($conf->global->SIGNATURE_TEMPLATE_SUPPLIER_ORDER_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_SUPPLIER_ORDER_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_SUPPLIER_ORDER_SUBJECT)) {
            $subject = $conf->global->SIGNATURE_TEMPLATE_SUPPLIER_ORDER_SUBJECT;
        }
    }
    if ($source == "expedition") {
        if ($conf->global->SIGNATURE_TEMPLATE_EXPEDITION !== "" && $conf->global->SIGNATURE_TEMPLATE_EXPEDITION !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_EXPEDITION)) {
            $template = $conf->global->SIGNATURE_TEMPLATE_EXPEDITION;
        }
        if ($conf->global->SIGNATURE_TEMPLATE_EXPEDITION_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_EXPEDITION_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_EXPEDITION_SUBJECT)) {
            $subject = $conf->global->SIGNATURE_TEMPLATE_EXPEDITION_SUBJECT;
        }
    }
    if ($source == "delivery") {
        if ($conf->global->SIGNATURE_TEMPLATE_DELIVERY !== "" && $conf->global->SIGNATURE_TEMPLATE_DELIVERY !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_DELIVERY)) {
            $template = $conf->global->SIGNATURE_TEMPLATE_DELIVERY;
        }
        if ($conf->global->SIGNATURE_TEMPLATE_DELIVERY_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_DELIVERY_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_DELIVERY_SUBJECT)) {
            $subject = $conf->global->SIGNATURE_TEMPLATE_DELIVERY_SUBJECT;
        }
    }
    if ($source == "intervention") {
        if ($conf->global->SIGNATURE_TEMPLATE_INTERVENTION !== "" && $conf->global->SIGNATURE_TEMPLATE_INTERVENTION !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_INTERVENTION)) {
            $template = $conf->global->SIGNATURE_TEMPLATE_INTERVENTION;
        }
        if ($conf->global->SIGNATURE_TEMPLATE_INTERVENTION_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_INTERVENTION_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_INTERVENTION_SUBJECT)) {
            $subject = $conf->global->SIGNATURE_TEMPLATE_INTERVENTION_SUBJECT;
        }
    }
    if ($source == "contract") {
        if ($conf->global->SIGNATURE_TEMPLATE_CONTRACT !== "" && $conf->global->SIGNATURE_TEMPLATE_CONTRACT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_CONTRACT)) {
            $template = $conf->global->SIGNATURE_TEMPLATE_CONTRACT;
        }
        if ($conf->global->SIGNATURE_TEMPLATE_CONTRACT_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_CONTRACT_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_CONTRACT_SUBJECT)) {
            $subject = $conf->global->SIGNATURE_TEMPLATE_CONTRACT_SUBJECT;
        }
    }
    if ($source == "sepamandate") {
        if ($conf->global->SIGNATURE_TEMPLATE_SEPA_MANDATE !== "" && $conf->global->SIGNATURE_TEMPLATE_SEPA_MANDATE !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_SEPA_MANDATE)) {
            $template = $conf->global->SIGNATURE_TEMPLATE_SEPA_MANDATE;
        }
        if ($conf->global->SIGNATURE_TEMPLATE_SEPA_MANDATE_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_SEPA_MANDATE_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_SEPA_MANDATE_SUBJECT)) {
            $subject = $conf->global->SIGNATURE_TEMPLATE_SEPA_MANDATE_SUBJECT;
        }
    }
    if ($source == "holiday") {
        if ($conf->global->SIGNATURE_TEMPLATE_HOLIDAY !== "" && $conf->global->SIGNATURE_TEMPLATE_HOLIDAY !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_HOLIDAY)) {
            $template = $conf->global->SIGNATURE_TEMPLATE_HOLIDAY;
        }
        if ($conf->global->SIGNATURE_TEMPLATE_HOLIDAY_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_HOLIDAY_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_HOLIDAY_SUBJECT)) {
            $subject = $conf->global->SIGNATURE_TEMPLATE_HOLIDAY_SUBJECT;
        }
    }
    if ($source == "expensereport") {
        if ($conf->global->SIGNATURE_TEMPLATE_EXPENSE_REPORT !== "" && $conf->global->SIGNATURE_TEMPLATE_EXPENSE_REPORT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_EXPENSE_REPORT)) {
            $template = $conf->global->SIGNATURE_TEMPLATE_EXPENSE_REPORT;
        }
        if ($conf->global->SIGNATURE_TEMPLATE_EXPENSE_REPORT_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_EXPENSE_REPORT_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_EXPENSE_REPORT_SUBJECT)) {
            $subject = $conf->global->SIGNATURE_TEMPLATE_EXPENSE_REPORT_SUBJECT;
        }
    }
    if ($source == "agefodd_convention") {
        if ($conf->global->SIGNATURE_TEMPLATE_AGEFODD !== "" && $conf->global->SIGNATURE_TEMPLATE_AGEFODD !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_AGEFODD)) {
            $template = $conf->global->SIGNATURE_TEMPLATE_AGEFODD;
        }
        if ($conf->global->SIGNATURE_TEMPLATE_AGEFODD_SUBJECT !== "" && $conf->global->SIGNATURE_TEMPLATE_AGEFODD_SUBJECT !== NULL && !empty($conf->global->SIGNATURE_TEMPLATE_AGEFODD_SUBJECT)) {
            $subject = $conf->global->SIGNATURE_TEMPLATE_AGEFODD_SUBJECT;
        }
    }

    if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) {
        if ($source == "sepamandate") {
            $companybankaccount = new CompanyBankAccount($db);
            $companybankaccount->fetch('', $object->id);
            $message = str_replace(array("{CLIENT}", "{CUSTOMER}", "{REF}", "\r"), array($clientSignataire, $clientSignataire, $langs->transnoentitiesnoconv("SepaMandateShort") . ' ' . $companybankaccount->ref . "-" . dol_sanitizeFileName($companybankaccount->rum), "<br>"), $template);
            $subject = str_replace(array("{CLIENT}", "{CUSTOMER}", "{REF}", "\r"), array($clientSignataire, $clientSignataire, $langs->transnoentitiesnoconv("SepaMandateShort") . ' ' . $companybankaccount->ref . "-" . dol_sanitizeFileName($companybankaccount->rum), "<br>"), $subject);
        } else {
            $message = str_replace(array("{CLIENT}", "{CUSTOMER}", "{REF}", "\r"), array($clientSignataire, $clientSignataire, $object_ref, "<br>"), $template);
            $subject = str_replace(array("{CLIENT}", "{CUSTOMER}", "{REF}", "\r"), array($clientSignataire, $clientSignataire, $object_ref, "<br>"), $subject);
        }
    } else {
        if ($source == "sepamandate") {
            $companybankaccount = new CompanyBankAccount($db);
            $companybankaccount->fetch('', $object->id);
            $message = str_replace(array("{CLIENT}", "{CUSTOMER}", "{REF}"), array($clientSignataire, $clientSignataire, $langs->transnoentitiesnoconv("SepaMandateShort") . ' ' . $companybankaccount->ref . "-" . dol_sanitizeFileName($companybankaccount->rum)), $template);
            $subject = str_replace(array("{CLIENT}", "{CUSTOMER}", "{REF}"), array($clientSignataire, $clientSignataire, $langs->transnoentitiesnoconv("SepaMandateShort") . ' ' . $companybankaccount->ref . "-" . dol_sanitizeFileName($companybankaccount->rum)), $subject);
        } else {
            $message = str_replace(array("{CLIENT}", "{CUSTOMER}", "{REF}"), array($clientSignataire, $clientSignataire, $object_ref), $template);
            $subject = str_replace(array("{CLIENT}", "{CUSTOMER}", "{REF}"), array($clientSignataire, $clientSignataire, $object_ref), $subject);
        }
    }
    $from = $conf->global->MAIN_INFO_SOCIETE_MAIL; // Envoyé par la société

    // Envoi du mail

	if ($entity == 1) {
		if ($source == 'proposal') {
			$attached = $conf->global->SIGNATURE_DOC_PATH . '/propale/' . $object->ref . '/' . $object->ref . '_signature.pdf';
		} else if ($source == 'order') {
			$attached = $conf->global->SIGNATURE_DOC_PATH . '/commande/' . $object->ref . '/' . $object->ref . '_signature.pdf';
		} else if ($source == 'ordersupplier') {
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/fournisseur/commande/' . $object->ref . '/' . $object->ref . '_signature.pdf';
        }  else if ($source == 'expedition') {
			$attached = $conf->global->SIGNATURE_DOC_PATH . '/expedition/sending/' . $object->ref . '/' . $object->ref . '_signature.pdf';
        }  else if ($source == 'delivery') {
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/expedition/receipt/' . $object->ref . '/' . $object->ref . '_signature.pdf';
		} else if ($source == 'intervention') {
			$attached = $conf->global->SIGNATURE_DOC_PATH . '/ficheinter/' . $object->ref . '/' . $object->ref . '_signature.pdf';
		} else if ($source == 'contract') {
			$attached = $conf->global->SIGNATURE_DOC_PATH . '/contract/' . $object->ref . '/' . $object->ref . '_signature.pdf';
		} else if ($source == 'sepamandate') {
            $companybankaccount = new CompanyBankAccount($db);
            $companybankaccount->fetch('', $object->id);
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/societe/' . $object->id . '/' . $langs->transnoentitiesnoconv("SepaMandateShort") . ' ' . $companybankaccount->ref . "-" . dol_sanitizeFileName($companybankaccount->rum) . '_signature.pdf';
        } else if ($source == 'holiday') {
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/holiday/' . $object->ref . '/' . $object->ref . '_signature.pdf';
        } else if ($source == 'expensereport') {
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/expensereport/' . $object->ref . '/' . $object->ref . '_signature.pdf';
        } else if ($source == "agefodd_convention") {
            $resqlagf=$db->query("SELECT * FROM " . MAIN_DB_PREFIX . "agefodd_convention WHERE rowid = " . $object->id);
            if ($resqlagf) {
                $numagf = $db->num_rows($resqlagf);
                if ($numagf) {
                    $objagf = $db->fetch_object($resqlagf);
                    if ($objagf) {
                        $convfksoc = $objagf->fk_societe;
                        $file = 'convention' . '_' . $objagf->fk_agefodd_session . '_' . $objagf->fk_societe . '_' . $objagf->rowid . '_signature.pdf';
                    }
                }
            }
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/societe/' . $convfksoc . '/' . $file;
        }
	} else {
		if ($source == 'proposal') {
			$attached = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/propale/' . $object->ref . '/' . $object->ref . '_signature.pdf';
		} else if ($source == 'order') {
			$attached = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/commande/' . $object->ref . '/' . $object->ref . '_signature.pdf';
		} else if ($source == 'ordersupplier') {
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/fournisseur/commande/' . $object->ref . '/' . $object->ref . '_signature.pdf';
        }  else if ($source == 'expedition') {
			$attached = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/expedition/sending/' . $object->ref . '/' . $object->ref . '_signature.pdf';
        }  else if ($source == 'delivery') {
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/expedition/receipt/' . $object->ref . '/' . $object->ref . '_signature.pdf';
		} else if ($source == 'intervention') {
			$attached = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/ficheinter/' . $object->ref . '/' . $object->ref . '_signature.pdf';
		} else if ($source == 'contract') {
			$attached = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/contract/' . $object->ref . '/' . $object->ref . '_signature.pdf';
		} else if ($source == 'sepamandate') {
            $companybankaccount = new CompanyBankAccount($db);
            $companybankaccount->fetch('', $object->id);
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/societe/' . $object->id . '/' . $langs->transnoentitiesnoconv("SepaMandateShort") . ' ' . $companybankaccount->ref . "-" . dol_sanitizeFileName($companybankaccount->rum) . '_signature.pdf';
        } else if ($source == 'holiday') {
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/holiday/' . $object->ref . '/' . $object->ref . '_signature.pdf';
        } else if ($source == 'expensereport') {
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/expensereport/' . $object->ref . '/' . $object->ref . '_signature.pdf';
        } else if ($source == "agefodd_convention") {
            $resqlagf=$db->query("SELECT * FROM " . MAIN_DB_PREFIX . "agefodd_convention WHERE rowid = " . $object->id);
            if ($resqlagf) {
                $numagf = $db->num_rows($resqlagf);
                if ($numagf) {
                    $objagf = $db->fetch_object($resqlagf);
                    if ($objagf) {
                        $file = 'convention' . '_' . $objagf->fk_agefodd_session . '_' . $objagf->fk_societe . '_' . $objagf->rowid . '_signature.pdf';
                    }
                }
            }
            $attached = $conf->global->SIGNATURE_DOC_PATH . '/' . $entity . '/societe/' . $object->socid . '/' . $file;
        }
	}
    $outputlangs = $langs;
    if ($source == "agefodd_convention") {
        $agsession = new Agsession($db);
        $agsession->fetch(GETPOST("ref", 'alpha'));
        $substit= getCommonSubstitutionArray($outputlangs, 0, NULL, $agsession);
        complete_substitutions_array($substit, $outputlangs, $agsession, array());
    } else {
        $substit = getCommonSubstitutionArray($outputlangs, 0, NULL, $object);
        complete_substitutions_array($substit, $outputlangs, $object, array());
    }
    $message = make_substitutions($message, $substit);
    $subject = make_substitutions($subject, $substit);
	if ($source == 'sepamandate') {
        $mail = new CMailFile($subject, $sendto, $from, $message, array($attached), array('application/pdf'), array($langs->transnoentitiesnoconv("SepaMandateShort") . ' ' . $companybankaccount->ref . "-" . dol_sanitizeFileName($companybankaccount->rum) . '.pdf'), $object->thirdparty->email, "", 0, 1); // Copie au client
    } else if ($source == 'holiday') {
        $holiday_validator = new User($db);
        $holiday_validator->fetch($object->fk_validator);
        $holiday_user = new User($db);
        $holiday_user->fetch($object->fk_user);
        if ($conf->global->SIGNATURE_SEND_HOLIDAY_TO !== "" && $conf->global->SIGNATURE_SEND_HOLIDAY_TO !== NULL && !empty($conf->global->SIGNATURE_SEND_HOLIDAY_TO)) {
            $cc = $holiday_user->email . "," . $conf->global->SIGNATURE_SEND_HOLIDAY_TO;
        } else {
            $cc = $holiday_user->email;
        }
        $mail = new CMailFile($subject, $holiday_validator->email, $from, $message, array($attached), array('application/pdf'), array($object->ref . '.pdf'), $cc, "", 0, 1); // Copie au client
    } else if ($source == 'expensereport') {
        $expensereport_validator = new User($db);
        $expensereport_validator->fetch($object->fk_user_validator);
        $expensereport_user = new User($db);
        $expensereport_user->fetch($object->fk_user_author);
        if ($conf->global->SIGNATURE_SEND_EXPENSE_REPORT_TO !== "" && $conf->global->SIGNATURE_SEND_EXPENSE_REPORT_TO !== NULL && !empty($conf->global->SIGNATURE_SEND_EXPENSE_REPORT_TO)) {
            $cc = $expensereport_user->email . "," . $conf->global->SIGNATURE_SEND_EXPENSE_REPORT_TO;
        } else {
            $cc = $expensereport_user->email;
        }
        $mail = new CMailFile($subject, $expensereport_validator->email, $from, $message, array($attached), array('application/pdf'), array($object->ref . '.pdf'), $cc, "", 0, 1); // Copie au client
    } else {
        if ($source == "agefodd_convention") {
            $sendtoagf = new Societe($db);
            $sendtoagf->fetch($convfksoc);
            $cc = $sendtoagf->email;
            dol_syslog("Send to thirdparty - " . $cc);
        } else {
            $contactlist = $object->liste_contact(-1, "external");
            if (empty($contactlist[0]["email"]) || $contactlist[0]["email"] == "" || $contactlist[0]["email"] == NULL) {
                $cc = $object->thirdparty->email;
                dol_syslog("Send to thirdparty - " . $cc);
            } else {
                $cc = $contactlist[0]["email"];
                dol_syslog("Send to contact - " . $cc);
            }
        }
        if ($odt) {
            $mail = new CMailFile($subject, $conf->global->MAIN_INFO_SOCIETE_MAIL, $from, $message, array(''), array(''), array(''), $cc, "", 0, 1);
        } else {
            $mail = new CMailFile($subject, $sendto, $from, $message, array($attached), array('application/pdf'), array($object_ref . '.pdf'), $cc, "", 0, 1); // Copie au client
        }
    }
    $result = $mail->error;

    if (!$result) {
        $result = $mail->sendfile();
        if ($result) {
            dol_syslog('Email has been correctly sent');
        } else {
            dol_syslog('Error sending email');
        }
    } else {
        dol_syslog('Error in creating email');
    }
    if ($odt) {
        unlink("temp/signature.png");
    }
    return $result;
}

function generateDocument($outputlangs, $source, $object, $conf, $double, $db, $odt, $object_ref) {

    $hidedetails = !empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0;
    $hidedesc = !empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0;
    $hideref = !empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0;

    if ($conf->global->MAIN_MODULE_SUBTOTAL == "1" && $source == 'proposal') {
        echo "<div style='display: none !important;'>";
        global $hookmanager;
        $hookmanager->initHooks(array('propalcard'));
        $parameters = array('object' => $object, 'outputlangs' => $outputlangs);
        $action = 'builddoc';
        $_GET["hideInnerLines"] = isset($_SESSION['subtotal_hideInnerLines_propal'][$object->id]) ? $_SESSION['subtotal_hideInnerLines_propal'][$object->id] : 0;
        $_GET["hidedetails"] = isset($_SESSION['subtotal_hidedetails_propal'][$object->id]) ? $_SESSION['subtotal_hidedetails_propal'][$object->id] : 0;
        $hidedetails = $_GET["hidedetails"];
        $hidepricesDefaultConf = !empty($conf->global->SUBTOTAL_HIDE_PRICE_DEFAULT_CHECKED) ? $conf->global->SUBTOTAL_HIDE_PRICE_DEFAULT_CHECKED : 0;
        $_GET["hideprices"] = isset($_SESSION['subtotal_hideprices_propal'][$object->id]) ? $_SESSION['subtotal_hideprices_propal'][$object->id] : $hidepricesDefaultConf;
        $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action);
        echo "</div>";
    }

    if ($conf->global->MAIN_MODULE_ULTIMATEPDF == "1") {
        if ($object->modelpdf == "ultimate_propal") {
            $staticpdf = glob($conf->ultimatepdf->dir_output . "/proposals/*.pdf");
        } else if ($object->modelpdf == "ultimate_order") {
            $staticpdf = glob($conf->ultimatepdf->dir_output . "/orders/*.pdf");
        } else if ($object->modelpdf == "ultimate_supplierorder") {
            $staticpdf = glob($conf->ultimatepdf->dir_output . "/supplier_orders/*.pdf");
        } else if ($object->modelpdf == "ultimate_contract") {
            $staticpdf = glob($conf->ultimatepdf->dir_output . "/contracts/*.pdf");
        }
        if (!empty($staticpdf)) {
            foreach ($staticpdf as $filename) {
                $morefiles[] = basename($filename, ".pdf");
                $morefiles[] .= ''; //To have an empty line in second position
            }
        }
        if (!empty($morefiles)) {
            $_GET["ultimatepdffile"] = $morefiles[0];
        }
    }

    if (!empty($conf->global->MAIN_MULTILANGS)) {
        $outputlangs = new Translate("", $conf);
        $newlang = $object->thirdparty->default_lang;
        $outputlangs->setDefaultLang($newlang);
    }
    if ($source == 'proposal') {
        if ($conf->global->MAIN_MODULE_ULTIMATEPDF == "1" && $object->modelpdf == "ultimate_propal") {
            $modelpdf = "ultimate_propal";
        } else if ($object->modelpdf == "rubis" && $conf->global->MAIN_MODULE_RUBIS) {
            $modelpdf = "rubis_sign";
        } else if ($object->model_pdf == "cyan") {
            $modelpdf = "cyan_sign";
        } else {
            $modelpdf = "azur_sign";
        }
        if ($odt) {
            $modelpdf = $object->model_pdf;
        }
        $object->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
    } else if ($source == 'order') {
        if ($conf->global->MAIN_MODULE_ULTIMATEPDF == "1" && $object->modelpdf == "ultimate_order") {
            $modelpdf = "ultimate_order";
        } else if ($object->modelpdf == "edison" && $conf->global->MAIN_MODULE_RUBIS) {
            $modelpdf = "edison_sign";
        } else if ($object->model_pdf == "eratosthene") {
            $modelpdf = "eratosthene_sign";
        } else {
            $modelpdf = "einstein_sign";
        }
        $object->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
    } else if ($source == 'ordersupplier') {
        if ($conf->global->MAIN_MODULE_ULTIMATEPDF == "1" && $object->modelpdf == "ultimate_supplierorder") {
            $modelpdf = "ultimate_supplierorder";
        } else if ($object->model_pdf == "cornas") {
            $modelpdf = "cornas_sign";
        } else {
            $modelpdf = "muscadet_sign";
        }
        $object->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
    } else if ($source == 'expedition') {
        if ($conf->global->MAIN_MODULE_ULTIMATEPDF == "1" && $object->modelpdf == "ultimate_shipment") {
            $modelpdf = "ultimate_shipment";
        } else if ($object->modelpdf == "epinoche" && $conf->global->MAIN_MODULE_RUBIS) {
            $modelpdf = "epinoche_sign";
        } else {
            $modelpdf = "rouget_sign";
        }
        $object->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
    } else if ($source == 'delivery') {
        if ($conf->global->MAIN_MODULE_ULTIMATEPDF == "1" && $object->modelpdf == "ultimate_delivery") {
            $modelpdf = "ultimate_delivery";
        } else {
            $modelpdf = "Typhon_sign";
        }
        $object->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
    } else if ($source == 'intervention') {
        if ($conf->global->MAIN_MODULE_ULTIMATEPDF == "1" && $object->modelpdf == "ultimate_inter") {
            $modelpdf = "ultimate_inter";
        } else {
            $modelpdf = "soleil_sign";
        }
        $object->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
    } else if ($source == 'contract') {
        if ($conf->global->MAIN_MODULE_ULTIMATEPDF == "1" && $object->modelpdf == "ultimate_contract") {
            $modelpdf = "ultimate_contract";
        } else if ($conf->global->MAIN_MODULE_RUBIS) {
            $modelpdf = "alto_sign";
        } else {
            $modelpdf = "strato_sign";
        }
        $object->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
    }  else if ($source == 'holiday') {
        try {
            if (!file_exists(DOL_DOCUMENT_ROOT.'/custom/mbisignature/newonlinesign.php'))
                throw new Exception ('Does not exist');
            else
                $path = "/custom/mbisignature";
        }
        catch(Exception $e) {
            $path = "/mbisignature";
        }
        require_once DOL_DOCUMENT_ROOT. $path . '/class/holidaysign.class.php';
        $holidayGen = new HolidaySign($db);
        $holidayGen->fetch($object->id);
        $holidayGen->generateDocument('holiday_sign', $outputlangs, $hidedetails, $hidedesc, $hideref);
        require_once DOL_DOCUMENT_ROOT. $path . '/class/approve.php';
        global $langs;
        approve_holiday($object->id, $db, $langs);
    } else if ($source == 'expensereport') {
        dol_include_once("/mbisignature/class/approve.php");
        global $langs;
        approve_expensereport($object->id, $db, $langs, $hidedetails, $hidedesc, $hideref);
        $object->generateDocument('standard_sign', $outputlangs, $hidedetails, $hidedesc, $hideref);
    } else if ($source == 'sepamandate') {
        require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
        $societe = new Societe($db);
        $societe->fetch($object->id);
        $companybankaccount = new CompanyBankAccount($db);
        $companybankaccount->fetch('', $object->id);
        $moreparams = array(
            'use_companybankid'=>$companybankaccount->id,
            'force_dir_output'=>$conf->societe->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->id),
            'societe_id'=>$object->id
        );
        $societe->generateDocument('sepamandate_sign', $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
    } else if ($source == "agefodd_convention") {
        $resqlagf=$db->query("SELECT * FROM " . MAIN_DB_PREFIX . "agefodd_convention WHERE rowid = " . $object->id);
        if ($resqlagf) {
            $numagf = $db->num_rows($resqlagf);
            if ($numagf) {
                $objagf = $db->fetch_object($resqlagf);
                if ($objagf) {
                    $convid = $objagf->rowid;
                    $convfksoc = $objagf->fk_societe;
                    $file = 'convention' . '_' . $objagf->fk_agefodd_session . '_' . $objagf->fk_societe . '_' . $convid . '_signature.pdf';
                }
            }
        }

        $societe = new Societe($db);
        $societe->fetch($convfksoc);
        $moreparams = array(
            'file' => $file,
            'agf' => $object->id,
            'socid' => $convfksoc,
            'convid' => $convid
        );
        $societe->generateDocument('convention_sign', $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
    }
    if ($source !== "sepamandate" && $source !== "holiday") {
        if ($conf->global->SIGNATURE_DOCUMENT_PREVIEW == "true" && !$odt) {
            if ($source == "agefodd_convention") {
                unlink("temp/" . GETPOST("hashp") . "" . $_GET["nconv"] . ".pdf");
            } else {
                unlink("temp/" . GETPOST("hashp") . ".pdf");
            }
            echo "<script>document.getElementById('tempDocPreview').style.display = 'none';</script>";
        }
    }
}

function showForm($langs, $signataire) {
    global $conf;
    echo "<div id='canvasAndForm'>";
    echo "<script>function extendCanvas(){
	var canvas = document.getElementById('canvas');
	var line = document.getElementById('lineOnCanvas');
	var ribbon = document.getElementById('ribbon');
	if (canvas.width === 340) {
	    canvas.width = 600;
		canvas.height = 300;
		try {
            line.style.width = '600px';
            line.style.bottom = '100px';
            ribbon.style.top = '180px';
            ribbon.style.right = '290px';
		} catch {
		    console.log('Ribbon and line not displayed');
		}
	} else if (canvas.width === 600) {
	    canvas.width = 340;
		canvas.height = 170;
		try {
		line.style.width = '340px';
		line.style.bottom = '60px';
		ribbon.style.top = '90px';
		ribbon.style.right = '160px';
		} catch {
		    console.log('Ribbon and line not displayed');
		}
	}
	}</script>";
    if (!empty($conf->global->SIGNATURE_CUSTOM_RIBBON_COLOR) && $conf->global->SIGNATURE_CUSTOM_RIBBON_COLOR !== "" && $conf->global->SIGNATURE_CUSTOM_RIBBON_COLOR !== NULL) {
        $ribbon_color = "#" . $conf->global->SIGNATURE_CUSTOM_RIBBON_COLOR;
    } else {
        $ribbon_color = "#ff0000";
    }
    if (!empty($conf->global->SIGNATURE_CUSTOM_LINE_COLOR) && $conf->global->SIGNATURE_CUSTOM_LINE_COLOR !== "" && $conf->global->SIGNATURE_CUSTOM_LINE_COLOR !== NULL) {
        $line_color = "#" . $conf->global->SIGNATURE_CUSTOM_LINE_COLOR;
    } else {
        $line_color = "dodgerblue";
    }
    if (!empty($conf->global->SIGNATURE_CUSTOM_CHECKBOX_COLOR) && $conf->global->SIGNATURE_CUSTOM_CHECKBOX_COLOR !== "" && $conf->global->SIGNATURE_CUSTOM_CHECKBOX_COLOR !== NULL) {
        $checkbox_color = "#" . $conf->global->SIGNATURE_CUSTOM_CHECKBOX_COLOR;
    } else {
        $checkbox_color = "#26a69a";
    }
    if (!empty($conf->global->SIGNATURE_CUSTOM_BUTTON_COLOR) && $conf->global->SIGNATURE_CUSTOM_BUTTON_COLOR !== "" && $conf->global->SIGNATURE_CUSTOM_BUTTON_COLOR !== NULL) {
        $button_color = "background-color: #" . $conf->global->SIGNATURE_CUSTOM_BUTTON_COLOR;
    } else {
        $button_color = "";
    }
    echo "<span id='signTitle' style='position: relative; top: 16px;'>" . $signataire . " :</span>";
    echo "<style>@keyframes bounce {from {transform: translateY(0);} to {transform: translateY(-20px);}} #ribbon {animation: bounce 0.5s ease 4 alternate; pointer-events: none; position: relative; top: 90px; right: 160px; margin: 0 auto;width: 32px; height: 60px; background: " . $ribbon_color . ";} #ribbon:after {content: ''; position: absolute; top: 60px; left: 0; border-left: 16px solid transparent; border-right: 16px solid transparent; border-top: 16px solid " . $ribbon_color . "; border-bottom: 16px solid transparent;}</style>";
    if ($conf->global->SIGNATURE_DISPLAY_LINE_AND_RIBBON == "true") {
        echo "<div id='ribbon'><i class='fas fa-pencil-alt fa-lg' style='color: white; position: relative; top: 20px;'></i></div>";
    } else {
        echo "<br><br>";
    }
    echo "<canvas id='canvas' width='340' height='170' style='background-color: #f0f0f0;'></canvas>";
    if ($conf->global->SIGNATURE_DISPLAY_LINE_AND_RIBBON == "true") {
        echo "<div id='lineOnCanvas' style='width: 340px; margin: auto; border-bottom: 1px solid " . $line_color . "; height: 0; position: relative; bottom: 60px;'></div>";
    }
    echo "<br>";
    echo "<form method='post' action='' onsubmit='postData();'>";
    echo "<input id='inp_img' name='image' type='hidden' value=''>";
    echo "<input style='appearance: none; -moz-appearance: none; -webkit-appearance: none;' type='text' name='client' id='client' value='' placeholder='" . $langs->trans("NomPrenom") . "' required>";
    echo "<style>[type=\"checkbox\"].filled-in:checked + span:not(.lever):after {background-color: " . $checkbox_color . "; border: 2px solid " . $checkbox_color . ";}</style>";
    echo "<label for='agree' id='agreeLabel' class='badge badge-status' style='background-color:#f0f0f0; color: black !important;'><input style='appearance: none; -moz-appearance: none; -webkit-appearance: none;' type='checkbox' class='filled-in' id='agree' name='agree' required><span style='font-size: 14px;'> " . $langs->trans("Accord") . "</span></label>";
    echo "<br><br>";
	echo "<input class='butAction' style='background-color: #bdbdbd; appearance: none; -moz-appearance: none; -webkit-appearance: none;' onclick='extendCanvas()' value='" . $langs->trans("ExtendCanvas") . "' type='button'>";
    echo "<input id='clear' value='" . $langs->trans("Effacer") . "' class='butAction' type='button' style='background-color: #bdbdbd; appearance: none; -moz-appearance: none; -webkit-appearance: none;'>";
    echo "<input id='save' name='submitSignature' type='submit' class='butAction' style='margin-left: 8px; appearance: none; -moz-appearance: none; -webkit-appearance: none; " . $button_color . "' value='" . $langs->trans("Valider") . "'>";
    echo "</form>";
    echo "</div>";
}

print '</div>';

dol_include_once("/mbisignature/class/signature_page.class.php");
$signaturePage = new SignaturePage();
$signaturePage->showSocialLinks();

htmlPrintOnlinePaymentFooter($mysoc, $langs);
llxFooter('', 'public');

$db->close();
