<?php
/* Copyright (C) 2026		Eduard Wisch				<data@data-it-solution.de>
 *
 * AJAX: Delete entire 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';

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

// Security check
if (!$user->hasRight('fournisseur', 'commande', 'supprimer') && !$user->hasRight('supplier_order', 'supprimer')) {
	echo json_encode(['success' => false, 'error' => 'Keine Berechtigung zum Löschen']);
	exit;
}

$orderId = GETPOSTINT('order_id');

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

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

// Only allow deletion of draft orders
if ($order->statut != 0) {
	echo json_encode(['success' => false, 'error' => 'Nur Entwürfe können gelöscht werden']);
	exit;
}

$result = $order->delete($user);

if ($result < 0) {
	echo json_encode(['success' => false, 'error' => 'Löschen fehlgeschlagen: ' . $order->error]);
	exit;
}

echo json_encode([
	'success' => true,
	'message' => 'Bestellung gelöscht'
]);
