<?php
/* Copyright (C) 2004-2017  Laurent Destailleur     <eldy@users.sourceforge.net>
 * Copyright (C) 2024       Frédéric France         <frederic.france@free.fr>
 * Copyright (C) 2026		Eduard Wisch			<data@data-it-solution.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 */

/**
 * \file    handybarcodescanner/admin/setup.php
 * \ingroup handybarcodescanner
 * \brief   HandyBarcodeScanner setup page.
 */

// Load Dolibarr environment
$res = 0;
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
	$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
}
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME'];
$tmp2 = realpath(__FILE__);
$i = strlen($tmp) - 1;
$j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
	$i--;
	$j--;
}
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
	$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
}
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
	$res = @include dirname(substr($tmp, 0, ($i + 1)))."/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("Include of main fails");
}

// Libraries
require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
require_once '../lib/handybarcodescanner.lib.php';

/**
 * @var Conf $conf
 * @var DoliDB $db
 * @var HookManager $hookmanager
 * @var Translate $langs
 * @var User $user
 */

// Translations
$langs->loadLangs(array("admin", "handybarcodescanner@handybarcodescanner", "stocks"));

// Access control
if (!$user->admin) {
	accessforbidden();
}

// Parameters
$action = GETPOST('action', 'aZ09');
$backtopage = GETPOST('backtopage', 'alpha');

$error = 0;

/*
 * Actions
 */

if ($action == 'update') {
	// Order prefix
	$orderPrefix = GETPOST('order_prefix', 'alphanohtml');
	if (!empty($orderPrefix)) {
		dolibarr_set_const($db, 'HANDYBARCODESCANNER_ORDER_PREFIX', $orderPrefix, 'chaine', 0, '', $conf->entity);
	}

	// Default warehouse
	$defaultWarehouse = GETPOSTINT('default_warehouse');
	dolibarr_set_const($db, 'HANDYBARCODESCANNER_DEFAULT_WAREHOUSE', $defaultWarehouse, 'chaine', 0, '', $conf->entity);

	// Mode toggles
	$enableOrder = GETPOSTINT('enable_order');
	$enableShop = GETPOSTINT('enable_shop');
	$enableInventory = GETPOSTINT('enable_inventory');

	dolibarr_set_const($db, 'HANDYBARCODESCANNER_ENABLE_ORDER', $enableOrder, 'chaine', 0, '', $conf->entity);
	dolibarr_set_const($db, 'HANDYBARCODESCANNER_ENABLE_SHOP', $enableShop, 'chaine', 0, '', $conf->entity);
	dolibarr_set_const($db, 'HANDYBARCODESCANNER_ENABLE_INVENTORY', $enableInventory, 'chaine', 0, '', $conf->entity);

	// Vibration feedback
	$enableVibration = GETPOSTINT('enable_vibration');
	dolibarr_set_const($db, 'HANDYBARCODESCANNER_ENABLE_VIBRATION', $enableVibration, 'chaine', 0, '', $conf->entity);

	// Sound feedback
	$enableSound = GETPOSTINT('enable_sound');
	dolibarr_set_const($db, 'HANDYBARCODESCANNER_ENABLE_SOUND', $enableSound, 'chaine', 0, '', $conf->entity);

	setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
}


/*
 * View
 */

$form = new Form($db);

$help_url = '';
$title = "HandyBarcodeScannerSetup";

llxHeader('', $langs->trans($title), $help_url, '', 0, 0, '', '', '', 'mod-handybarcodescanner page-admin');

