<?php
/* Copyright (C) 2026		Eduard Wisch				<data@data-it-solution.de>
 *
 * AJAX: Update or delete order line
 */

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';

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

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

$action = GETPOST('action', 'alpha');
$orderId = GETPOSTINT('order_id');
$lineId = GETPOSTINT('line_id');

if (empty($orderId) || empty($lineId)) {
	echo json_encode(['success' => false, 'error' => 'Missing parameters']);
	exit;
}

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

// Only allow changes to draft orders
if ($order->statut != 0) {
	echo json_encode(['success' => false, 'error' => 'Order is not a draft']);
	exit;
}

// Find line
$targetLine = null;
foreach ($order->lines as $line) {
	if ($line->id == $lineId) {
		$targetLine = $line;
		break;
	}
}

if (!$targetLine) {
	echo json_encode(['success' => false, 'error' => 'Line not found']);
	exit;
}

if ($action === 'delete') {
	$result = $order->deleteLine($lineId);

	if ($result < 0) {
		echo json_encode(['success' => false, 'error' => 'Failed to delete line: ' . $order->error]);
		exit;
	}

	// Check if order is now empty - if so, delete it
	$order->fetch($orderId);
	if (count($order->lines) == 0) {
		$order->delete($user);
		echo json_encode([
			'success' => true,
			'message' => 'Line and empty order deleted',
			'order_deleted' => true
		]);
		exit;
	}

	echo json_encode([
		'success' => true,
		'message' => 'Line deleted',
		'order_deleted' => false
	]);

} elseif ($action === 'update') {
	$newQty = GETPOSTFLOAT('qty');
	$newDesc = GETPOST('description', 'restricthtml');

	if ($newQty <= 0) {
		echo json_encode(['success' => false, 'error' => 'Quantity must be greater than 0']);
		exit;
	}

	// Use new description if provided, otherwise keep existing
	$description = !empty($newDesc) ? $newDesc : $targetLine->desc;

	$result = $order->updateline(
		$lineId,
		$description,
		$targetLine->subprice,
		$newQty,
		$targetLine->remise_percent,
		$targetLine->tva_tx,
		$targetLine->localtax1_tx ?: 0,
		$targetLine->localtax2_tx ?: 0,
		'HT',
		0,
		0,
		$targetLine->product_type ?: 0,
		false,
		null,
		null,
		0,
		$targetLine->ref_fourn
	);

	if ($result < 0) {
		echo json_encode(['success' => false, 'error' => 'Failed to update line: ' . $order->error]);
		exit;
	}

	echo json_encode([
		'success' => true,
		'message' => 'Line updated',
		'new_qty' => $newQty
	]);

} else {
	echo json_encode(['success' => false, 'error' => 'Unknown action']);
}
