<?php
/* Copyright (C) 2013  altairis <contact@altairis.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 <http://www.gnu.org/licenses/>.
 */

/**
 *  \file       htdocs/core/triggers/interface_90_all_CustomRef.class.php
 *  \ingroup    prices
 *  \brief      Fichier de définition des triggers du module CustomRef
 *  \remarks    Triggers pris en charge :
 *              - PRODUCT_DELETE : suppression des prix du produit supprimé
 */


/**
 *  Class of triggers for CustomRef module
 */
class InterfaceCustomRef
{
    var $db;

    /**
     *   Constructor
     *
     *   @param		DoliDB		$db      Database handler
     */
    function __construct($db)
    {
        $this->db = $db;

        $this->name = preg_replace('/^Interface/i','',get_class($this));
        $this->family = "Dolitools";
        $this->description = "Dolitools triggers.";
        $this->version = 'dolibarr';            // 'development', 'experimental', 'dolibarr' or version
        $this->picto = 'altairis@dolitools';
    }


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

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

    /**
     *   Return version of trigger file
     *
     *   @return     string      Version of trigger file
     */
    function getVersion()
    {
        global $langs;
        $langs->load("admin");

        if ($this->version == 'development') return $langs->trans("Development");
        elseif ($this->version == 'experimental') return $langs->trans("Experimental");
        elseif ($this->version == 'dolibarr') return DOL_VERSION;
        elseif ($this->version) return $this->version;
        else return $langs->trans("Unknown");
    }

    /**
     *      Function called when a Dolibarrr business event is done.
     *      All functions "run_trigger" are triggered if file is inside directory htdocs/core/triggers
     *
     *      @param	string		$action		Event action code
     *      @param  Object		$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
     */
	function run_trigger($action,$object,$user,$langs,$conf)
	{
		if (empty($conf->global->DOLITOOLS_USE_CUSTOMREF)) return;

		if ( $action == 'PROPAL_CREATE' || $action == 'ORDER_CREATE' || $action == 'BILL_CREATE' || $action == 'SHIPPING_CREATE' || $action == 'SHIPPING_VALIDATE')
        {
            dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id);
            return $this->update_ref($action,$object,$user,$langs,$conf);
        }
		return 0;
    }

    function update_ref($trigger,$object,$user,$langs,$conf)
    {
		$sep = $conf->global->CUSTOMREF_SEPARATOR?$conf->global->CUSTOMREF_SEPARATOR:'';
		$lensep = mb_strlen($sep);

		$action = GETPOST('action');
		$confirm=GETPOST('confirm','alpha');

		$element = $object->element;
		if ($element == 'propal') $element = 'propale';

		$glovar = "CUSTOMREF_".strtoupper($element)."_NOPROV";
		$noprov = !empty($conf->global->$glovar);

		$glovar = "CUSTOMREF_".strtoupper($element)."_SUFFIX_ON_CLONE";
		$suffixonclone = !empty($conf->global->$glovar);

		$glovar = "CUSTOMREF_".strtoupper($element)."_KEEP_SUFFIX_ON_WORKFLOW";
		$keep_suffix = !empty($conf->global->$glovar);

		if ($action == 'add' && $noprov)
		{
			$ref = GETPOST('ref');
		}
		elseif ($action == 'confirm_clone' && $confirm == 'yes' && $suffixonclone)
		{
			$ref =  GETPOST('refstart');
			$refsuffix = GETPOST('clone_ref') ;
			if (!empty($refsuffix))
			{
				if (substr($refsuffix,0,$lensep) != $sep)
					$ref .= $sep.$refsuffix;
				else
					$ref .= $refsuffix;
			}
		}
		elseif((!empty($object->origin) && $keep_suffix) || ($action == 'confirm_clone' && $confirm == 'yes'))
		{
			include_once __DIR__ . '/../../lib/customref.lib.php';
			if ($keep_suffix) $refsuffix = getSuffixFromOriginRef($object->origin, $object->origin_id);
			if ($noprov) $ref = $object->getNextNumRef($soc);
			else $ref = $object->newref?$object->newref:$object->ref;
			if (!empty($refsuffix))
			{
				if (substr($refsuffix,0,$lensep) != $sep)
					$ref .= $sep.$refsuffix;
				else
					$ref .= $refsuffix;
			}
		}

		if (!empty($ref))
		{
			$object->ref = dol_string_nospecial(trim($ref));
			$reffield = 'ref';
			switch($trigger)
			{
				case 'PROPAL_CREATE':
					$table = 'propal';
					break;
				case 'ORDER_CREATE':
					$table = 'commande';
					break;
				case 'SHIPPING_CREATE':
				case 'SHIPPING_VALIDATE':
					$table = 'expedition';
					break;
				case 'BILL_CREATE':
					$table = 'facture';
					// commented by christophe battarel$reffield = 'facnumber';
					break;
			}
			$sql = 'UPDATE '.MAIN_DB_PREFIX.$table." SET ".$reffield."='".$object->ref."' WHERE rowid=".$object->id;
			dol_syslog(get_class($this)."::create sql=".$sql);

			$resql=$this->db->query($sql);
			if (! $resql)
			{
				$this->errors[] = $langs->trans("UpdateRefFailed");
				return -1;
			}
		}

		return 1;

	}

}
?>
