<?php
/*
    part-db version 0.1
    Copyright (C) 2005 Christoph Lechner
    http://www.cl-projects.de/

    part-db version 0.2+
    Copyright (C) 2009 K. Jacobs and others (see authors.php)
    http://code.google.com/p/part-db/

    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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

    $Id$

    Changelog (sorted by date):
        [DATE]      [NICKNAME]          [CHANGES]
*/

    include_once('start_session.php');

	/* API version */
	$version=1;

    $messages = array();

    $keyword = isset($_REQUEST['name']) ? trim((string)$_REQUEST['name']) : '';
    $action = isset($_REQUEST['action']) ? trim((string)$_REQUEST['action']) : '';
    $id = isset($_REQUEST['id']) ? (integer)$_REQUEST['id'] : '';
    $quantity = isset($_REQUEST['quantity']) ? (integer)$_REQUEST['quantity'] : 0;
    $category_name = isset($_REQUEST['category_name']) ? trim((string)$_REQUEST['category_name']) : '';
    $footprint_name = isset($_REQUEST['footprint_name']) ? trim((string)$_REQUEST['footprint_name']) : '';
    $part_id = isset($_REQUEST['pid']) ? (integer)$_REQUEST['pid'] : -1;
    $supplier_name =  isset($_REQUEST['supplier_name']) ? trim((string)$_REQUEST['supplier_name']) : '';
    $supplier_id = isset($_REQUEST['supplier_id']) ? (integer)$_REQUEST['supplier_id'] : 0;
    $supplierpartnr = isset($_REQUEST['supplierpartnr']) ? (string)$_REQUEST['supplierpartnr'] : '';
    
    $new_name = isset($_REQUEST['name']) ? (string)$_REQUEST['name'] : '';
    $new_description = isset($_REQUEST['description']) ? (string)$_REQUEST['description'] : '';
    $new_manufacturer_id = isset($_REQUEST['manufacturer_id']) ? (integer)$_REQUEST['manufacturer_id'] : 0;
    $new_instock = isset($_REQUEST['instock']) ? (integer)$_REQUEST['instock'] : 0;
    $new_mininstock = isset($_REQUEST['mininstock']) ? (integer)$_REQUEST['mininstock'] : 0;
    $new_category_id = isset($_REQUEST['category_id']) ? (integer)$_REQUEST['category_id'] : 0;
    $new_storelocation_id = isset($_REQUEST['storelocation_id']) ? (integer)$_REQUEST['storelocation_id'] : 0;
    $new_footprint_id = isset($_REQUEST['footprint_id']) ? (integer)$_REQUEST['footprint_id'] : 0;
    $new_visible = isset($_REQUEST['visible']);
    $new_comment = isset($_REQUEST['comment']) ? (string)$_REQUEST['comment'] : '';
    
    $new_show_in_table = isset($_REQUEST['show_in_table']);
    $new_attachement_type_id = isset($_REQUEST['attachement_type_id']) ? (integer)$_REQUEST['attachement_type_id'] : 0;
    $new_is_master_picture = isset($_REQUEST['is_master_picture']);
    
    $orderdetails_id = isset($_REQUEST['orderdetails_id']) ? (integer)$_REQUEST['orderdetails_id'] : 0;
    $new_supplier_id = $supplier_id;
    $new_supplierpartnr = $supplierpartnr;
    
    $new_price = isset($_REQUEST['price']) ? (float)str_replace(',', '.', $_REQUEST['price']) : 0; // TODO: use the PHP class "NumberFormatter"
    $new_min_discount_quantity = isset($_REQUEST['min_discount_quantity']) ? (integer)$_REQUEST['min_discount_quantity'] : 1;
    $new_price_related_quantity = isset($_REQUEST['price_related_quantity']) ? (integer)$_REQUEST['price_related_quantity'] : 1;
    
    $new_footprint_name =  $footprint_name;
    $new_footprint_parent_id =  isset($_REQUEST['footprint_parent_id']) ? (integer)$_REQUEST['footprint_parent_id'] : 0;
    
    $show_version = isset($_REQUEST['version']);
    
    /********************************************************************************
    *
    *   Initialize Objects
    *
    *********************************************************************************/

    // Echo all parameters
