<?php
/* Debug: Show barcodes in database */

if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1');
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1');
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '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("Failed to load Dolibarr");
}

header('Content-Type: text/plain; charset=utf-8');

echo "=== PRODUCT BARCODES ===\n\n";

// Get all products with barcodes
$sql = "SELECT rowid, ref, label, barcode FROM ".MAIN_DB_PREFIX."product WHERE barcode IS NOT NULL AND barcode != '' ORDER BY rowid DESC LIMIT 20";
$resql = $db->query($sql);

if ($resql) {
	while ($obj = $db->fetch_object($resql)) {
		echo "ID: ".$obj->rowid."\n";
		echo "Ref: ".$obj->ref."\n";
		echo "Label: ".$obj->label."\n";
		echo "Barcode: [".$obj->barcode."] (Length: ".strlen($obj->barcode).")\n";
		echo "---\n";
	}
} else {
	echo "SQL Error: ".$db->lasterror()."\n";
}

echo "\n=== SUPPLIER BARCODES ===\n\n";

$sql2 = "SELECT pfp.rowid, pfp.fk_product, pfp.barcode, pfp.ref_fourn, p.ref as product_ref
         FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp
         LEFT JOIN ".MAIN_DB_PREFIX."product as p ON pfp.fk_product = p.rowid
         WHERE pfp.barcode IS NOT NULL AND pfp.barcode != ''
         ORDER BY pfp.rowid DESC LIMIT 20";

$resql2 = $db->query($sql2);

if ($resql2) {
	while ($obj = $db->fetch_object($resql2)) {
		echo "Product ID: ".$obj->fk_product." (".$obj->product_ref.")\n";
		echo "Supplier Barcode: [".$obj->barcode."] (Length: ".strlen($obj->barcode).")\n";
		echo "Supplier Ref: ".$obj->ref_fourn."\n";
		echo "---\n";
	}
} else {
	echo "SQL Error: ".$db->lasterror()."\n";
}

echo "\n=== SEARCH TEST ===\n";
$testCode = isset($_GET['code']) ? $_GET['code'] : '202500000068';
echo "Testing barcode: [".$testCode."]\n\n";

// Test search
$sql3 = "SELECT rowid, ref, barcode FROM ".MAIN_DB_PREFIX."product WHERE barcode = '".$db->escape($testCode)."'";
$resql3 = $db->query($sql3);
if ($resql3 && $db->num_rows($resql3) > 0) {
	$obj = $db->fetch_object($resql3);
	echo "FOUND in product.barcode: ID=".$obj->rowid.", Ref=".$obj->ref."\n";
} else {
	echo "NOT FOUND in product.barcode\n";
}

// Test with extra digit
$testCodeWith1 = $testCode . '1';
$sql4 = "SELECT rowid, ref, barcode FROM ".MAIN_DB_PREFIX."product WHERE barcode = '".$db->escape($testCodeWith1)."'";
$resql4 = $db->query($sql4);
if ($resql4 && $db->num_rows($resql4) > 0) {
	$obj = $db->fetch_object($resql4);
	echo "FOUND with extra '1': ID=".$obj->rowid.", Ref=".$obj->ref.", Barcode=".$obj->barcode."\n";
} else {
	echo "NOT FOUND with extra '1' (".$testCodeWith1.")\n";
}
