<?php
/* Copyright (C) 2026		Eduard Wisch				<data@data-it-solution.de>
 *
 * AJAX: Add free text line to 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.'/societe/class/societe.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;
}

$supplierId = GETPOSTINT('supplier_id');
$description = GETPOST('description', 'alphanohtml');
$qty = GETPOSTFLOAT('qty');
$price = GETPOSTFLOAT('price');

if (empty($supplierId) || empty($description) || $qty <= 0) {
	echo json_encode(['success' => false, 'error' => 'Missing parameters (supplier_id, description, qty required)']);
	exit;
}

// Load supplier
$supplier = new Societe($db);
if ($supplier->fetch($supplierId) <= 0) {
	echo json_encode(['success' => false, 'error' => 'Supplier not found']);
	exit;
}

// Build ref_supplier for today
$refSupplier = date('ymd') . '-Direkt';

// Search for existing draft order for this supplier with today's ref_supplier
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur";
$sql .= " WHERE fk_soc = ".((int) $supplierId);
$sql .= " AND fk_statut = 0"; // Draft status
$sql .= " AND ref_supplier = '".$db->escape($refSupplier)."'";
$sql .= " AND entity IN (".getEntity('supplier_order').")";
$sql .= " ORDER BY rowid DESC LIMIT 1";

$resql = $db->query($sql);
$existingOrderId = 0;

if ($resql && $db->num_rows($resql) > 0) {
	$obj = $db->fetch_object($resql);
	$existingOrderId = $obj->rowid;
}

$order = new CommandeFournisseur($db);

if ($existingOrderId > 0) {
	$order->fetch($existingOrderId);
} else {
	// Create new order
	$order->socid = $supplierId;
	$order->ref_supplier = $refSupplier;
	$order->cond_reglement_id = $supplier->cond_reglement_supplier_id ?: getDolGlobalInt('FOURN_COND_REGLEMENT_ID_DEFAULT', 1);
	$order->mode_reglement_id = $supplier->mode_reglement_supplier_id ?: getDolGlobalInt('FOURN_MODE_REGLEMENT_ID_DEFAULT', 1);
	$order->date = dol_now();
	$order->date_livraison = dol_now() + (7 * 24 * 60 * 60);

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

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

// Add free text line (no product_id)
$tva_tx = getDolGlobalString('MAIN_DEFAULT_TVA') ?: 19;

$result = $order->addline(
	$description,       // description
	$price,            // pu_ht (unit price)
	$qty,              // qty
	$tva_tx,           // txtva
	0,                 // localtax1
	0,                 // localtax2
	0,                 // fk_product (0 = free text)
	0,                 // fk_prod_fourn_price
	'',                // ref_fourn
	0,                 // remise_percent
	'HT',              // price_base_type
	0,                 // pu_devise
	0,                 // type (0 = product, 1 = service)
	0,                 // rang
	0                  // special_code
);

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

// Get updated order info
$order->fetch($order->id);
$totalItems = count($order->lines);
$totalQty = 0;
foreach ($order->lines as $line) {
	$totalQty += $line->qty;
}

echo json_encode([
	'success' => true,
	'order_id' => $order->id,
	'order_ref' => $order->ref,
	'total_items' => $totalItems,
	'total_qty' => $totalQty,
	'message' => 'Free text line added to ' . $order->ref
]);
