<?php
/* Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>
 *
 * 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 2 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * $Id$
 */

/**
   \file       htdocs/includes/triggers/interface_modCommande_Ecotax.class.php
   \ingroup    core
   \brief      Ajout Ecotax sur produit d'un certaine categorie
*/


/**
   \class      InterfaceEcotax
   \brief      Classe des fonctions triggers des actions personalisées du workflow
*/

class InterfaceEcotax
{
  var $db;
  var $error;
  
  /**
   *   \brief      Constructeur.
   *   \param      DB      Handler d'accès base
   */
  function InterfaceEcotax($DB)
  {
    $this->db = $DB ;
    
    $this->name = eregi_replace('Interface','',get_class($this));
    $this->family = "facture";
    $this->description = "Les triggers de ce composant calculent le ecotax du produit si le produit est membre d'une categorie speciale (par default: 'Ecotax', change le valeur du variable \$ecotax dans le trigger pour accomoder votre choix).";
    $this->revision = explode(' ','$Revision$');
    $this->version = $this->revision[1];
  }
  
  /**
   *   \brief      Renvoi nom du lot de triggers
   *   \return     string      Nom du lot de triggers
   */
  function getName()
  {
    return $this->name;
  }
  
  /**
   *   \brief      Renvoi descriptif du lot de triggers
   *   \return     string      Descriptif du lot de triggers
   */
  function getDesc()
  {
    return $this->description;
  }
  /**
   *   \brief      Renvoi version du lot de triggers
   *   \return     string      Version du lot de triggers
   */
  function getVersion()
  {
    global $langs;
    $langs->load("admin");
    
    if ($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");
  }
  
  /**
   *      \brief      Fonction appelée lors du déclenchement d'un évènement Dolibarr.
   *                  D'autres fonctions run_trigger peuvent etre présentes dans includes/triggers
   *      \param      action      Code de l'evenement
   *      \param      object      Objet concern
   *      \param      user        Objet user
   *      \param      lang        Objet lang
   *      \param      conf        Objet conf
   *      \return     int         <0 si ko, 0 si aucune action faite, >0 si ok
   */
  function run_trigger($action,$object,$user,$langs,$conf)
  {
    if ($action == 'LINEORDER_INSERT')
      {
	return $this->_add_replace_ecotax($action,$object,$user,$langs,$conf);
      }
    if ($action == 'LINEORDER_DELETE')
      {
	return $this->_add_replace_ecotax($action,$object,$user,$langs,$conf);
      }
    // Renvoi 0 car aucune action de faite
    return 0;
  }


  function _add_replace_ecotax($action,$object,$user,$langs,$conf)
  {
    // The next 3 parameter can be replaced at will:
    $desc = "Ecotax"; // the description on the invoice (recupel in Belgium)
    $txtva = 21;      // the default tax percentage
    $ecocat = "Ecotax"; // the category products must be in for ecotax to apply

    // Ajoute une ligne de ecotax automatiquement
    // 
	dolibarr_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->fk_commande);


	/*
	 * Calcul le ecotax, dependant du prix
	 *
	 */
	$sql = "SELECT fd.price, fd.qty, fd.fk_product";
	$sql.= " FROM ".MAIN_DB_PREFIX."commandedet as fd";
	$sql.= " WHERE fd.fk_commande = '".$object->fk_commande."'";
	$sql.= " AND fd.special_code = '0'";

	$resql = $this->db->query($sql) ;
	
	$eco = 0;
	if ($resql)
	  {
	    while ( $row = $this->db->fetch_row($resql) )
	      {
		$price=$row[0];
		$qty=$row[1];
		$prod_id=$row[2];
		if ($this->_is_in_cat($ecocat,$prod_id)) {
		   if ($price<=100) {
		      $eco+=5*$qty;
		   } elseif ($price>100 && $price<=300) {
		      $eco+=10*$qty;
		   } else {
		      $eco+=15*$qty;
		   }
		}
	      }
	  }
	else
	  {
	    dolibarr_syslog("Trigger '".$this->name."' in action '$action' [2] SQL ERROR ");
	  }
	/*
	 *
	 *
	 */

	/*
	 * Détecte si la ligne existe
	 *
	 */
	$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commandedet ";
	$sql.= " WHERE fk_commande = '".$object->fk_commande."'";
	$sql.= " AND special_code = 2;";
	
	$resql = $this->db->query($sql) ;
	
	if ($resql)
	  {
	    $exists = $this->db->num_rows($resql);
	    $this->db->free($resql);
	  }
	else
	  {
	    dolibarr_syslog("Trigger '".$this->name."' in action '$action' [3] SQL ERROR $sql");
	  }
	/*
	 * Nombre de ligne de commande
	 *
	 */
	$sql = "SELECT MAX(rang) FROM ".MAIN_DB_PREFIX."commandedet";
	$sql.= " WHERE fk_commande=".$object->fk_commande.";";
	
	$resql = $this->db->query($sql) ;
	$num_lignes=0;
	if ($resql)
	  {
	    while ( $row = $this->db->fetch_row($resql) )
	      {
		$num_lignes = $row[0];	    
	      }	    
	  }
	else
	  {
	    dolibarr_syslog("Trigger '".$this->name."' in action '$action' [4] SQL ERROR ");
	  }

	/*
	 * Calcul les ecotax
	 */
	$rang = $num_lignes + 1;

	// Tout a 0 tant que l'on ne sait pas calculer
	$total_ht = $eco;
	$total_tva = $eco*$txtva/100;
	$total_ttc = $total_ht+$total_ttc;

	if ($exists > 0)
	  {
	    // Mets à jour la ligne
	    $sql = "UPDATE  ".MAIN_DB_PREFIX."commandedet";
	    $sql.= " SET description ='".addslashes($desc)."'";
	    $sql.= ", rang='".$rang."'";
	    $sql.= " WHERE fk_commande=".$object->fk_commande;
	    $sql.= " AND special_code=2;";
	    
	    $resql = $this->db->query($sql) ;
	    
	    if ($resql)
	      {
		return 2;
	      }
	    else
	      {
		dolibarr_syslog("Trigger '".$this->name."' in action '$action' [5] SQL ERROR $sql");
	      }
	  }
	else
	  {
	    // Insertion dans base de la ligne
	    // See class CommandeLigne
	    // we don't use the class CommandeLigne for insert, because
	    // then the trigger would be called again ... and again ... and ...
	    $sql = "INSERT INTO ".MAIN_DB_PREFIX."commandedet";
	    $sql.= " (fk_commande, description, qty, tva_tx,";
	    $sql.= " fk_product, remise_percent, subprice, price, remise, fk_remise_except,";
	    $sql.= " marge_tx, marque_tx, rang, info_bits, total_ht, total_tva, total_ttc, special_code)";
	    $sql.= " VALUES (".$object->fk_commande.",";
	    $sql.= " '".addslashes($desc)."',";
	    $sql.= " '1',";
	    $sql.= " '".price2num($txtva)."',";
	    $sql.= 'null,'; 
	    $sql.= " '0',";
	    $sql.= " '".price2num($total_ht)."',";
	    $sql.= " '".price2num($total_ht)."',";
	    $sql.= " 0,0,0,0,";
	    $sql.= ' '.$rang.',0,';
	    $sql.= " '".price2num($total_ht)."',";
	    $sql.= " '".price2num($total_tva)."',";
	    $sql.= " '".price2num($total_ttc)."'";
	    $sql.= ",2);";
	    
	    $resql = $this->db->query($sql) ;
	    
	    if ($resql)
	      {
		return 1;
	      }
	    else
	      {
		dolibarr_syslog("Trigger '".$this->name."' in action '$action' [5] SQL ERROR $sql");
	      }
	  }
  }

  function _is_in_cat($ecocat,$product_id) {
	/*
	 * See if the product is in the ecotax category
	 * Stop and return 0 if the product is not in it
	 */
	require_once(DOL_DOCUMENT_ROOT."/categories/categorie.class.php");
	if (!isset($product_id) || empty($product_id)) {
	   return 0;
	}
	$c = new Categorie($this->db);
	$cats = array();
        $cats = $c->containing($product_id);
	$found=0;
	if (count($cats)==0) {
	   return 0;
	}
	foreach ($cats as $cat) {
	   if ($cat->label===$ecocat) {
		$found=1;
	   }
	}
	if ($found==0) {
	   return 0;
	}
	return 1;
   }
}
?>
