<!DOCTYPE html>
<?php
session_start();
global $settings;
$root_dir = $_SERVER['DOCUMENT_ROOT'];
include "{$root_dir}/includes/database.php";
include "{$root_dir}/includes/lang_helper.php";

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
if (isset($_SESSION['login_error'])) {
    echo "<div class='error'>" . $_SESSION['login_error'] . "</div>";
    unset($_SESSION['login_error']); // Clear the error message after displaying it
}

// Initialize variables
$productid = "";
$selectedProduct = "";
$selectedMaat = "";
$selectedFilament = "";
$amount = 1;
$filamentPrice = 0;
$omschrijving = "";
$is_admin = 0;
$userIsSpecial = false;

// Get products & filaments from the database (we use this for the dropdown)
$settings = getAllGeneralSettings();
// Only set defaultlanguage if 'lang' session is not set
if (!isset($_SESSION['lang'])) {
    $_SESSION['defaultlanguage'] = $settings['language'];
} else {
    $_SESSION['defaultlanguage'] = $_SESSION['lang']; // Use the user-selected language
}

$defaultLang = $_SESSION['defaultlanguage']; // Get language for JS

$filamenten = getFilamenten();
$productall = getProductAll();
// Group products by name
$groupedProducts = [];

foreach ($productall as $product) {
		$groupedProducts[$product['naam']][] = $product;
}

// Fetch customer info from the database (if logged in)
$customerInfo = [];
if (isset($_SESSION['user_id'])) {
    $customerInfo = getCustomerInfo($_SESSION['user_id']);
	$is_admin = isAdmin($_SESSION['user_id']);
	$userId = $_SESSION['user_id'];
    $userIsSpecial = isUserSpecial($userId);
	$temppass_active = isGetTemp($userId);
}
echo "<script>let temppass_active = " . json_encode($temppass_active) . ";</script>";
echo "<script>let userIsSpecial = " . json_encode($userIsSpecial) . ";</script>";
// Handle selection change
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get selected product, filament, and amount
	$productid = getProductenByID($_POST['maat']);
	$selectedProduct = array_column($productid, 'naam');	
	$selectedMaat = array_column($productid, 'maat');
    $selectedFilament = $_POST['filament'];
    $amount = $_POST['amount'];
    // Get filament price
    $filamentPrice = getFilamentPrice($selectedFilament);
    // Get the omschrijving for the extracted size
    if ($productid) {
        $omschrijving = getOmschrijvingBySize($productid);
    }
}
$sizes = getMaten();
$materials = getMaterials();
$prodtypes = getTypes();
echo "<script>var allMaterials = " . json_encode($materials) . ";</script>";

?>

<html lang="<?= htmlspecialchars($settings['language'], ENT_QUOTES, 'UTF-8') ?>">
<head>
    <title><?php echo trans('webTitle'); ?></title>
	<link rel="shortcut icon" type="image/png" href="images/favicon.png"/>
    <link rel="stylesheet" href="css/min-style.css">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.4.0/css/flag-icon.min.css">
	<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@500;700&family=Rubik:wght@400;500&display=swap" rel="stylesheet">
	
    <meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
		<meta name="description" content="3dPrint, Print Service">
		<meta name="keywords" content="3D, Printen, Print Service, Bambulabs, 3D Design">
		<meta name="robots" content="index, follow">
		<meta name="googlebot" content="noodp">
		<meta name="revisit-after" content="1 month">
		<meta name="language" content="English">
		<meta name="reply-to" content="please@helpmewithit.nl">
		<meta http-equiv="naam" content="Joram Dillen">
		<meta http-equiv="content-language" content="<?= htmlspecialchars($settings['language'], ENT_QUOTES, 'UTF-8') ?>">
		<meta http-equiv="Page-Enter" content="blendTrans(Duration=0.2)">
		<meta http-equiv="Page-Exit" content="blendTrans(Duration=0.2)">
		<meta name="copyright" content="helpmewithit.nl">	
		<meta name="web_author" content="helpmewithit.nl">	
	<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<script>
		const isLoggedIn = <?php echo json_encode(isset($_SESSION['user_id'])); ?>;
		var lang = <?php echo json_encode($lang); ?>;
		var trans_SelecteerMaat = "<?php echo trans('Selecteer_Maat_label'); ?>";
		var trans_NietLeverbaar = "<?php echo trans('niet_leverbaar'); ?>";
		var defaultLanguage = "<?php echo $defaultLang; ?>";
	</script>
	<script src="js/header_scripts.js"></script>		
    <script>
        function showDetails(productId) {
            document.querySelectorAll('.product-details').forEach(el => el.style.display = 'none');
            document.getElementById('details-' + productId).style.display = 'block';
        }
    </script>
</head>
<body>


<div id="confirmationModal" class="modal_pop modal_pop_mobpad" style="display: none;">
  <div class="modal-content_stat stretch_wide_mob" style="overflow-y: hidden;">
		<br>
		<p><center><?php echo trans('sure_change'); ?><center></p>
		<button class="confirmButton" id="confirmRemoveButton"><?php echo trans('ja'); ?></button>
		<button class="cancelButton" id="cancelRemoveButton"><?php echo trans('cancel'); ?></button>
  </div>

