<?php
/*
 * @version $Id: HEADER 15930 2011-10-30 15:47:55Z tsmr $
 -------------------------------------------------------------------------
 Manageentities plugin for GLPI
 Copyright (C) 2003-2011 by the Manageentities Development Team.

 https://forge.indepnet.net/projects/manageentities
 -------------------------------------------------------------------------

 LICENSE
		
 This file is part of Manageentities.

 Manageentities 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.

 Manageentities 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 Manageentities. If not, see <http://www.gnu.org/licenses/>.
 --------------------------------------------------------------------------
 */

if (!defined('GLPI_ROOT')) {
	die("Sorry. You can't access directly to this file");
}

class PluginManageentitiesContractDay extends CommonDBTM {
   
   function getFromDBbyTypeAndContract($plugin_manageentities_critypes_id,$contracts_id,$entities_id) {
		global $DB;
		
		$query = "SELECT *
		FROM `".$this->getTable()."`
		WHERE `plugin_manageentities_critypes_id` = '" . $plugin_manageentities_critypes_id . "'
		AND `contracts_id` = '" . $contracts_id . "'
		AND `entities_id` = '".$entities_id."' ";
		if ($result = $DB->query($query)) {
			if ($DB->numrows($result) != 1) {
				return false;
			}
			$this->fields = $DB->fetch_assoc($result);
			if (is_array($this->fields) && count($this->fields)) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
	
	function addNbDay($values) {

      if ($this->getFromDBbyTypeAndContract($values["plugin_manageentities_critypes_id"],$values["contracts_id"],$values["entities_id"])) {

         $this->update(array(
           'id'=>$this->fields['id'],
           'nbday'=>$values["nbday"],
           'entities_id'=>$values["entities_id"]));
      } else {

         $this->add(array(
           'plugin_manageentities_critypes_id'=>$values["plugin_manageentities_critypes_id"],
           'contracts_id'=>$values["contracts_id"],
           'nbday'=>$values["nbday"],
           'entities_id'=>$values["entities_id"]));
      }
   }

	static function showform($target,$contracts_id) {
		global $DB,$LANG,$CFG_GLPI;

		$contract = new contract;
		$contract->getFromDB($contracts_id);
		$entities_id=$contract->fields["entities_id"];
		$used=array();
		$number=0;
		$query = "SELECT `glpi_plugin_manageentities_contractdays`.*
				FROM `glpi_plugin_manageentities_contractdays`
				WHERE `glpi_plugin_manageentities_contractdays`.`entities_id` = '".$entities_id."' 
				AND `glpi_plugin_manageentities_contractdays`.`contracts_id` = '".$contracts_id."'";
      
      $restant = 0;
		if ($result = $DB->query($query)) {
			$number = $DB->numrows($result);
			if ($number != 0) {
            $rand=mt_rand();
				echo "<form method='post' name='massiveaction_form_nbdaycri$rand' id='massiveaction_form_nbdaycri$rand' action=\"$target\">";
				echo "<div align='center'>";
				echo "<table class='tab_cadre_fixe' cellpadding='5'>";
				echo "<tr>";
				echo "<th></th>";
				echo "<th>".$LANG['plugin_manageentities'][14]."</th>";
				echo "<th>".$LANG['plugin_manageentities'][16]."</th>";
				echo "<th>".$LANG['plugin_manageentities'][18]."</th>";
				echo "<th>".$LANG['plugin_manageentities'][20]."</th>";
				echo "<th>".$LANG['plugin_manageentities'][19]."</th>";
				echo "</tr>";
            
            
				while($ligne= mysql_fetch_array($result)) {

					$ID=$ligne["id"];
					$critype = $ligne["plugin_manageentities_critypes_id"];
					$used[]= $critype;

					$totalcri=0;
					$totalallcri=0;
					$totalrealtime=0;
					$forfait=0;
					$pricecri=0;
					$query_cri = "SELECT `plugin_manageentities_critypes_id`, `realtime` "
					." FROM `glpi_plugin_manageentities_cridetails` "
					." WHERE `contracts_id` = '".$contracts_id."' AND `entities_id` = '".$entities_id."' ";
					$query_cri;
					$result_cri = $DB->query($query_cri);

					if ($result_cri = $DB->query($query_cri)) {
						$number_cri = $DB->numrows($result_cri);
						if ($number_cri != 0) {
							while($ligne_cri= mysql_fetch_array($result_cri)) {
								$obj=new PluginManageentitiesCriPrice();
								if ($obj->getFromDBbyType($critype,$entities_id))
									$pricecri=$obj->fields["price"];
								$totalcri=$pricecri*$ligne_cri["realtime"];
								$totalrealtime+=$ligne_cri["realtime"];
								$totalallcri+=$totalcri;
							}
						}
					}

					echo "<tr class='tab_bg_1'>";
               
               echo "<td>";
					echo "<input type='hidden' name='id' value='$ID'>";
					echo "<input type='checkbox' name='item_nbday[$ID]' value='1'>";
					echo "</td>";
					
					//interventon type
					$type=new PluginManageentitiesCriType();
					$type->getFromDB($critype);
					echo "<td>".$type->getLink()."</td>";
					
					//Nb jours total
					echo "<td>".Html::formatnumber($ligne["nbday"],true)." ".$LANG['plugin_manageentities'][17]."</td>";

					//forfait total
					echo "<td>";
					$PluginManageentitiesCriPrice=new PluginManageentitiesCriPrice();
					if ($PluginManageentitiesCriPrice->getFromDBbyType($critype,$entities_id)) {
						$forfait=$ligne["nbday"]*$PluginManageentitiesCriPrice->fields["price"];
						echo Html::formatnumber($forfait,true);
					}
					echo "</td>";
					//nb jours restants
					echo "<td>";

					$nbdayrestant=$ligne["nbday"]-$totalrealtime;
					echo Html::formatnumber($nbdayrestant,true)." ".$LANG['plugin_manageentities'][17];

					echo "</td>";
					//forfait restant
					echo "<td>";
					$restant=$forfait-$totalallcri;
					echo Html::formatnumber($restant,true);
					echo "</td>";
					
				}

				Html::openArrowMassives("massiveaction_form_nbdaycri$rand", true);
            Html::closeArrowMassives(array('delete_nbday' => $LANG['buttons'][6]));
            
				echo "</table>";
				echo "</div>";
				echo "</form>";
				
				PluginManageentitiesCriPrice::showform($critype);
			}
		

			$querydisplay = "SELECT `glpi_plugin_manageentities_cridetails`.*, 
                                 `glpi_plugin_manageentities_critypes`.`name` AS name_plugin_manageentities_critypes_id,
                                  `glpi_documents`.`id` AS documents_id, `glpi_documents`.`is_deleted`
				FROM `glpi_plugin_manageentities_cridetails`
				LEFT JOIN `glpi_plugin_manageentities_critypes` 
               ON (`glpi_plugin_manageentities_critypes`.`id` = `glpi_plugin_manageentities_cridetails`.`plugin_manageentities_critypes_id`)
				LEFT JOIN `glpi_documents` 
               ON (`glpi_plugin_manageentities_cridetails`.`documents_id` = `glpi_documents`.`id`)
				WHERE `glpi_plugin_manageentities_cridetails`.`entities_id` ='".$entities_id."' 
            AND `glpi_plugin_manageentities_cridetails`.`contracts_id` = '".$contracts_id."'
				ORDER BY `glpi_documents`.`date_mod` ";

			if ($resultdisplay = $DB->query($querydisplay)) {
				$numberdisplay = $DB->numrows($resultdisplay);
				
					echo "<div align='center'>";
					echo "<table class='tab_cadre_fixe' cellpadding='5'>";
					echo "<tr>";
					echo "<th>".$LANG['common'][27]."</th>";
					echo "<th>".$LANG['plugin_manageentities'][14]."</th>";
					echo "<th>".$LANG["document"][2]."</th>";
					echo "<th>".$LANG['plugin_manageentities']['cri'][18]."</th>";
					echo "<th>".$LANG['plugin_manageentities']['infoscompreport'][4]."</th>";
					echo "<th>".$LANG['plugin_manageentities'][21]."</th>";
					echo "<th>".$LANG['plugin_manageentities'][22]."</th>";
					echo "</tr>";
            if ($numberdisplay != 0) {
					$totalannuel=0;
					while($display= mysql_fetch_array($resultdisplay)) {
						echo "<tr class='tab_bg_1".($display["is_deleted"]=='1'?"_2":"")."'>";
						echo "<td>".Html::convdate($display['date'])."</td>";
						echo "<td>".$display['name_plugin_manageentities_critypes_id']."</td>";
						$doc = new Document();
						$doc->getFromDB($display["documents_id"]);
						echo "<td class='center'  width='100px'>".$doc->getDownloadLink()."</td>";
						echo "<td>".Html::formatnumber($display['realtime'],true)."</td>";
						echo "<td>".$display['technicians']."</td>";
						
						$criprice=0;
						$PluginManageentitiesCriPrice=new PluginManageentitiesCriPrice();
						if ($PluginManageentitiesCriPrice->getFromDBbyType($display["plugin_manageentities_critypes_id"],$entities_id)) {
							$criprice=$PluginManageentitiesCriPrice->fields["price"];
						}
						if ($criprice) {
                     echo "<td>";
                     echo Html::formatnumber($criprice,true);
                     echo "</td>";
                     echo "<td>".Html::formatnumber($criprice*$display['realtime'],true)."</td>";
						} else {
                     echo "<td colspan='2'>";
                     echo "</td>";
						}
						echo "</tr>";
						
						$totalannuel+=$criprice*$display['realtime'];
					}
					echo "<tr class='tab_bg_2'>";
					if ($criprice) {
                  echo "<td colspan='6' class='right'><b>".$LANG['plugin_manageentities'][23]." : </b></td>";
                  echo "<td><b>".Html::formatnumber($totalannuel,true)."</b></td>";
                  $nbtheoricaldays=$restant/$criprice;
                  echo "<tr class='tab_bg_2'>";
                  echo "<td colspan='6' align='right'><b>".$LANG['plugin_manageentities'][24]." : </b></td>";
                  echo "<td><b>".Html::formatnumber($nbtheoricaldays,true)."</b></td>";
                  echo "</tr>";
               }
				}
				
				echo "</table>";
            echo "</div>";
			}

			if ($number < 1) {
					echo "<form method='post'  action=\"$target\">";
					echo "<table class='tab_cadre' cellpadding='5'>";
					echo "<tr><th colspan='3'>".$LANG['plugin_manageentities']['setup'][5]."</th></tr>";
					echo "<tr class='tab_bg_1'><td>";
					$q="SELECT COUNT(*)
						FROM `glpi_plugin_manageentities_critypes` ";
					$result = $DB->query($q);
					$nb = $DB->result($result,0,0);
					if ($nb>count($used))
                  Dropdown::show('PluginManageentitiesCriType', array('name' => 'plugin_manageentities_critypes_id','entity' => $entities_id,'used' => $used));
					echo "</td><td>";
					echo "&nbsp;x&nbsp;<input type='text' name='nbday' size='16'>&nbsp;".$LANG['plugin_manageentities'][17];
					echo "<input type='hidden' name=\"entities_id\" value='".$entities_id."'>";
					echo "<input type='hidden' name=\"contracts_id\" value='".$contracts_id."'>";
					echo "<td>";
					echo "<div align='center'><input type='submit' name='add_nbday' value=\"".$LANG['buttons'][2]."\" class='submit' ></div></td></tr>";
					echo "</table>";
					echo "</form>";
			}
		}
	}
	
	function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
      global $LANG;

      if ($item->getType()=='Contract') {
            return $LANG['plugin_manageentities']['title'][3];
      }
      return '';
   }


   static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
      global $CFG_GLPI;

      if (get_class($item)=='Contract') {
         self::showform($CFG_GLPI['root_doc']."/plugins/manageentities/front/contract.form.php",$item->getField('id'));
      }
      return true;
   }
}

?>