<?php
/* 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.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

/**
 * \file    kundenkarte/admin/setup.php
 * \ingroup kundenkarte
 * \brief   KundenKarte setup page.
 */

// 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) {
	die("Include of main fails");
}

// Libraries
require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
require_once '../lib/kundenkarte.lib.php';

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

// Access control
if (!$user->admin && !$user->hasRight('kundenkarte', 'admin')) {
	accessforbidden();
}

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

// Directory for PDF templates
$uploadDir = $conf->kundenkarte->dir_output.'/templates';

/*
 * Actions
 */

// Handle PDF template upload
if ($action == 'upload_template') {
	$error = 0;

	if (!empty($_FILES['pdf_template']['name'])) {
		// Check file type
		$fileInfo = pathinfo($_FILES['pdf_template']['name']);
		if (strtolower($fileInfo['extension']) !== 'pdf') {
			setEventMessages($langs->trans("ErrorOnlyPDFAllowed"), null, 'errors');
			$error++;
		}

		if (!$error) {
			// Create directory if not exists
			if (!is_dir($uploadDir)) {
				dol_mkdir($uploadDir);
			}

			// Save template as fixed name
			$targetFile = $uploadDir.'/export_template.pdf';

			if (move_uploaded_file($_FILES['pdf_template']['tmp_name'], $targetFile)) {
				dolibarr_set_const($db, 'KUNDENKARTE_PDF_TEMPLATE', 'export_template.pdf', 'chaine', 0, '', $conf->entity);
				setEventMessages($langs->trans("TemplateUploadSuccess"), null, 'mesgs');
			} else {
				setEventMessages($langs->trans("ErrorUploadFailed"), null, 'errors');
			}
		}
	} else {
		setEventMessages($langs->trans("ErrorNoFileSelected"), null, 'errors');
	}
}

// Handle template deletion
if ($action == 'delete_template') {
	$templateFile = $uploadDir.'/export_template.pdf';
	if (file_exists($templateFile)) {
		unlink($templateFile);
		dolibarr_set_const($db, 'KUNDENKARTE_PDF_TEMPLATE', '', 'chaine', 0, '', $conf->entity);
		setEventMessages($langs->trans("TemplateDeleted"), null, 'mesgs');
	}
}

if ($action == 'update') {
	$error = 0;

	// Save settings
	$res = dolibarr_set_const($db, 'KUNDENKARTE_SHOW_FAVORITES_TAB', GETPOSTINT('KUNDENKARTE_SHOW_FAVORITES_TAB'), 'chaine', 0, '', $conf->entity);
	if (!($res > 0)) {
		$error++;
	}

	$res = dolibarr_set_const($db, 'KUNDENKARTE_SHOW_ANLAGEN_TAB', GETPOSTINT('KUNDENKARTE_SHOW_ANLAGEN_TAB'), 'chaine', 0, '', $conf->entity);
	if (!($res > 0)) {
		$error++;
	}

	$res = dolibarr_set_const($db, 'KUNDENKARTE_DEFAULT_ORDER_TYPE', GETPOSTINT('KUNDENKARTE_DEFAULT_ORDER_TYPE'), 'chaine', 0, '', $conf->entity);
	if (!($res > 0)) {
		$error++;
	}

	// PDF font size settings
	dolibarr_set_const($db, 'KUNDENKARTE_PDF_FONT_HEADER', GETPOSTINT('KUNDENKARTE_PDF_FONT_HEADER'), 'chaine', 0, '', $conf->entity);
	dolibarr_set_const($db, 'KUNDENKARTE_PDF_FONT_CONTENT', GETPOSTINT('KUNDENKARTE_PDF_FONT_CONTENT'), 'chaine', 0, '', $conf->entity);
	dolibarr_set_const($db, 'KUNDENKARTE_PDF_FONT_FIELDS', GETPOSTINT('KUNDENKARTE_PDF_FONT_FIELDS'), 'chaine', 0, '', $conf->entity);

	// View mode
	dolibarr_set_const($db, 'KUNDENKARTE_DEFAULT_VIEW', GETPOST('KUNDENKARTE_DEFAULT_VIEW', 'aZ09'), 'chaine', 0, '', $conf->entity);

	// Tree display settings
	dolibarr_set_const($db, 'KUNDENKARTE_TREE_INFO_DISPLAY', GETPOST('KUNDENKARTE_TREE_INFO_DISPLAY', 'aZ09'), 'chaine', 0, '', $conf->entity);
	dolibarr_set_const($db, 'KUNDENKARTE_TREE_BADGE_COLOR', GETPOST('KUNDENKARTE_TREE_BADGE_COLOR', 'alphanohtml'), 'chaine', 0, '', $conf->entity);

	if (!$error) {
		setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
	} else {
		setEventMessages($langs->trans("Error"), null, 'errors');
	}
}