</div>

    <div class="language-switcher">
        <button id="lang-btn"><i class="fas fa-globe" style="color: #116db4;"></i></button>
        <div id="lang-menu" class="dropdown hidden">
		<button class="lang-option" data-lang="NL">
			<span class="flag-icon flag-icon-nl"></span> NL
		</button>
		<button class="lang-option" data-lang="ENG">
			<span class="flag-icon flag-icon-gb"></span> ENG
		</button>

        </div>
    </div>

    <div id="notification" class="notification-banner"></div>

<div class="content">
	<a href="https://print3d.helpmewithit.nl" title="print3d.helpmewithit.nl"><img src="images/styles/HMWIT_logo_2.png" alt="HMWIT weblogo" class="responsive-img"></a>
	<h1 style="display:none;"><?php echo trans('hiddenh1'); ?></h1>
	<h2 style="display:none;"><?php echo trans('hiddenh2'); ?></h2>
	<nav>	
		<a href="index.php" id="orderform" title="<?php echo trans('formTitle'); ?>" class="styled-link"><?php echo trans('formTitle'); ?></a>

		<button id="cartBtn" title="<?php echo trans('cart'); ?>" class="styled-link"><i class="fa-solid fa-cart-shopping"></i></button>
		<?php if(isset($_SESSION['user_id'])): ?>
			<button id="stlaanvraagBtn" title="<?php echo trans('EigenFile'); ?>" class="styled-link"><i class="fa-solid fa-upload"></i></button>
			<a href="logout.php" id="logoutlink" title="<?php echo trans('Uitloggen'); ?>" class="styled-link"><i class="fa-solid fa-right-from-bracket"></i></a>
		<?php else: ?>
			<button id="loginBtn" title="<?php echo trans('Login'); ?>" class="styled-link login-button"><i class="fa-solid fa-right-to-bracket"></i></button>
		<?php endif; ?>
			<?php if($is_admin == 1): ?>
				<a href="admin/" id="adminlink" class="styled-link"><?php echo trans('admin'); ?></a>
			<?php else: ?>	
				<button id="overviewBtn" title="<?php echo trans('Over'); ?>" class="styled-link"><i class="fa-solid fa-circle-info"></i></button>
			<?php endif; ?>

			<div class="nav-right">	
			<div class="toggle-buttons">
				<button id="gridViewBtn" class="active">
					<i class="fas fa-th"></i>
				</button>
				<button id="listViewBtn">
					<i class="fas fa-list"></i>
				</button>
			</div>		
				<div class="select-container">
					<select id="sizeFilter">
						<option style="color:#116db4;font-weight: bold;" value="all"><?php echo trans('Selecteer_maat_label'); ?></option>
						<?php foreach ($sizes as $size): ?>
							<option value="<?php echo htmlspecialchars($size['naam']); ?>">
								<?php echo htmlspecialchars($size['naam']); ?>
							</option>
						<?php endforeach; ?>
					</select>
				</div>
				<div class="select-container">
					<?php $typeCount = count($prodtypes); ?>
					<select id="typeFilter">
						
						<?php if ($typeCount > 1): ?>
							<!-- Show ALL only when there is more than one type -->
							<option style="color:#116db4;font-weight: bold;" value="all">
								<?php echo trans('Selecteer_maat_label'); ?>
							</option>
						<?php endif; ?>

						<?php foreach ($prodtypes as $type): ?>
							<option
								value="<?php echo htmlspecialchars($type['ProdType']); ?>"
								<?php echo ($type['ProdType'] === 'Original') ? 'selected' : ''; ?>
							>
								<?php echo htmlspecialchars($type['ProdType']); ?>
							</option>
						<?php endforeach; ?>

					</select>
				</div>				
				<div class="search-container">
                    <i class="fas fa-search" style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: #116db4;"></i>
					<input type="text" id="searchBox" placeholder=<?php echo trans('search'); ?> >
					<span id="clearSearch"><i class="fas fa-times"></i>	</span>
				</div>
			</div>
	</nav>

	<div class="main-container">
		<!-- Product Selection Section -->
		<?php
		$language = $_SESSION['defaultlanguage'] ?? 'NL'; // Assuming language is stored in session
		$nameKey = $language === 'ENG' ? 'naam_eng' : 'naam';
		$descKey = $language === 'ENG' ? 'omschrijving_eng' : 'omschrijving';
		$sizeOrder = [
			'Extra Small' => 0,
			'Small' => 1,
			'Medium' => 2,
			'Large' => 3,
			'Extra Large' => 4
		];
			$originalCount = 0;
			foreach ($groupedProducts as $name => $group) {
				if ($group[0]['ProdType'] === 'Original') {
					$originalCount++;
				}
			}
			$printableCount = 0;
			foreach ($groupedProducts as $name => $group) {
				if ($group[0]['ProdType'] === 'Printable') {
					$printableCount++;
				}
			}	
		?>

		<div class="container" id="originalContainer">
		<h3 class="white"><?php echo trans('original'); ?></h3>
		
		<!-- Dit moet gefilterd worden met ProdType Original flag -->
			<div class="product-grid" id="productGrid">
			
				<?php foreach ($groupedProducts as $name => $group): 
				    if ($group[0]['ProdType'] !== 'Original') {
						continue;   // skip this product
					}
					$sizes = array_column($group, 'maat');

					// Find the smallest size based on $sizeOrder, without changing the order
					$minIndex = null;
					$minValue = PHP_INT_MAX;

					foreach ($group as $i => $item) {
						$maat = $item['maat'];
						if (isset($sizeOrder[$maat]) && $sizeOrder[$maat] < $minValue) {
							$minValue = $sizeOrder[$maat];
							$minIndex = $i + 1; // 1-based
						}
					}

					// Fallback in case nothing matched
					if ($minIndex === null) {
						$minIndex = 1;
					}

					// JSON for all available sizes (as-is, in original order)
					$sizesJson = htmlspecialchars(json_encode($sizes), ENT_QUOTES, 'UTF-8');
				?>
				<div class="product-card detailsButtons" 
					<?php foreach ($group as $index => $item): ?>
						data-id-<?php echo $index; ?>="<?php echo $item['id']; ?>" 
						data-name-<?php echo $index; ?>="<?php echo htmlspecialchars($item[$nameKey]); ?>"
						data-nlname-<?php echo $index; ?>="<?php echo htmlspecialchars($item['naam']); ?>" 						
						data-description-<?php echo $index; ?>="<?php echo htmlspecialchars($item[$descKey]); ?>" 
						data-image-<?php echo $index; ?>="<?php echo $item['afbeelding']; ?>"
						data-image_sec-<?php echo $index; ?>="<?php echo $item['afbeelding_second']; ?>"
						data-custom-<?php echo $index; ?>="<?php echo $item['custom']; ?>"
						data-multicolor-<?php echo $index; ?>="<?php echo $item['multicolor']; ?>"
						data-size="<?php echo $minIndex; ?>"
						data-mature-<?php echo $index; ?>="<?php echo $item['mature']; ?>"
						data-gallery-<?php echo $index; ?>="<?php echo $item['gallery']; ?>"	
					<?php endforeach; ?>
				>
				<img class="product-image" src="<?php if($group[0]['mature'] == 0){ echo $group[0]['afbeelding']; } else{ './images/styles/MatureContent.png'; } ?>" alt="<?php if($group[0]['mature'] == 0){ echo $group[0][$nameKey];}else{ echo $mature;} ?>">
					<div class="product-info">
						<h3><?php echo $group[0][$nameKey]; ?></h3>
						<h5 class="product-description"><?php echo $group[0][$descKey]; ?></h5>
					</div>
					<input type="hidden" class="available-sizes" value="<?php echo $sizesJson; ?>">
				</div>
				
				<?php endforeach; ?>

				<!-- "Nothing Found" Card -->
				<div class="no-product-card">
					<div id="noResultsCard" class="product-card no-results" style="display: none;">
							<img src="images/styles/not_found.png" alt="<?php echo trans('no_search_result'); ?>">
							<div class="product-info">
								<h3></h3>
								<h5></h5>
							</div>
					</div>
				</div>
			</div>
			<?php if ($originalCount > 8): ?>
			<br>
			<center>
				<button id="loadMoreBtnOriginal" class="styled-link" style="width:100%;">
					<?php echo trans('more_results'); ?>
				</button>
			</center>
			<?php endif; ?>			
		</div>

		<div class="container" id="printableContainer">
			<h3 class="white"><?php echo trans('printables'); ?></h3>
			    <div class="product-grid" id="printableGrid">
					<?php foreach ($groupedProducts as $name => $group): 
						if ($group[0]['ProdType'] !== 'Printable') {
							continue;   // skip this product
						}
						$sizes = array_column($group, 'maat');

						// Find the smallest size based on $sizeOrder, without changing the order
						$minIndex = null;
						$minValue = PHP_INT_MAX;

						foreach ($group as $i => $item) {
							$maat = $item['maat'];
							if (isset($sizeOrder[$maat]) && $sizeOrder[$maat] < $minValue) {
								$minValue = $sizeOrder[$maat];
								$minIndex = $i + 1; // 1-based
							}
						}

						// Fallback in case nothing matched
						if ($minIndex === null) {
							$minIndex = 1;
						}

						// JSON for all available sizes (as-is, in original order)
						$sizesJson = htmlspecialchars(json_encode($sizes), ENT_QUOTES, 'UTF-8');
					?>
					<div class="product-card detailsButtons" 
						<?php foreach ($group as $index => $item): ?>
							data-id-<?php echo $index; ?>="<?php echo $item['id']; ?>" 
							data-name-<?php echo $index; ?>="<?php echo htmlspecialchars($item[$nameKey]); ?>"
							data-nlname-<?php echo $index; ?>="<?php echo htmlspecialchars($item['naam']); ?>" 						
							data-description-<?php echo $index; ?>="<?php echo htmlspecialchars($item[$descKey]); ?>" 
							data-image-<?php echo $index; ?>="<?php echo $item['afbeelding']; ?>"
							data-image_sec-<?php echo $index; ?>="<?php echo $item['afbeelding_second']; ?>"
							data-custom-<?php echo $index; ?>="<?php echo $item['custom']; ?>"
							data-multicolor-<?php echo $index; ?>="<?php echo $item['multicolor']; ?>"
							data-size="<?php echo $minIndex; ?>"
							data-mature-<?php echo $index; ?>="<?php echo $item['mature']; ?>"
							data-gallery-<?php echo $index; ?>="<?php echo $item['gallery']; ?>"								
						<?php endforeach; ?>
					>
						<img class="product-image" src="<?php if($group[0]['mature'] == 0){ echo $group[0]['afbeelding']; } else{ './images/styles/MatureContent.png'; } ?>" alt="<?php if($group[0]['mature'] == 0){ echo $group[0][$nameKey];}else{ echo $mature;} ?>">
						<div class="product-info">
							<h3><?php echo $group[0][$nameKey]; ?></h3>
							<h5 class="product-description"><?php echo $group[0][$descKey]; ?></h5>
						</div>
						<input type="hidden" class="available-sizes" value="<?php echo $sizesJson; ?>">
					</div>
					
					<?php endforeach; ?>

					<!-- "Nothing Found" Card -->
					<div class="no-product-card">
						<div id="noResultsCard" class="product-card no-results" style="display: none;">
								<img src="images/styles/not_found.png" alt="<?php echo trans('no_search_result'); ?>">
								<div class="product-info">
									<h3></h3>
									<h5></h5>
								</div>
						</div>
					</div>
				</div>
			<?php if ($printableCount > 8): ?>
			<br>
			<center>
				<button id="loadMoreBtnPrintable" class="styled-link" style="width:100%;">
					<?php echo trans('more_results'); ?>
				</button>
			</center>
			<?php endif; ?>	
		</div>

			<!-- Customer Information Section -->
			<div class="customer-info-container">
				<h3><?php echo trans('Klantinfo'); ?></h3>
						<?php if($is_admin == 1): ?>
							<a href="admin/" class="styled-link" id="adminlinkalt"><?php echo trans('admin'); ?></a>
						<?php endif; ?><br>
				<?php 
				if ($customerInfo): ?>
					<p>
					<strong><?php echo trans('Klantnummer'); ?></strong> <?= htmlspecialchars($customerInfo['klantnummer']) ?><br>			
					<strong><?php echo trans('Bedrijfsnaam'); ?></strong> <?= htmlspecialchars($customerInfo['naam']) ?><br>
					<strong><?php echo trans('BedrijfswebAdres'); ?></strong> <?= htmlspecialchars($customerInfo['adres']) ?><br>
					<strong><?php echo trans('Email'); ?></strong> <?= htmlspecialchars($customerInfo['email']) ?>
					</p>
					
					<p>
					<strong><?php echo trans('BedrijfsPostcode'); ?></strong> <?= htmlspecialchars($customerInfo['postcode']) ?><br>
					<strong><?php echo trans('BedrijfsHuisnummer'); ?></strong> <?= htmlspecialchars($customerInfo['huisnummer']) ?><br>					
					<strong><?php echo trans('BedrijfsPlaats'); ?></strong> <?= htmlspecialchars($customerInfo['plaats']) ?><br>
					<strong><?php echo trans('PayTerm'); ?></strong> <?= htmlspecialchars($customerInfo['NET']) ?> <?php echo trans('days'); ?>			
					</p>
					<?php if($userIsSpecial == 1): ?>
					<p>
					<strong><?php echo trans('specialpricing_active'); ?></strong>
					</p>
					<?php endif; ?>
					<br>
					<button class="styled-link add-button" id="changeBtn"><?php echo trans('Wijzig_Info'); ?></button><br>
					<button class="styled-link add-button" id="orderviewBtn"><?php echo trans('Orders'); ?></button><br>
					<button class="styled-link add-button" id="stlviewerBtn"><?php echo trans('stlrequests'); ?></button><br>
					
			
				<?php else: ?>
					<p><?php echo trans('Geen_informatie_beschikbaar'); ?><br><br> <?php echo trans('Login_informatie_zichtbaar'); ?></p><br>
					<button class="styled-link add-button" id="addUserBtn"><?php echo trans('word_klant'); ?></button><br>
					
				<?php endif; ?>
				<br>

			</div>
					
	</div>
	<!-- cart (Popup) -->		
    <div id="cartModal" class="modal">
		<div class="modal-content_details stretch animate-from-click" style="overflow-y: scroll;">	
			<span class="cartclose">&times;</span>
			<table id="productTable">		
				<thead>
					<tr><th colspan='5'><h3><?php echo trans('Winkelmandje'); ?></h3></th></tr>	
					<tr>		
						<th><?php echo trans('Aantal'); ?></th>
						<th><?php echo trans('Omschrijving'); ?></th>
						<th><?php echo trans('Prijs_per_stuk'); ?></th>
						<th><?php echo trans('Totaal'); ?></th>
						<th><?php echo trans('Actie'); ?></th>
					</tr>
				</thead>
				<tbody>
					<!-- Dynamic rows will be added here -->
				</tbody>
				
			<tfoot id="productsub">
				<tr style="border: none;">
					<td colspan="2" style="border: none;"></td>
					<td style="border: none;"></td>
					<td id="spacer" style="border: none;"></td>
					<td style="border: none;"></td>
				</tr>
				<tr>
					<td style="border: 0px;" colspan="2"></td>
					<td><?php echo trans('subtotal'); ?></td>
					<td id="total_excl_btw">€0.00</td>
					<td style="border: 0px;" ></td>
				</tr>
			</tfoot>				
			</table>
			<a href="cart.php" id="cartform" class="styled-link cart"><?php echo trans('Bestel'); ?></a>
		</div>
	</div>
    <!-- Over (Popup) -->
    <div id="overModal" class="modal">
        <div class="modal-content_details animate-from-click" style="overflow-y: scroll;">
            <span class="overclose">&times;</span>
            <h2><?php echo trans('Over'); ?></h2>
            <form id="overForm">
			<p><?php echo trans('over_content1'); ?></p>	
			<p><?php echo trans('over_content2'); ?></p>	
			<p><?php echo trans('over_content3'); ?></p>	
			<p><?php echo trans('over_content4'); ?> <?php echo trans('over_content4_4'); ?></p>
			<p><?php echo trans('over_content4_44'); ?></p>
			<p><?php echo trans('over_content5'); ?> 
			<?php echo trans('over_content6'); ?> <?= htmlspecialchars($settings['tax'], ENT_QUOTES, 'UTF-8') ?> <?php echo trans('over_content6_6'); ?></p>	
			<hr>
			<?php echo nl2br(str_replace('\\n', "\n", trans('material_use'))); ?>
			<hr>
			<p><?php echo trans('over_content7'); ?> <a href="mailto:<?php echo trans('MailAdress'); ?>"><?php echo trans('MailAdress'); ?></a> <?php echo trans('over_content7_1'); ?></p>			
            </form>
        </div>
    </div>
		
    <!-- Login Modal (Popup) -->
    <div id="loginModal" class="modal">
        <div class="modal-content animate-from-click" style="overflow-y: hidden;">
            <span class="close">&times;</span>
            <h2><?php echo trans('Login_form'); ?></h2>
            <form id="loginForm">
                <label for="username"><?php echo trans('Klantnummer_form'); ?></label>
                <input type="text" id="username" class="right" name="username" required autocomplete="username" required><br><br>
                <label for="password"><?php echo trans('Wachtwoord_form'); ?></label>
                <input type="password" id="password" class="right" name="password" autocomplete="current-password" required><br><br><br>
               	<button type="submit" class="styled-button stretch_wide"><?php echo trans('Login_form'); ?></button><br>
            </form><br><button class="styled-button stretch_wide" id="changepassBtn"><?php echo trans('forgot_password'); ?></button><br>
        </div>
    </div>
	<!-- Update user (Popup) -->
    <div id="editModal" class="modal">
        <div class="modal-content stretch animate-from-click" style="overflow-y: scroll;">
            <span class="updateclose">&times;</span>
            <h2><?php echo trans('Wijzig_Info_form'); ?></h2>
            <form id="editForm">
                <p><?php echo trans('Klantnummer_form'); ?><br>
				<input type="hidden" name="klantnummer" id="klantnummer" value="<?= htmlspecialchars($customerInfo['klantnummer']) ?>">
                <b><?= htmlspecialchars($customerInfo['klantnummer']) ?></b><br></p>
                
				<p><label for="naam"><?php echo trans('Bedrijfsnaam_form'); ?></label>
                <input type="text" id="naam" class="right" name="naam" value="<?= htmlspecialchars($customerInfo['naam']) ?>" required></p>
                
				<p><label for="adres"><?php echo trans('BedrijfswebAdres_form'); ?></label>
                <input type="text" id="adres" class="right" name="adres" value="<?= htmlspecialchars($customerInfo['adres']) ?>" required></p>
				
                <p><label for="email"><?php echo trans('BedrijfsEmail_form'); ?></label>
                <input type="text" id="email" class="right" name="email" value="<?= htmlspecialchars($customerInfo['email']) ?>" autocomplete="email" required></p>
                
				<p><label for="postcode"><?php echo trans('BedrijfsPostcode_form'); ?></label>
                <input type="text" id="postcode" class="right" name="postcode" value="<?= htmlspecialchars($customerInfo['postcode']) ?>" required></p>
				
  				<p><label for="huisnummer"><?php echo trans('BedrijfsHuisnummer_form'); ?></label>
                <input type="text" id="huisnummer" class="right" name="huisnummer" value="<?= htmlspecialchars($customerInfo['huisnummer']) ?>" required></p>        
				
				<p><label for="plaats"><?php echo trans('BedrijfsPlaats_form'); ?></label>
                <input type="text" id="plaats" class="right" name="plaats" value="<?= htmlspecialchars($customerInfo['plaats']) ?>" required></p><br>					
                
				<p><label for="wachtwoord"><?php echo trans('Wachtwoord_form'); ?></label>
                <input type="password" id="wachtwoord" class="right" name="wachtwoord" autocomplete="current-password"><br><br>
				<label for="wachtwoord_veri"><?php echo trans('Wachtwoord_nog_een_keer_form'); ?></label>
                <input type="password" id="wachtwoord_veri" class="right" name="wachtwoord_veri" autocomplete="current-password"></p><br><br>
				
                <button type="submit" id="updateButton" class="styled-button stretch_wide"><?php echo trans('Update_form'); ?></button>
                <div class="spaceret"><br><br><br></div>
            </form>
        </div>
    </div>

	<!-- change password (Popup) -->
    <div id="changeModal" class="modal">
        <div class="modal-content animate-from-click" style="overflow-y: hidden;">
            <span class="changeclose">&times;</span>
            <h2><?php echo trans('change_pass'); ?></h2>
            <form id="changeForm">
            	
                <p><label for="changepass_email"><?php echo trans('BedrijfsEmail_form'); ?></label>
                <input type="text" id="changepass_email" class="right buff" name="changepass_email" value="" autocomplete="email" required></p>
                <br><br><br><br><br>
               					
                <button type="submit" id="changeUserButton" class="styled-button stretch_wide"><?php echo trans('Indienen'); ?></button><br><br>	
				<button id="backtologin" type="button" class="styled-button stretch_wide"><?php echo trans('Login_anyway_form'); ?></button>				
                <br>
            </form>
        </div>
    </div>             
                
	<!-- Add user (Popup) -->
    <div id="addModal" class="modal">
        <div class="modal-content stretch animate-from-click" style="overflow-y: scroll;">
            <span class="addCustclose">&times;</span>
            <h2><?php echo trans('word_klant'); ?></h2>
            <form id="addForm">
                
				<p><label for="add_naam"><?php echo trans('Bedrijfsnaam_form'); ?></label>
                <input type="text" id="add_naam" class="right" name="add_naam" value="" required></p>
                
				<p><label for="add_adres"><?php echo trans('BedrijfswebAdres_form'); ?></label>
                <input type="text" id="add_adres" class="right" name="add_adres" value="" required></p>
				
                <p><label for="add_email"><?php echo trans('BedrijfsEmail_form'); ?></label>
                <input type="text" id="add_email" class="right" name="add_email" value="" autocomplete="email" required></p>
                
				<p><label for="add_postcode"><?php echo trans('BedrijfsPostcode_form'); ?></label>
                <input type="text" id="add_postcode" class="right" name="add_postcode" value="" required></p>
				
 				<p><label for="add_huisnummer"><?php echo trans('BedrijfsHuisnummer_form'); ?></label>
                <input type="text" id="add_huisnummer" class="right" name="add_huisnummer" value="" required></p>
				
				<p><label for="add_plaats"><?php echo trans('BedrijfsPlaats_form'); ?></label>
                <input type="text" id="add_plaats" class="right" name="add_plaats" value="" required></p><br>					
                
				<p><label for="add_wachtwoord"><?php echo trans('Wachtwoord_form'); ?></label>
                <input type="password" id="add_wachtwoord" class="right" name="add_wachtwoord" autocomplete="current-password" required><br><br>
				<label for="add_wachtwoord_veri"><?php echo trans('Wachtwoord_nog_een_keer_form'); ?></label>
                <input type="password" id="add_wachtwoord_veri" class="right" name="add_wachtwoord_veri" autocomplete="current-password" required></p><br><br>
				
                <button type="submit" id="addUserButton" class="styled-button stretch_wide"><?php echo trans('Aanvragen'); ?></button>
                <div class="spaceret"><br><br><br></div>
            </form>
        </div>
    </div>
	

    <!-- Modal details (Popup) -->
    <div id="detailsModal" class="modal">
		<div class="modal-content_details spacer animate-from-click" style="overflow-y: scroll;">
			<div id="galleryOverlay" class="gallery-overlay">
				<span id="galleryClose">&times;</span>
				<img id="galleryLarge">
			</div>			
			<span class="detailsclose">&times;</span>
				<button id="copyProductURL" aria-label="Copy product link" title="<?php echo trans('copy_item_url'); ?>">
					<i class="fas fa-link"></i>
				</button>
			<h2><?php echo trans('Product_details'); ?></h2>
			<div class="product-details">
			
			<div class="imgblock">

				<div class="imgmain">

					<div class="imgwindow">
						<img id="modalImage" src="" class="preview" alt="<?php echo trans('ProductImg_form'); ?>" />
						<img id="modalImage_sec" src="" class="preview" alt="<?php echo trans('ProductImg_form'); ?>" />
					</div>

					<small><?php echo trans('afwijken'); ?>*</small>

				</div>

				<!-- GALLERY THUMBNAILS -->
				<div id="productGallery" class="product-gallery"></div>

			</div>
				
					<div class="text-details">
						<h3 id="modalTitle"></h3>
						<p id="modalDescription"></p>
						<!-- Maat Buttons -->
						<div class="maat-options">
							<label><?php echo trans('Selecteer_Maat'); ?></label>
							<div class="maat-buttons"><!-- Buttons will be added here --></div>
						</div>
						<input type="hidden" id="maat"> <!-- Hidden input for selected size -->
											
						<!-- Material Buttons -->
						<div class="material-options">

								<div class="material-table">			
									<div class="material-row material-header"><?php echo trans('material_info_header'); ?></div>
										<div class="material-buttons"><!-- Buttons will be added here --></div>
									<div class="material-row material-content" data-material="PLA">
										<?php echo trans('material_infoPLA'); ?>
									</div>	

									<div class="material-row material-content" data-material="ABS">
										<?php echo trans('material_infoABS'); ?>
									</div>	

									<div class="material-row material-content" data-material="TPU">
										<?php echo trans('material_infoTPU'); ?>
									</div>	
								</div>

						</div>
						<input type="hidden" id="material"> <!-- Hidden input for selected material -->
						
						<input type="hidden" id="prodid">
					<!-- Filament color selector1 -->
						<label id="color-label" for="filament"><?php echo trans('Selecteer_Kleur'); ?></label>
							<div class="color-picker" id="color-picker">
								<div class="color-swatch none-swatch active"
									 data-color=""
									 title="<?php echo trans('no_color'); ?>"
									 onclick="selectColor('')">
								</div>	
								<?php foreach ($filamenten as $filament): ?>
									<!-- Only show available colors -->
									<?php if ($filament['leverbaar'] != 0): ?>
										<div class="color-swatch" 
										     data-color="<?= htmlspecialchars(explode(' - ', $filament['naam'])[0]); ?>"
											 style="background-color: <?= htmlspecialchars($filament['kleur']); ?>" 
											 title="<?= htmlspecialchars(preg_replace('/\s*-\s*[^-]*$/', '', $filament['naam'])); ?>" 
											 onclick="selectColor('<?= htmlspecialchars($filament['naam']); ?>')">			 
										</div>
									<?php endif; ?>
								<?php endforeach; ?>
							</div>
							<!-- Hidden Dropdown for Form Submission -->
								<select id="filament" name="filament" class="dropdown_kleur" onchange="updateSelection()" style="display:none;">
									<option style="background:#f9f9f9;color:#116db4;" value="" selected>
										<?php echo trans('Selecteer_Kleur_label'); ?>
									</option>

									<?php foreach ($filamenten as $filament): ?>
										<option 
											<?= $filament['leverbaar'] == 0 ? 'hidden' : '' ?>
											value="<?= htmlspecialchars($filament['naam']); ?>"
											data-price="<?= $filament['prijs']; ?>"
											data-colorpla="<?= $filament['ColorPLA']; ?>"
											data-colorabs="<?= $filament['ColorABS']; ?>"
											data-colortpu="<?= $filament['ColorTPU']; ?>"
										>
											<?= htmlspecialchars(explode(' - ', $filament['naam'])[0]); ?>
										</option>
									<?php endforeach; ?>
								</select>
							<br>
							
							
					<!-- Filament color selector2 -->
						<label id="color-label-2" for="filament2"><div id="multitext"><?php echo trans('multicolor_label'); ?></div>
						  <span class="tooltipcolor"><i style="color:#116db4;" class="fa fa-info-circle"></i>
							<span class="tooltiptext"><?php echo nl2br(str_replace('\\n', "\n", trans('color_tool'))); ?><?= htmlspecialchars($settings['custom_color'], ENT_QUOTES, 'UTF-8') ?> <?php echo nl2br(str_replace('\\n', "\n", trans('color_tool2'))); ?></span>
						  </span>										
						</label>
						<!-- Swatches for filament2 (instead of a dropdown) -->
						<div class="color-picker" id="color-picker2">
								<div class="color-swatch none-swatch active"
									 data-color=""
									 title="<?php echo trans('no_color'); ?>"
									 onclick="selectColor_sec('')">
								</div>						
							<?php foreach ($filamenten as $filament): ?>
								<?php if ($filament['leverbaar'] != 0): ?>
									<div class="color-swatch" 
										 data-color="<?= htmlspecialchars(explode(' - ', $filament['naam'])[0]); ?>"
										 style="background-color: <?= htmlspecialchars($filament['kleur']); ?>" 
										 title="<?= htmlspecialchars(preg_replace('/\s*-\s*[^-]*$/', '', $filament['naam'])); ?>" 
										 onclick="selectColor_sec('<?= htmlspecialchars($filament['naam']); ?>')">
									</div>
								<?php endif; ?>
							<?php endforeach; ?>
						</div>
						<!-- Hidden Dropdown for filament2 (still exists for form submission, but is hidden) -->
							<select id="filament2" name="filament2" class="dropdown_kleur" onchange="updateSelection()" style="display:none;" disabled>
								<option style="background:#f9f9f9;color:#116db4;" value="" selected>
									<?php echo trans('Selecteer_Kleur_label'); ?>
								</option>

								<?php foreach ($filamenten as $filament): ?>
									<option 
										<?= $filament['leverbaar'] == 0 ? 'hidden' : '' ?>
										value="<?= htmlspecialchars($filament['naam']); ?>"
										data-price="<?= $filament['prijs']; ?>"
										data-colorpla="<?= $filament['ColorPLA']; ?>"
										data-colorabs="<?= $filament['ColorABS']; ?>"
										data-colortpu="<?= $filament['ColorTPU']; ?>"
									>
										<?= htmlspecialchars(explode(' - ', $filament['naam'])[0]); ?>
									</option>
								<?php endforeach; ?>
							</select>

						<br>
						<!-- Custom text input -->
						<label for="custom"><?php echo trans('custom_label'); ?>
						  <span class="tooltip"><i style="color:#116db4;" class="fa fa-info-circle"></i>
							<span class="tooltiptext"><?php echo nl2br(str_replace('\\n', "\n", trans('custom_tool'))); ?><?= htmlspecialchars($settings['custom_text'], ENT_QUOTES, 'UTF-8') ?> <?php echo nl2br(str_replace('\\n', "\n", trans('custom_tool2'))); ?></span>
						  </span>
						</label>
						<input type="text" id="custom" class="short" name="custom" value="" maxlength="20"><br>


						<!-- Amount Input -->
						<label for="amount"><?php echo trans('Selecteer_Aantal'); ?></label>
							<div class="amount-input">
								<button type="button" class="decrement">−</button>
								<input type="number" id="amount" value="1" min="1" max="99" oninput="enforceMinValue(this)" onchange="updateSelection()" />
								<button type="button" class="increment">+</button>
							</div>
							<br>
								<div class="button-container">
									<button class="styled-link add-to-table-btn" id="addToTableBtn">
										<?php echo trans('Regel_toevoegen'); ?>
									</button>
									<button id="tocartBtn" title="<?php echo trans('cart'); ?>" class="styled-link tocart-btn">
										<i class="fa-solid fa-cart-shopping"></i>
									</button>
								</div>
					</div>
							<!-- Summary of the selection -->
							<div class="summary" id="summary">
								<!-- Selection summary will be displayed here dynamically -->		
							</div><br>
			</div>
		</div>
    </div>	
	
	<div id="ordersModal" class="modal">
        <div class="modal-content_orders stretch animate-from-click" style="overflow-y: scroll;">
			<div class="order_header">
				<span class="ordersclose">&times;</span>
					<div id="confirmCancelModal" class="modal" style="display: none;">
						<div class="modal-content">
							<br>
							<p><center><?php echo trans('confirm_cancel_order'); ?><center></p>
							<button class="confirmButton" id="confirmCancelButton"><?php echo trans('ja'); ?></button>
							<button class="cancelButton" id="cancelCancelButton"><?php echo trans('cancel'); ?></button>
						</div>	
					</div> 
				<h2><?php echo trans('Orders_Form'); ?></h2>
					<!-- Dropdown for selecting customer -->
					<form method="GET">
						<select name="order" id="order" onchange="loaduserOrders()">
								<option value='In behandeling'><?php echo trans('In_behandeling'); ?></option>
								<option value='Bevestigd'><?php echo trans('Bevestigd'); ?></option>
								<option value='Verzonden'><?php echo trans('Verzonden'); ?></option>	
								<option value='Voltooid'><?php echo trans('Voltooid'); ?></option>
								<option value='Geannuleerd'><?php echo trans('Geannuleerd'); ?></option>				
						</select>
					</form>
				<br>
			</div>	
				<br>
				<!-- Placeholder for the order table -->
				<div id="orderTable"></div>
        </div>
    </div>

	<div id="stlModal" class="modal">
        <div class="modal-content animate-from-click" style="overflow-y: hidden;">
				<span class="stlclose">&times;</span>
				<h2><?php echo trans('EigenFileUpload'); ?></h2>
				<form id="fileForm">			
					<p>
					<label for="add_filenaam"><?php echo trans('Bestandsnaam'); ?></label>
					<input type="text" id="add_filenaam" class="right" name="add_filenaam" value="" required>
					</p>
					<p>
					<label for="omschrijving"><?php echo trans('Omschrijving'); ?></label>
					<input type="text" id="omschrijving" class="right" name="omschrijving" value="" required>
					</p>					
					<p>
						<label for="fileInput"><?php echo trans('file'); ?></label>
						<input type="text" id="file" class="right" name="file" value="" required readonly style="display: none;">
						<input type="file" id="fileInput" accept=".stl" style="display: none;">
						<!-- Custom Upload Button -->
						<button type="button" id="customFileButton" class="custom-file-upload">
							<?php echo trans('choose_file'); ?>
						</button>
						<span id="fileName" class="file-name"><?php echo trans('no_file_chosen'); ?></span>
					</p>			
					<button type="submit" id="addFileButton" class="styled-button stretch_wide"><?php echo trans('Aanvragen'); ?><div class="loader" id="loader"></div></button>
				</form>
			<br>
        </div>
    </div>

	<div id="stlViewModal" class="modal">
        <div class="modal-content_orders stretch animate-from-click" style="overflow-y: scroll;">
			<div class="order_stl">
				<span class="stlviewclose">&times;</span>
				<h2><?php echo trans('stlrequests'); ?></h2>
					<form method="GET">		 
					 <input type="hidden" id="klantnummerstl" name="klantnummerstl" value="<?php echo $_SESSION['user_id']; ?>" required readonly>
					</form>
				<br>
			</div>	
				<br>
				<!-- Placeholder for the stl table -->
				<div id="stlTable"></div>
        </div>
    </div>
          
<script>
	let settings = {}; // Global object to store settings
	// Fetch all settings from the server
	async function fetchSettings() {
		try {
			const response = await fetch('includes/settings.php');
			settings = await response.json();
		} catch (error) {
			console.error("Error fetching settings:", error);
		}
	}
	fetchSettings(); // Load settings once
	let jstax = <?php echo json_encode($taxsettings); ?>;
	let jspagination = <?php echo json_encode($settings['pagination']); ?>;
</script>
<script src="js/pagination.js"></script>      
<script src="js/scripts.js" defer></script>		
<script src="js/modal.js"></script>	
<script src="js/summary.js"></script>	

</div>
<?php include 'includes/foot.php'; ?>
</body>
</html>
