<?php
/* Copyright (C) 2026		Eduard Wisch				<data@data-it-solution.de>
 *
 * AJAX: Get order lines for a specific supplier order
 */

if (!defined('NOTOKENRENEWAL')) {
	define('NOTOKENRENEWAL', '1');
}
if (!defined('NOREQUIREMENU')) {
	define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
	define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
	define('NOREQUIREAJAX', '1');
}

// Load Dolibarr environment
$res = 0;
if (!$res && file_exists("../../main.inc.php")) {
	$res = @include "../../main.inc.php";
}
if (!$res && file_exists("../../../main.inc.php")) {
	$res = @include "../../../main.inc.php";
}
if (!$res && file_exists("../../../../main.inc.php")) {
	$res = @include "../../../../main.inc.php";
}
if (!$res) {
	die(json_encode(['success' => false, 'error' => 'Failed to load Dolibarr']));
}

require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';

header('Content-Type: application/json; charset=utf-8');

// Security check
if (!$user->hasRight('fournisseur', 'commande', 'lire') && !$user->hasRight('supplier_order', 'read')) {
	echo json_encode(['success' => false, 'error' => 'Access denied']);
	exit;
}

$orderId = GETPOSTINT('order_id');

if (empty($orderId)) {
	echo json_encode(['success' => false, 'error' => 'No order_id provided']);
	exit;
}

$order = new CommandeFournisseur($db);
if ($order->fetch($orderId) <= 0) {
	echo json_encode(['success' => false, 'error' => 'Order not found']);
	exit;
}

$lines = [];

foreach ($order->lines as $line) {
	$productLabel = $line->product_label ?: $line->desc;
	$productRef = $line->product_ref ?: '';
	$stock = 0;

	// Get stock if product exists
	if (!empty($line->fk_product)) {
		$product = new Product($db);
		if ($product->fetch($line->fk_product) > 0) {
			$stock = (float) $product->stock_reel;
			if (empty($productLabel)) {
				$productLabel = $product->label;
			}
			if (empty($productRef)) {
				$productRef = $product->ref;
			}
		}
	}

	$lines[] = [
		'id' => (int) $line->id,
		'product_id' => (int) $line->fk_product,
		'product_ref' => $productRef,
		'product_label' => $productLabel,
		'description' => $line->desc ?: '',
		'qty' => (float) $line->qty,
		'price' => (float) $line->subprice,
		'total_ht' => (float) $line->total_ht,
		'stock' => $stock,
		'ref_fourn' => $line->ref_fourn ?: '',
		'is_freetext' => empty($line->fk_product) ? true : false
	];
}

echo json_encode([
	'success' => true,
	'order' => [
		'id' => $order->id,
		'ref' => $order->ref,
		'ref_supplier' => $order->ref_supplier,
		'status' => (int) $order->statut,
		'supplier_name' => $order->thirdparty->name ?? '',
		'total_ht' => (float) $order->total_ht
	],
	'lines' => $lines
]);
