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

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

/**
 *  Class of triggers for MyModule module
 */
class InterfaceDeleteSignature 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_DELETE" || $action == "FICHINTER_DELETE" || $action == "ORDER_DELETE" || $action == "CONTRACT_DELETE" || $action == "SHIPPING_DELETE") {
            dol_syslog("Trigger for action '$action' launched. id=".$object->id);
            $db->begin();
            $db->query("DELETE FROM " . MAIN_DB_PREFIX . "mbi_signature WHERE object_type = '" . $object->ref . "' AND entity = " . $conf->entity);
            $db->commit();
            $db->begin();
            $db->query("DELETE FROM " . MAIN_DB_PREFIX . "mbi_signature_hash WHERE ref = '" . $object->ref . "' AND entity = " . $conf->entity);
            $db->commit();
        }
		return 0;
	}
}