//    foreach ($_REQUEST as $key=>$value) {
//    	echo "$key = " . urldecode($value) . "<br />\n";
//    }
    $xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><api_response></api_response>");
    
    try
    {
    	$database = new Database();
    	$log = new Log($database);
    	$current_user = new User($database, $current_user, $log, 1); // admin
    
    	switch ($action)
    	{
    		case 'increase_quantity':
    			try
    			{
    				$part = new Part($database, $current_user, $log, $id);
    				$part->set_instock($part->get_instock() + $quantity);
    				
   					$xml->addChild('ok','');
    			}
    			catch (Exception $e)
    			{
   					$xml->addChild('err',$e->getMessage());
    			}
    			break;
    		case 'name2id':
    			try
    			{
    				$search_name = true;
    				$search_category = false;
    				$search_description = false;
    				$search_comment = false;
    				$search_supplier = false;
    				$search_supplierpartnr = false;
    				$search_storelocation = false;
    				$search_footprint = false;
    				$search_manufacturer = false;
    				
    				$category_parts = Part::search_parts($database, $current_user, $log, $keyword, '',
    						$search_name, $search_description, $search_comment,
    						$search_footprint, $search_category, $search_storelocation,
    						$search_supplier, $search_supplierpartnr, $search_manufacturer);
    				$hits_count = count($category_parts);
    			
    				if ($hits_count == 1)
    				{
    					$xml->addChild('id', $category_parts[0] -> get_id());
    				}
    				else
    				{
    					$xml->addChild('id', 0);
    				}
    			}
    			catch (Exception $e)
    			{
    				$xml->addChild('err',$e->getMessage());
    			}
    			break;
    		case 'categoryname2id':
    			try
    			{
    				 $search_result = Category::search($database, $current_user, $log, $category_name);
    				 if (isset($search_result[0]))
    				 {
    				 	$xml->addChild('category_id', $search_result[0]->get_id());
    				 }
    				 else
    				 {
    				 	$xml->addChild('category_id', 0);
    				 }
    			}
    			catch (Exception $e)
    			{
					$xml->addChild('err',$e->getMessage());
    			}
    			break;
			case 'create_new_part':
				try
				{
					$part = Part::add( $database, $current_user, $log, $new_name, $new_category_id,
    							$new_description, $new_instock, $new_mininstock, $new_storelocation_id,
    							$new_manufacturer_id, $new_footprint_id, $new_comment, $new_visible);
					$xml->addChild('ok','');
				}
				catch (Exception $e)
				{
					$xml->addChild('err',$e->getMessage());
				}
				break;
			case 'footprintname2footprintid':
    			try
    			{
    				 $search_result = Footprint::search($database, $current_user, $log, $footprint_name, true);
    				 if (isset($search_result[0]))
    				 {
    				 	$xml->addChild('footprint_id', $search_result[0]->get_id());
    				 }
    				 else
    				 {
    				 	$xml->addChild('footprint_id', 0);
    				 }
    			}
    			catch (Exception $e)
    			{
					$xml->addChild('err',$e->getMessage());
    			}
    			break;
			case 'attachement_add':
				try
				{
					if ((strlen($_FILES['attachement_file']['name']) == 0) == (strlen($new_filename) == 0))
						throw new Exception('Sie müssen entweder ein Dateiname angeben, oder eine Datei zum Hochladen wählen!');

					if (strlen($_FILES['attachement_file']['name']) > 0)
						$new_filename = upload_file($_FILES['attachement_file'], BASE.'/data/media/');
						/* We need to urlencode for links to work properly */
						$new_filename = implode('/', array_map('rawurlencode', explode('/', $new_filename)));
						$new_name = urldecode(basename($new_filename));
					
					$part = new Part($database, $current_user, $log, $part_id);

					$new_attachement = Attachement::add($database, $current_user, $log, $part, $new_attachement_type_id,
							$new_filename, $new_name, $new_show_in_table);
								
					if ($new_is_master_picture && $new_attachement->is_picture())
						$part->set_master_picture_attachement_id($new_attachement->get_id());
					
					$xml->addChild('ok','');
				}
				catch (Exception $e)
				{
					$xml->addChild('err',$e->getMessage());
				}
				break;
			case 'suppliername2supplierID':
    			try
    			{
    				 $search_result = Supplier::search($database, $current_user, $log, $supplier_name);
    				 if (isset($search_result[0]))
    				 {
    				 	$xml->addChild('supplier_id', $search_result[0]->get_id());
    				 }
    				 else
    				 {
    				 	$xml->addChild('supplier_id', 0);
    				 }
    			}
    			catch (Exception $e)
    			{
					$xml->addChild('err',$e->getMessage());
    			}
    			break;
			case 'orderdetails_add':
				try
				{
					$new_orderdetails = Orderdetails::add($database, $current_user, $log, $part_id,
							$new_supplier_id, $new_supplierpartnr, $new_obsolete);
					
					$xml->addChild('ok','');
				}
				catch (Exception $e)
				{
					$xml->addChild('err',$e->getMessage());
				}
				break;
			case 'pricedetails_add':
				try
				{
					$part = new Part($database, $current_user, $log, $part_id);
					foreach ($part->get_orderdetails() as $orderdetails)
					{
						if (($orderdetails->get_supplier()->get_id() == $supplier_id) && ($orderdetails->get_supplierpartnr() == $supplierpartnr))
						{
							$new_pricedetails = Pricedetails::add($database, $current_user, $log, $orderdetails->get_id(),
									$new_price, $new_price_related_quantity,
									$new_min_discount_quantity);

							$xml->addChild('ok','');
							break;
						}
					}
						
				}
				catch (Exception $e)
				{
					$xml->addChild('err',$e->getMessage());
				}
				break;
			case 'footprint_add':
				try
				{
					$new_orderdetails = Footprint::add($database, $current_user, $log, $new_footprint_name,
							$new_footprint_parent_id);
					
					$xml->addChild('ok','');
				}
				catch (Exception $e)
				{
					$xml->addChild('err',$e->getMessage());
				}
				break;
    	}
	}
	catch (Exception $e)
	{
		$xml->addChild('err',$e->getMessage());
	}
	
	if($show_version)
	{
		$xml->addChild('api_version',$version);
	}
    	 
    header('Content-type: text/xml');
    print($xml->asXML());
    

?>
