<?php
	if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal

	$res=@include("../../main.inc.php");					// For root directory
	if (! $res) $res=@include("../../../main.inc.php");		// For "custom" directory

	require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
	require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
	include_once __DIR__ . '/../lib/dolitools.lib.php';

	$idprod = GETPOST("idprod");
	$thirdpartyid = GETPOST("thirdpartyid");

	$thirdparty = new Societe($db);
	$thirdparty->fetch($thirdpartyid);

	$product = new Product($db);
	$product->fetch($idprod);

	if (empty($product->status))
	{
		$langs->load("altatpl@dolitools");
		$ret['error'] = 1;
		$ret['error_desc'] = $langs->trans("ProductNotOnSale");
	}
	else
	{
		$ret = array("error"=>"0");

		$ret['prodlink'] = $product->getNomUrl(1, '', 0, 0, 1).' - '.dol_trunc($product->label,66,'middle');

		$ret['label'] = $product->label;

		$ret['description'] = $product->description;

		$product->load_stock();

		if ($conf->global->USE_AVAILABLE_STOCK) {
			include_once __DIR__ . '/../lib/availablestock.lib.php';
			load_available_stock($product);
			$stock = $product->stock_available;
		}
		else
		{
			$stock = $product->stock_reel?$product->stock_reel:"0";

			if ($conf->global->USE_VIRTUAL_STOCK) {
				$product->load_virtual_stock();
				$stock = $product->stock_theorique;
			}

			if (!empty($conf->rental->enabled))
			{
				dol_include_once("/rental/lib/rental.lib.php");
				$stock = get_sell_stock($idprod);
			}
		}

		$ret['stock_available'] = $stock;
		$ret['stock'] = $stock;

		$ret['onpurchase'] = $product->status_buy;
		$ret['product_type'] = $product->type;

		// Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
		$pqp = (GETPOST('pbq', 'int') ? GETPOST('pbq', 'int') : 0);

		$datapriceofproduct = $product->getSellPrice($mysoc, $thirdparty, $pqp);

		$pu_ht = $datapriceofproduct['pu_ht'];
		$pu_ttc = $datapriceofproduct['pu_ttc'];
		$price_min = $datapriceofproduct['price_min'];
		$price_base_type = $datapriceofproduct['price_base_type'];
		$tva_tx = $datapriceofproduct['tva_tx'];
		$tva_npr = $datapriceofproduct['tva_npr'];

		$tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
		$tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $product->tva_tx));

		// On reevalue prix selon taux tva car taux tva transaction peut etre different
		// de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
		if ($tmpvat != $tmpprodvat)
		{
			if ($price_base_type != 'HT')
			{
				$pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
			}
			else
			{
				$pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
			}
		}

		$ret['price'] = price2num($pu_ht);
		$ret['tva_tx'] = price2num($tva_tx);
		$ret['price_ttc'] = price2num($pu_ttc);

		$ret['units'] = $product->fk_unit;
	}

	echo json_encode($ret);
?>
