<?php
/* Copyright (C) 2022       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/>.
 */

require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php';

/**
 *  Class of triggers for MyModule module
 */
class InterfaceGenerateLink extends DolibarrTriggers
{
	/**
	 * @var DoliDB Database handler
	 */
	protected $db;

	/**
	 * Constructor
	 *
	 * @param DoliDB $db Database handler
	 */
	public function __construct($db)
	{
		$this->db = $db;
		$this->name = preg_replace('/^Interface/i', '', get_class($this));
		$this->family = "demo";
		$this->description = "MBI Signature triggers";
		$this->version = 'development';
		$this->picto = 'logo@mbisignature';
	}

	/**
	 * Trigger name
	 *
	 * @return string Name of trigger file
	 */
	public function getName()
	{
		return $this->name;
	}

	/**
	 * Trigger description
	 *
	 * @return string Description of trigger file
	 */
	public function getDesc()
	{
		return $this->description;
	}

	/**
	 * Function called when a Dolibarrr business event is done.
	 * All functions "runTrigger" are triggered if file
	 * is inside directory core/triggers
	 *
	 * @param string 		$action 	Event action code
	 * @param CommonObject 	$object 	Object
	 * @param User 			$user 		Object user
	 * @param Translate 	$langs 		Object langs
	 * @param Conf 			$conf 		Object conf
	 * @return int              		<0 if KO, 0 if no triggered ran, >0 if OK
	 */
	public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf)
	{
		if (empty($conf->mbisignature->enabled)) return 0;

		global $db;
        if ($action == "PROPAL_VALIDATE" && $conf->global->SIGNATURE_ENABLE_PROPAL == "true") {
            dol_syslog("Trigger for action '$action' launched. id=".$object->id);

            dol_include_once('/mbisignature/lib/signatureToText.lib.php');
            $resqlhash = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_hash WHERE ref = '" . $object->newref . "' AND entity = '" . $conf->entity . "'");
            if ($resqlhash) {
                $num = $db->num_rows($resqlhash);
                if ($num === 0) {
                    $extrafields = $object->array_options;
                    $extrafields['signature_link'] = strval(showOnlineSignatureUrlText('proposal', $object->newref));
                    $object->array_options = $extrafields;
                    $result = $object->insertExtraFields();
                    if ($result < 0) {
                        setEventMessages("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN PROPAL " . $object->newref, null, 'errors');
                        dol_syslog("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN PROPAL " . $object->newref, LOG_ERR);
                    }
                } else {
                    dol_syslog("REF ALREADY EXISTS IN " . MAIN_DB_PREFIX . "mbi_signature_hash IN PROPAL " . $object->newref, LOG_INFO);
                }
            }
        }
        if ($action == "ORDER_VALIDATE" && $conf->global->SIGNATURE_ENABLE_ORDER == "true") {
            dol_syslog("Trigger for action '$action' launched. id=".$object->id);

            dol_include_once('/mbisignature/lib/signatureToText.lib.php');
            $resqlhash = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_hash WHERE ref = '" . $object->newref . "' AND entity = '" . $conf->entity . "'");
            if ($resqlhash) {
                $num = $db->num_rows($resqlhash);
                if ($num === 0) {
                    $extrafields = $object->array_options;
                    $extrafields['signature_link'] = strval(showOnlineSignatureUrlText('order', $object->newref));
                    $object->array_options = $extrafields;
                    $result = $object->insertExtraFields();
                    if ($result < 0) {
                        setEventMessages("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN ORDER " . $object->newref, null, 'errors');
                        dol_syslog("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN ORDER " . $object->newref, LOG_ERR);
                    }
                } else {
                    dol_syslog("REF ALREADY EXISTS IN " . MAIN_DB_PREFIX . "mbi_signature_hash IN ORDER " . $object->newref, LOG_INFO);
                }
            }
        }
        if ($action == "ORDER_SUPPLIER_VALIDATE" && $conf->global->SIGNATURE_ENABLE_ORDER_SUPPLIER == "true") {
            dol_syslog("Trigger for action '$action' launched. id=".$object->id);

            dol_include_once('/mbisignature/lib/signatureToText.lib.php');
            $resqlhash = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_hash WHERE ref = '" . $object->newref . "' AND entity = '" . $conf->entity . "'");
            if ($resqlhash) {
                $num = $db->num_rows($resqlhash);
                if ($num === 0) {
                    $extrafields = $object->array_options;
                    $extrafields['signature_link'] = strval(showOnlineSignatureUrlText('ordersupplier', $object->newref));
                    $object->array_options = $extrafields;
                    $result = $object->insertExtraFields();
                    if ($result < 0) {
                        setEventMessages("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN ORDER " . $object->newref, null, 'errors');
                        dol_syslog("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN ORDER " . $object->newref, LOG_ERR);
                    }
                } else {
                    dol_syslog("REF ALREADY EXISTS IN " . MAIN_DB_PREFIX . "mbi_signature_hash IN ORDER " . $object->newref, LOG_INFO);
                }
            }
        }
        if ($action == "SHIPPING_VALIDATE" && $conf->global->SIGNATURE_ENABLE_EXPEDITION == "true") {
            dol_syslog("Trigger for action '$action' launched. id=".$object->id);

            dol_include_once('/mbisignature/lib/signatureToText.lib.php');
            $resqlhash = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_hash WHERE ref = '" . $object->newref . "' AND entity = '" . $conf->entity . "'");
            if ($resqlhash) {
                $num = $db->num_rows($resqlhash);
                if ($num === 0) {
                    $extrafields = $object->array_options;
                    $extrafields['signature_link'] = strval(showOnlineSignatureUrlText('expedition', $object->newref));
                    $object->array_options = $extrafields;
                    $result = $object->insertExtraFields();
                    if ($result < 0) {
                        setEventMessages("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN SHIPMENT " . $object->newref, null, 'errors');
                        dol_syslog("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN SHIPMENT " . $object->newref, LOG_ERR);
                    }
                } else {
                    dol_syslog("REF ALREADY EXISTS IN " . MAIN_DB_PREFIX . "mbi_signature_hash IN SHIPMENT " . $object->newref, LOG_INFO);
                }
            }
        }
        if ($action == "FICHINTER_VALIDATE" && $conf->global->SIGNATURE_ENABLE_INTERVENTION == "true") {
            dol_syslog("Trigger for action '$action' launched. id=".$object->id);

            dol_include_once('/mbisignature/lib/signatureToText.lib.php');
            $resqlhash = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_hash WHERE ref = '" . $object->newref . "' AND entity = '" . $conf->entity . "'");
            if ($resqlhash) {
                $num = $db->num_rows($resqlhash);
                if ($num === 0) {
                    $extrafields = $object->array_options;
                    $extrafields['signature_link'] = strval(showOnlineSignatureUrlText('intervention', $object->newref));
                    $object->array_options = $extrafields;
                    $result = $object->insertExtraFields();
                    if ($result < 0) {
                        setEventMessages("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN INTERVENTION " . $object->newref, null, 'errors');
                        dol_syslog("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN INTERVENTION " . $object->newref, LOG_ERR);
                    }
                } else {
                    dol_syslog("REF ALREADY EXISTS IN " . MAIN_DB_PREFIX . "mbi_signature_hash IN INTERVENTION " . $object->newref, LOG_INFO);
                }
            }
        }
        if (($action == "CONTRACT_VALIDATE" || $action == "CONTRACT_SERVICE_ACTIVATE") && $conf->global->SIGNATURE_ENABLE_CONTRACT == "true") {
            dol_syslog("Trigger for action '$action' launched. id=".$object->id);

            dol_include_once('/mbisignature/lib/signatureToText.lib.php');
            $resqlhash = $db->query("SELECT * from " . MAIN_DB_PREFIX . "mbi_signature_hash WHERE ref = '" . $object->newref . "' AND entity = '" . $conf->entity . "'");
            if ($resqlhash) {
                $num = $db->num_rows($resqlhash);
                if ($num === 0) {
                    $extrafields = $object->array_options;
                    $extrafields['signature_link'] = strval(showOnlineSignatureUrlText('contract', $object->newref));
                    $object->array_options = $extrafields;
                    $result = $object->insertExtraFields();
                    if ($result < 0) {
                        setEventMessages("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN CONTRACT " . $object->newref, null, 'errors');
                        dol_syslog("ERROR WHILE INSERTING EXTRAFIELD SIGNATURE_LINK IN CONTRACT " . $object->newref, LOG_ERR);
                    } else {
                        echo "<script>window.location.reload();</script>";
                    }
                } else {
                    dol_syslog("REF ALREADY EXISTS IN " . MAIN_DB_PREFIX . "mbi_signature_hash IN CONTRACT " . $object->newref, LOG_INFO);
                }
            }
        }
		return 0;
	}
}