/*
 * View
 */

$form = new Form($db);

$title = $langs->trans("KundenKarteSetup");
llxHeader('', $title);

// Subheader
$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
print load_fiche_titre($title, $linkback, 'title_setup');

// Configuration header
$head = kundenkarteAdminPrepareHead();
print dol_get_fiche_head($head, 'settings', $langs->trans('ModuleKundenKarteName'), -1, "fa-address-card");

print '<span class="opacitymedium">'.$langs->trans("KundenKarteSetupPage").'</span><br><br>';

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">';

// Header
print '<tr class="liste_titre">';
print '<td>'.$langs->trans("Parameter").'</td>';
print '<td>'.$langs->trans("Value").'</td>';
print '</tr>';

// Show Favorites Tab
print '<tr class="oddeven">';
print '<td>'.$langs->trans("ShowFavoritesTab").'</td>';
print '<td>';
print $form->selectyesno('KUNDENKARTE_SHOW_FAVORITES_TAB', getDolGlobalInt('KUNDENKARTE_SHOW_FAVORITES_TAB', 1), 1);
print '</td>';
print '</tr>';

// Show Anlagen Tab
print '<tr class="oddeven">';
print '<td>'.$langs->trans("ShowAnlagenTab").'</td>';
print '<td>';
print $form->selectyesno('KUNDENKARTE_SHOW_ANLAGEN_TAB', getDolGlobalInt('KUNDENKARTE_SHOW_ANLAGEN_TAB', 1), 1);
print '</td>';
print '</tr>';

// Default Order Type for Favorites
print '<tr class="oddeven">';
print '<td>'.$langs->trans("DefaultOrderType").'</td>';
print '<td>';
$orderTypes = array(
	0 => $langs->trans("OrderTypeOrder"),
	1 => $langs->trans("OrderTypeProposal"),
);
print $form->selectarray('KUNDENKARTE_DEFAULT_ORDER_TYPE', $orderTypes, getDolGlobalInt('KUNDENKARTE_DEFAULT_ORDER_TYPE', 0));
print '</td>';
print '</tr>';

// Default View Mode for Anlagen
print '<tr class="oddeven">';
print '<td>'.$langs->trans("DefaultViewMode").'</td>';
print '<td>';
$viewModes = array(
	'tree' => $langs->trans("ViewModeTree"),
	'graph' => $langs->trans("ViewModeGraph"),
);
print $form->selectarray('KUNDENKARTE_DEFAULT_VIEW', $viewModes, getDolGlobalString('KUNDENKARTE_DEFAULT_VIEW', 'tree'));
print '</td>';
print '</tr>';

print '</table>';

// Tree Display Settings
print '<br><br>';
print '<div class="titre inline-block">'.$langs->trans("TreeDisplaySettings").'</div>';
print '<br><br>';

print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td>'.$langs->trans("Parameter").'</td>';
print '<td>'.$langs->trans("Value").'</td>';
print '<td>'.$langs->trans("Preview").'</td>';
print '</tr>';

