<?php
/* Copyright (C) 2026		Eduard Wisch				<data@data-it-solution.de>
 *
 * AJAX: Get all suppliers for manual selection
 */

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']));
}

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

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

// Get all suppliers (fournisseur = 1)
$sql = "SELECT rowid, nom, url FROM ".MAIN_DB_PREFIX."societe";
$sql .= " WHERE fournisseur = 1";
$sql .= " AND status = 1"; // Active only
$sql .= " AND entity IN (".getEntity('societe').")";
$sql .= " ORDER BY nom ASC";

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

$suppliers = [];

if ($resql) {
	while ($obj = $db->fetch_object($resql)) {
		$suppliers[] = [
			'id' => (int) $obj->rowid,
			'name' => $obj->nom,
			'url' => $obj->url ?: ''
		];
	}
}

echo json_encode([
	'success' => true,
	'suppliers' => $suppliers
]);
