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

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', 'lire') && !$user->hasRight('supplier_order', 'read')) {
	echo json_encode(['success' => false, 'error' => 'Access denied']);
	exit;
}

$orders = [];

// Get all draft orders (fk_statut = 0) and approved orders (fk_statut = 1)
// Sorted: Direkt-drafts first, then other drafts, then approved
$sql = "SELECT cf.rowid, cf.ref, cf.ref_supplier, cf.fk_statut as status, cf.date_commande, cf.total_ht,";
$sql .= " s.nom as supplier_name, s.rowid as supplier_id,";
$sql .= " (SELECT COUNT(*) FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande = cf.rowid) as line_count,";
$sql .= " (SELECT SUM(qty) FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande = cf.rowid) as total_qty";
$sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON cf.fk_soc = s.rowid";
$sql .= " WHERE cf.entity IN (".getEntity('supplier_order').")";
$sql .= " AND cf.fk_statut IN (0, 1, 2)"; // Draft, Validated, Approved
$sql .= " ORDER BY";
// Direkt-Bestellungen (Entwurf) zuerst
$sql .= " CASE WHEN cf.fk_statut = 0 AND cf.ref_supplier LIKE '%-Direkt' THEN 0";
// Dann Direkt-Bestellungen (freigestellt)
$sql .= " WHEN cf.fk_statut IN (1,2) AND cf.ref_supplier LIKE '%-Direkt' THEN 1";
// Dann andere Entwürfe
$sql .= " WHEN cf.fk_statut = 0 THEN 2";
// Dann alle anderen
$sql .= " ELSE 3 END,";
$sql .= " cf.date_commande DESC, cf.rowid DESC";

$resql = $db->query($sql);
if ($resql) {
	while ($obj = $db->fetch_object($resql)) {
		$isDirekt = (strpos($obj->ref_supplier, '-Direkt') !== false);

		$orders[] = [
			'id' => (int) $obj->rowid,
			'ref' => $obj->ref,
			'ref_supplier' => $obj->ref_supplier,
			'status' => (int) $obj->status,
			'status_label' => getOrderStatusLabel((int) $obj->status),
			'date' => $obj->date_commande,
			'total_ht' => (float) $obj->total_ht,
			'supplier_id' => (int) $obj->supplier_id,
			'supplier_name' => $obj->supplier_name,
			'line_count' => (int) $obj->line_count,
			'total_qty' => (float) $obj->total_qty,
			'is_direkt' => $isDirekt
		];
	}
}

/**
 * Get status label
 */
function getOrderStatusLabel($status) {
	switch ($status) {
		case 0: return 'Entwurf';
		case 1: return 'Validiert';
		case 2: return 'Freigegeben';
		case 3: return 'Bestellt';
		case 4: return 'Teilweise geliefert';
		case 5: return 'Geliefert';
		case 6: return 'Storniert';
		case 7: return 'Annulliert';
		case 9: return 'Abgelehnt';
		default: return 'Unbekannt';
	}
}

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