// Tree info display mode
$currentDisplay = getDolGlobalString('KUNDENKARTE_TREE_INFO_DISPLAY', 'badge');
print '<tr class="oddeven">';
print '<td>'.$langs->trans("TreeInfoDisplayMode").'</td>';
print '<td>';
print '<select name="KUNDENKARTE_TREE_INFO_DISPLAY" class="flat" id="tree_info_display">';
print '<option value="badge"'.($currentDisplay == 'badge' ? ' selected' : '').'>'.$langs->trans("DisplayAsBadge").'</option>';
print '<option value="parentheses"'.($currentDisplay == 'parentheses' ? ' selected' : '').'>'.$langs->trans("DisplayInParentheses").'</option>';
print '<option value="none"'.($currentDisplay == 'none' ? ' selected' : '').'>'.$langs->trans("DisplayNone").'</option>';
print '</select>';
print '</td>';
print '<td>';
print '<span id="preview_badge" class="kundenkarte-tree-badge-preview" style="display:'.($currentDisplay == 'badge' ? 'inline-flex' : 'none').';align-items:center;gap:4px;padding:2px 8px;background:linear-gradient(135deg,#2a4a5e 0%,#1e3a4a 100%);border:1px solid #3a6a8e;border-radius:12px;font-size:11px;color:#8cc4e8;"><i class="fa fa-map-marker"></i> Serverraum</span>';
print '<span id="preview_parentheses" style="display:'.($currentDisplay == 'parentheses' ? 'inline' : 'none').';color:#999;font-size:0.9em;">(Standort: Serverraum)</span>';
print '<span id="preview_none" style="display:'.($currentDisplay == 'none' ? 'inline' : 'none').';color:#999;font-style:italic;">'.$langs->trans("Hidden").'</span>';
print '</td>';
print '</tr>';

// Badge color
$currentColor = getDolGlobalString('KUNDENKARTE_TREE_BADGE_COLOR', '#2a4a5e');
print '<tr class="oddeven" id="row_badge_color"'.($currentDisplay != 'badge' ? ' style="display:none;"' : '').'>';
print '<td>'.$langs->trans("TreeBadgeColor").'</td>';
print '<td>';
print '<input type="color" name="KUNDENKARTE_TREE_BADGE_COLOR" id="badge_color" value="'.dol_escape_htmltag($currentColor).'" style="width:60px;height:30px;border:1px solid #ccc;border-radius:4px;cursor:pointer;">';
print ' <input type="text" id="badge_color_hex" value="'.dol_escape_htmltag($currentColor).'" style="width:80px;" class="flat" readonly>';
print '</td>';
print '<td class="opacitymedium small">'.$langs->trans("TreeBadgeColorHelp").'</td>';
print '</tr>';

print '</table>';

print '<script>
$(document).ready(function() {
	// Update preview and show/hide color row on display mode change
	$("#tree_info_display").on("change", function() {
		var mode = $(this).val();
		$("#preview_badge, #preview_parentheses, #preview_none").hide();
		if (mode === "badge") {
			$("#preview_badge").show();
			$("#row_badge_color").show();
		} else if (mode === "parentheses") {
			$("#preview_parentheses").show();
			$("#row_badge_color").hide();
		} else {
			$("#preview_none").show();
			$("#row_badge_color").hide();
		}
	});

	// Update color preview and hex input
	$("#badge_color").on("input", function() {
		var color = $(this).val();
		$("#badge_color_hex").val(color);
		// Update preview badge background
		var lighterColor = color;
		$("#preview_badge").css("background", "linear-gradient(135deg, " + color + " 0%, " + adjustColor(color, -20) + " 100%)");
	});

	function adjustColor(hex, percent) {
		var num = parseInt(hex.slice(1), 16);
		var r = Math.min(255, Math.max(0, (num >> 16) + percent));
		var g = Math.min(255, Math.max(0, ((num >> 8) & 0x00FF) + percent));
		var b = Math.min(255, Math.max(0, (num & 0x0000FF) + percent));
		return "#" + (0x1000000 + (r << 16) + (g << 8) + b).toString(16).slice(1);
	}
});
</script>';

// PDF Font Size Settings
print '<br><br>';
print '<div class="titre inline-block">'.$langs->trans("PDFFontSettings").'</div>';
print '<br><br>';

print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td>'.$langs->trans("Parameter").'</td>';
print '<td>'.$langs->trans("Value").'</td>';
print '<td class="opacitymedium">'.$langs->trans("Description").'</td>';
print '</tr>';

