<?php
  /**************************************************************************\
  * phpGroupWare API - Homebrewing Class Structures                          *
  * This file written by Miles Lott <milosch@phpgroupware.org>               *
  * Copyright (C) 2001 Miles Lott                                            *
  * -------------------------------------------------------------------------*
  * This library is part of the phpGroupWare API                             *
  * http://www.phpgroupware.org/api                                          * 
  * ------------------------------------------------------------------------ *
  * This library is free software; you can redistribute it and/or modify it  *
  * under the terms of the GNU Lesser General Public License as published by *
  * the Free Software Foundation; either version 2.1 of the License,         *
  * or any later version.                                                    *
  * This library 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 Lesser General Public License for more details.              *
  * You should have received a copy of the GNU Lesser General Public License *
  * along with this library; if not, write to the Free Software Foundation,  *
  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA            *
  \**************************************************************************/

  /* $Id: class.brew.inc.php,v 1.5 2001/09/11 12:38:28 milosch Exp $ */

	define('MAX_NUM_MALTS', 8);
	define('MAX_NUM_YEASTS', 8);
	define('MAX_NUM_HOPS', 6);

	include(PHPGW_APP_INC . SEP . 'class.recipe.inc.php');

	class brew extends recipe
	{
		var $db = '';
		var $table = 'phpgw_brewer_batches';
		var $grants = '';
		var $style = '';
		var $malt = '';
		var $yeast = '';
		var $hop = '';
		var $recipe = '';
		var $debug = False;

		var $id = 0;

		var $batch = array();
		var $data = array(
			'id'          => 0,
			'recipe_id'   => 0,
			'style'       => 0,
			'description' => '',
			'ingredients' => '',
			'startdate'   => '',
			'enddate'     => ''
		);

		var $malt_tbl = array(
			'phpgw_brewer_malts',array(
				'id'          => 0,
				'name'        => '',
				'description' => '',
				'gravity'     => 0,
				'avg_color'   => 0,
				'starch_conv' => 0,
				'description' => ''
			)
		);

		var $yeast_tbl = array(
			'phpgw_brewer_yeasts',array(
				'id'          => 0,
				'name'        => '',
				'description' => '',
				'avgatten'    => 0,
				'flocrate'    => 0
			)
		);

		var $hop_tbl = array(
			'phpgw_brewer_hops',array(
				'id'        => 0,
				'name'      => 0,
				'description' => '',
				'avg_alpha' => 0,
				'avg_iols'  => 0
			)
		);

		var $style_tbl = array(
			'phpgw_brewer_styles',array(
				'id'          => 0,
				'name'        => '',
				'stock'       => 0,
				'description' => '',
				'ingredients' => '',
				'mingravity'  => 0,
				'maxgravity'  => 0,
				'minalcohol'  => 0,
				'maxalcohol'  => 0,
				'minbitter'   => 0,
				'maxbitter'   => 0,
				'mincolor'    => 0,
				'maxcolor'    => 0
			)
		);

		var $unit = array(
			'name' => '',				//char name[8];
			'conversion_factor' => 0	//float conversion_factor;
		);

		var $total = 0;

		// Constructor
		function brew($new='')
		{
			$this->db = $GLOBALS['phpgw']->db;

			if($new == 'recipe')
			{
				$this->_debug('<br>Creating recipe object.');
				$this->recipe = new recipe;
			}
			elseif (!$new)
			{
				$this->_debug('<br>Creating style object.');
				$this->style  = CreateObject('brewer.std',$this->style_tbl);
				$this->_debug('<br>Creating malt object.');
				$this->malt   = CreateObject('brewer.std',$this->malt_tbl);
				$this->_debug('<br>Creating yeast object.');
				$this->yeast  = CreateObject('brewer.std',$this->yeast_tbl);
				$this->_debug('<br>Creating hop object.');
				$this->hop    = CreateObject('brewer.std',$this->hop_tbl);
				$this->_debug('<br>Creating recipe object.');
				$this->recipe = new recipe;
			}
			else
			{
				$tbl = $new . '_tbl';
				$this->_debug('<br>Creating ' . $new . ' object.');
				$this->$new = CreateObject('brewer.std',$this->$tbl);
			}
/*
			if($useacl)
			{
				$this->grants = $GLOBALS['phpgw']->acl->get_grants('brewer');
			}
			$this->account_id = $GLOBALS['phpgw_info']['user']['account_id'];
*/
		}

		function get($id=0)
		{
			$fields = $this->fields;
			if (!$id)
			{
				$id = $this->id;
			}

			$sql = "SELECT " . $fields . " FROM " . $this->table . " WHERE id=" . $id;
			$this->db->query($sql,__LINE__,__FILE__);
			$this->db->next_record();
			
			reset($fields);
			while(list($a,$b) = each($fields))
			{
				$this->beer[$this->db->f('id')][$b] = $this->db->f($b);
			}
			return $this->beer;
		}

		function set($id=0)
		{
			$fields = $this->fields;

			if($id)
			{
				$sql = "UPDATE " . $this->table . " SET ";
				while(list($a,$b) = each($this->batch))
				{
					$sql .= $field[$b] . "='" . $b . "',";
				}
				$sql = substr(0,-1,$sql) . " WHERE id=" . $id;
			}
			else
			{
				$values = "'" . explode("','",$this->batch) . "'";
				$sql = "INSERT INTO " . $this->table . "(" . $fields . ") VALUES (" . $values . ")";
			}
			$ret = $this->db->query($sql,__LINE__,__FILE__);
			return $ret;
		}

		function get_list($start,$query='',$sort='ASC',$order='')
		{
			$fields = $this->fields();
			$fieldstr = implode(',',$fields);

			if($query)
			{
				$querystr = $this->makequery($query);
			}
			if($sort && $order)
			{
				$sort = ' ORDER BY ' . $order . ' ' . $sort;
			}
			else
			{
				$sort = '';
			}

			$sql = "SELECT " . $fieldstr . " FROM " . $this->table . $querystr;
			$this->db->query($sql,__LINE__,__FILE__);
			$this->total = $this->db->num_rows();

			$sql = "SELECT " . $fieldstr . " FROM " . $this->table . $querystr . ' ' . $this->db->limit($start) . $sort;
			$this->db->query($sql,__LINE__,__FILE__);

			while ($this->db->next_record())
			{
				@reset($fields);
				while(list($a,$b) = @each($fields))
				{
					$batch[$this->db->f('id')][$b] = ereg_replace('_',' ',$this->db->f($b));
				}
			}
			return $batch;
		}

		function fields()
		{
			@reset($this->data);
			while (list($key,$val) = each($this->data))
			{
				$fields[] = $key;
			}
			return $fields;
		}

		function makequery($query='')
		{
			if (!$query)
			{
				return;
			}

			$s = " WHERE (";

			$fields = $this->fields();
			while (list($key,$val) = each($fields))
			{
				if ($val != 'id')
				{
					$s .= $val . " LIKE '%$query%' OR ";
				}
			}
			$s = substr($s,0,-4);
			$s .= ")";

			return $s;
		}

		function add_ingredient($obj,$type,$id)
		{
			global $DEBUG;

			$types = $type . 's';
			$tmp = $this->${$type->get($id)};
			$tmp = $tmp[$id];

			if($DEBUG) { echo "Adding: \$this->recipe->" . $types . "[] using: " . $tmp['id']; }
			$obj->recipe[$types][] = $tmp['id'];
			$this->save_sessiondata($obj->recipe);
		}

		function remove_ingredient($obj,$type,$id)
		{
			global $DEBUG;

			$types = $type . 's';
			if($DEBUG) { echo "Removing: \$this->recipe->" . $types . "[" . $id. "]"; }
			unset($obj[$types][$id]);
			$this->save_sessiondata($obj);
		}

		function save_sessiondata($data='')
		{
			if (gettype($data) == 'array')
			{
				$GLOBALS['phpgw']->session->appsession('session_data','brewer',$data);
			}
		}

		function read_sessiondata()
		{
			return $GLOBALS['phpgw']->session->appsession('session_data','brewer');
		}

		function _debug($err,$var='')
		{
			if(!$err)
			{
				return;
			}
			if($this->debug)
			{
				echo $err . '&nbsp;';
				if($var)
				{
					var_dump($var);
				}
			}
		}

	}
?>