// Subheader
$linkback = '<a href="'.($backtopage ? $backtopage : DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1').'">'.$langs->trans("BackToModuleList").'</a>';

print load_fiche_titre($langs->trans($title), $linkback, 'title_setup');

// Configuration header
$head = handybarcodescannerAdminPrepareHead();
print dol_get_fiche_head($head, 'settings', $langs->trans($title), -1, "handybarcodescanner@handybarcodescanner");

// Get current values
$orderPrefix = getDolGlobalString('HANDYBARCODESCANNER_ORDER_PREFIX', 'Direktbestellung');
$defaultWarehouse = getDolGlobalInt('HANDYBARCODESCANNER_DEFAULT_WAREHOUSE', 0);
$enableOrder = getDolGlobalInt('HANDYBARCODESCANNER_ENABLE_ORDER', 1);
$enableShop = getDolGlobalInt('HANDYBARCODESCANNER_ENABLE_SHOP', 1);
$enableInventory = getDolGlobalInt('HANDYBARCODESCANNER_ENABLE_INVENTORY', 1);
$enableVibration = getDolGlobalInt('HANDYBARCODESCANNER_ENABLE_VIBRATION', 1);
$enableSound = getDolGlobalInt('HANDYBARCODESCANNER_ENABLE_SOUND', 0);

// Get warehouses for select
$warehouses = array();
$sql = "SELECT rowid, ref, lieu FROM ".MAIN_DB_PREFIX."entrepot WHERE statut = 1 AND entity IN (".getEntity('stock').") ORDER BY ref";
$resql = $db->query($sql);
if ($resql) {
	while ($obj = $db->fetch_object($resql)) {
		$warehouses[$obj->rowid] = $obj->ref . ($obj->lieu ? ' - ' . $obj->lieu : '');
	}
}

print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="update">';

print '<table class="noborder centpercent">';

// Section: General
print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("General").'</td></tr>';

// Order prefix
print '<tr class="oddeven">';
print '<td class="titlefield">'.$langs->trans("OrderPrefix").'</td>';
print '<td>';
print '<input type="text" name="order_prefix" value="'.dol_escape_htmltag($orderPrefix).'" class="minwidth300">';
print '<br><span class="opacitymedium small">'.$langs->trans("OrderPrefixDesc").'</span>';
print '</td></tr>';

// Default warehouse
print '<tr class="oddeven">';
print '<td>'.$langs->trans("DefaultWarehouse").'</td>';
print '<td>';
print '<select name="default_warehouse" class="flat minwidth200">';
print '<option value="0">-- '.$langs->trans("FirstAvailable").' --</option>';
foreach ($warehouses as $id => $label) {
	print '<option value="'.$id.'"'.($defaultWarehouse == $id ? ' selected' : '').'>'.dol_escape_htmltag($label).'</option>';
}
print '</select>';
print '<br><span class="opacitymedium small">'.$langs->trans("DefaultWarehouseDesc").'</span>';
print '</td></tr>';

// Section: Enabled Modes
print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("EnabledModes").'</td></tr>';

// Order mode
print '<tr class="oddeven">';
print '<td>'.$langs->trans("EnableOrderMode").'</td>';
print '<td>';
print '<input type="checkbox" name="enable_order" value="1"'.($enableOrder ? ' checked' : '').'>';
print '</td></tr>';

// Shop mode
print '<tr class="oddeven">';
print '<td>'.$langs->trans("EnableShopMode").'</td>';
print '<td>';
print '<input type="checkbox" name="enable_shop" value="1"'.($enableShop ? ' checked' : '').'>';
print '</td></tr>';

// Inventory mode
print '<tr class="oddeven">';
print '<td>'.$langs->trans("EnableInventoryMode").'</td>';
print '<td>';
print '<input type="checkbox" name="enable_inventory" value="1"'.($enableInventory ? ' checked' : '').'>';
print '</td></tr>';

// Section: Feedback
print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Feedback").'</td></tr>';

// Vibration
print '<tr class="oddeven">';
print '<td>'.$langs->trans("EnableVibration").'</td>';
print '<td>';
print '<input type="checkbox" name="enable_vibration" value="1"'.($enableVibration ? ' checked' : '').'>';
print '<br><span class="opacitymedium small">'.$langs->trans("EnableVibrationDesc").'</span>';
print '</td></tr>';

// Sound
print '<tr class="oddeven">';
print '<td>'.$langs->trans("EnableSound").'</td>';
print '<td>';
print '<input type="checkbox" name="enable_sound" value="1"'.($enableSound ? ' checked' : '').'>';
print '<br><span class="opacitymedium small">'.$langs->trans("EnableSoundDesc").'</span>';
print '</td></tr>';

print '</table>';

print '<div class="center">';
print '<input type="submit" class="button" value="'.$langs->trans("Save").'">';
print '</div>';

print '</form>';

// Show QR Code for mobile access
print '<br><br>';
print '<div class="fichecenter">';
print '<div class="fichehalfleft">';
print '<table class="noborder centpercent">';
print '<tr class="liste_titre"><td>'.$langs->trans("MobileAccess").'</td></tr>';
print '<tr class="oddeven"><td>';

$scannerUrl = dol_buildpath('/handybarcodescanner/handybarcodescannerindex.php', 2);
print '<p>'.$langs->trans("ScanQRCodeOrOpenURL").':</p>';
print '<p><a href="'.$scannerUrl.'" target="_blank" class="button">'.$scannerUrl.'</a></p>';

// QR Code using Google Charts API
$qrUrl = 'https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl='.urlencode($scannerUrl);
print '<p><img src="'.$qrUrl.'" alt="QR Code" style="border: 1px solid #ccc; padding: 10px;"></p>';

print '</td></tr>';
print '</table>';
print '</div>';
print '</div>';

// Page end
print dol_get_fiche_end();

llxFooter();
$db->close();
