/*
	PostNuke Wasteland Item Storage
	Author:	NeoPhoenix
	Date:	16.11.2013
*/

#if defined EX_cisto_included
	#endinput
#endif
#define EX_cisto_included
#include "libraries/lib_item.inc"

stock car::item_store_OnCarInit(vehicleid)
{
	format(query,sizeof(query),"SELECT * FROM pnwl_car_items WHERE vid='%d'",VehicleInfo[vehicleid][cID]);
	SQL_RES = db_query(SQL_DB,query);
	new count = 0,unique=0;
	if(db_num_rows(SQL_RES) >= 1)
	{
		new item_cache[2];
		do
		{
			db_get_field_assoc(SQL_RES,"itemid",string,sizeof(string));
			item_cache[0] = strval(string);
			if(item_cache[0] <= 0 || item_cache[0] > MAX_ITEMS) continue;
			db_get_field_assoc(SQL_RES,"anzahl",string,sizeof(string));
			item_cache[1] = strval(string);
			unique++;
			count += item_cache[1];
		}
		while(db_next_row(SQL_RES));
	}
	db_free_result(SQL_RES);
	VehicleInfo[vehicleid][cItemsUnique] = unique;
	return 1;
}

stock car::item_store_DeleteEntry(vehicleid)
{
	format(query,sizeof(query),"DELETE FROM pnwl_car_items WHERE vid='%d'",VehicleInfo[vehicleid][cID]);
	db_query_once(SQL_DB,query);
	VehicleInfo[vehicleid][cItemsUnique] = 0;
	return;
}

forward bool:car::item_store_ChangeItemCount(vehicleid,itemid,anzahl,bool:_add=true);
stock bool:car::item_store_ChangeItemCount(vehicleid,itemid,anzahl,bool:_add=true)
{
	new oldcount	= car::item_store_CountItems(vehicleid,itemid),
		newcount	= _add?oldcount+anzahl:anzahl;	
	if(oldcount == 0 && newcount <= 0) return true;
	if(newcount >= 1)
	{
		if(oldcount == 0)
		{//Insert
			format(query,sizeof(query),"INSERT INTO pnwl_car_items (vid,itemid,anzahl)",VehicleInfo[vehicleid][cID],itemid,newcount);
			db_query_once(SQL_DB,query);
			VehicleInfo[vehicleid][cItemsUnique]++;
		}
		else
		{//Update
			format(query,sizeof(query),"UPDATE pnwl_car_items SET anzahl=%d WHERE vid='%d' AND itemid='%d'",newcount,VehicleInfo[vehicleid][cID],itemid);
			db_query_once(SQL_DB,query);
		}
	}
	else if(newcount <= 0)
	{
		if(oldcount >= 1)
		{//Delete
			format(query,sizeof(query),"DELETE * FROM pnwl_car_items WHERE vid='%d' AND itemid='%d'",VehicleInfo[vehicleid][cID],itemid);
			db_query_once(SQL_DB,query);
			VehicleInfo[vehicleid][cItemsUnique]--;
		}
	}
	return true;
}

stock car::item_store_CountItems(vehicleid,itemid)
{
	format(query,sizeof(query),"SELECT * FROM pnwl_car_items WHERE vid='%d' AND itemid='%d'",VehicleInfo[vehicleid][cID],itemid);
	new DBResult:res	= db_query(SQL_DB,query),
		anzahl			= 0;
	if(db_num_rows(res))
	{
		db_get_field_assoc(res,"anzahl",string,sizeof(string));
		anzahl = strval(string);
	}
	db_free_result(res);
	return anzahl;
}