// Header font size
print '<tr class="oddeven">';
print '<td>'.$langs->trans("PDFFontHeader").'</td>';
print '<td>';
print '<select name="KUNDENKARTE_PDF_FONT_HEADER" class="flat">';
for ($i = 7; $i <= 14; $i++) {
	$sel = (getDolGlobalInt('KUNDENKARTE_PDF_FONT_HEADER', 9) == $i) ? ' selected' : '';
	print '<option value="'.$i.'"'.$sel.'>'.$i.' pt</option>';
}
print '</select>';
print '</td>';
print '<td class="opacitymedium small">'.$langs->trans("PDFFontHeaderHelp").'</td>';
print '</tr>';

// Content font size
print '<tr class="oddeven">';
print '<td>'.$langs->trans("PDFFontContent").'</td>';
print '<td>';
print '<select name="KUNDENKARTE_PDF_FONT_CONTENT" class="flat">';
for ($i = 6; $i <= 12; $i++) {
	$sel = (getDolGlobalInt('KUNDENKARTE_PDF_FONT_CONTENT', 7) == $i) ? ' selected' : '';
	print '<option value="'.$i.'"'.$sel.'>'.$i.' pt</option>';
}
print '</select>';
print '</td>';
print '<td class="opacitymedium small">'.$langs->trans("PDFFontContentHelp").'</td>';
print '</tr>';

// Field label font size
print '<tr class="oddeven">';
print '<td>'.$langs->trans("PDFFontFields").'</td>';
print '<td>';
print '<select name="KUNDENKARTE_PDF_FONT_FIELDS" class="flat">';
for ($i = 5; $i <= 10; $i++) {
	$sel = (getDolGlobalInt('KUNDENKARTE_PDF_FONT_FIELDS', 7) == $i) ? ' selected' : '';
	print '<option value="'.$i.'"'.$sel.'>'.$i.' pt</option>';
}
print '</select>';
print '</td>';
print '<td class="opacitymedium small">'.$langs->trans("PDFFontFieldsHelp").'</td>';
print '</tr>';

print '</table>';

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

print '</form>';

// PDF Template Section
print '<br><br>';
print '<div class="titre inline-block">'.$langs->trans("PDFExportTemplate").'</div>';
print '<br><br>';

$templateFile = $uploadDir.'/export_template.pdf';
$hasTemplate = file_exists($templateFile);

print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td colspan="2">'.$langs->trans("PDFTemplate").'</td>';
print '</tr>';

print '<tr class="oddeven">';
print '<td style="width:50%">'.$langs->trans("CurrentTemplate").'</td>';
print '<td>';
if ($hasTemplate) {
	print '<span class="badge badge-success" style="padding: 5px 10px;">';
	print '<i class="fas fa-file-pdf"></i> export_template.pdf';
	print '</span>';
	print ' <span class="opacitymedium">('.dol_print_size(filesize($templateFile)).')</span>';
	print '<br><br>';
	print '<a class="button buttongen" href="'.$_SERVER['PHP_SELF'].'?action=delete_template&token='.newToken().'" onclick="return confirm(\''.$langs->trans('ConfirmDeleteTemplate').'\');">';
	print '<i class="fas fa-trash"></i> '.$langs->trans("DeleteTemplate");
	print '</a>';
} else {
	print '<span class="opacitymedium">'.$langs->trans("NoTemplateUploaded").'</span>';
}
print '</td>';
print '</tr>';

print '<tr class="oddeven">';
print '<td>'.$langs->trans("UploadNewTemplate").'</td>';
print '<td>';
print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="upload_template">';
print '<input type="file" name="pdf_template" accept=".pdf" class="flat" style="max-width:300px;">';
print ' <input type="submit" class="button buttongen smallpaddingimp" value="'.$langs->trans("Upload").'">';
print '</form>';
print '<br><span class="opacitymedium small">'.$langs->trans("PDFTemplateHelp").'</span>';
print '</td>';
print '</tr>';

print '</table>';

// Info section
print '<br>';
print '<div class="info">';
print '<strong>'.$langs->trans("ConfigurationHelp").':</strong><br>';
print '&bull; '.$langs->trans("ConfigHelpSystems").'<br>';
print '&bull; '.$langs->trans("ConfigHelpTypes").'<br>';
print '</div>';

print dol_get_fiche_end();

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