jQuery(document).ready(function($) { const safeBorderColor = "#e5e7eb"; const safeBorderWidth = "1px"; const safeHeaderColor = "#374151"; const safeValueColor = "#111827"; function fetchAndStoreSheetData() { const sheetUrl = $("#sheet_url").val(); const isTSV = $("#sheet_type").val() === "tsv"; const url = sheetUrl; const type = isTSV ? "tsv" : "csv"; $.ajax({ url: checkerAdminSecurity.ajaxurl, type: "POST", data: { action: "load_repeater_field_card", sheet_url: url, sheet_type: type, security: checkerAdminSecurity.nonce, }, success: function (response) { if (response.success) { const parsedData = response.data; const headers = Object.keys(parsedData[0] || {}); const cleanedData = parsedData.map((row) => { const cleanedRow = {}; headers.forEach((header) => { cleanedRow[header] = row[header] || ""; }); return cleanedRow; }); sheetData = cleanedData; sheetHeaders = headers; appendFieldsToPreview(); handleResultsDisplay(); } else { console.error("Error fetching sheet data:", response.data); } }, error: function (xhr, status, error) { console.error("AJAX error:", error); }, }); } function parseSheetData(data) { return data; } function getStoredSheetData() { const data = $("#stored_sheet_data").val(); return data ? JSON.parse(data) : []; } function getStoredSheetHeaders() { const headers = $("#stored_sheet_headers").val(); return headers ? JSON.parse(headers) : []; } const sheetData = []; const sheetHeaders = []; function appendFieldsToPreview() { const fieldsContainer = $(".dw-checker-form-fields"); fieldsContainer.empty(); sheetHeaders.forEach((header) => { const fieldId = `field_${header.replace(/\s+/g, "_").toLowerCase()}`; const fieldLabel = header; const fieldPlaceholder = `Enter ${header}`; const fieldLabelColor = $("#field_label_color").val() || "#000000"; const fieldDisplayLabel = $("#field_display_label").is(":checked") ? "block" : "none"; const isTextField = true; let uniqueValues = []; if (sheetData.length > 0) { uniqueValues = [...new Set(sheetData.map((row) => row[header]))].filter( (val) => val !== "" ); } const fieldHtml = `
`; fieldsContainer.append(fieldHtml); }); } function setStyles() { const borderColor = $("#border_color").val() || safeBorderColor; const borderWidth = $("#border_width").val() || safeBorderWidth; const headerColor = $("#result_header").val() || safeHeaderColor; const valueColor = $("#result_value").val() || safeValueColor; $(".dw-checker-result-header").css("color", headerColor); $(".dw-checker-result-value").css("color", valueColor); $(".dw-checker-divider").css("border-color", borderColor); $(".dw-checker-divider").css("border-width", borderWidth); } function setButtonStyles() { const buttonTextColor = $("#button_text_color").val() || "#ffffff"; const buttonBgColor = $("#button_bg_color").val() || "#007bff"; const buttonBorderColor = $("#button_border_color").val() || "#007bff"; $(".search-button").css("color", buttonTextColor); $(".search-button").css("background-color", buttonBgColor); $(".search-button").css("border-color", buttonBorderColor); $(".back-button").css("color", buttonTextColor); $(".back-button").css("background-color", buttonBgColor); $(".back-button").css("border-color", buttonBorderColor); } function getColumnSettings() { const columnSettings = []; const columnName = $(".column-name"); const hide = $(".column-hide"); const type = $(".column-type"); const prefix = $(".column-prefix"); const button_text = $(".column-button-text"); columnName.each(function (index) { columnSettings.push({ name: $(this).val(), hide: $(hide[index]).is(":checked"), type: $(type[index]).val(), prefix: $(prefix[index]).val(), button_text: $(button_text[index]).val(), }); }); return columnSettings; } function preprocessSheetData(data, columnSettings) { const processedRow = {}; columnSettings.forEach((setting) => { if (!setting.hide) { processedRow[setting.name] = data[setting.name] || ""; } }); return processedRow; } const prefix = []; function handleResultsDisplay() { if (sheetData.length > 0) { // Extract column settings const columnSettings = getColumnSettings(); // Preprocess sheetData based on column settings const processedSheetData = preprocessSheetData(sheetData, columnSettings); const displayTypeSet = $(".result-display-type").val() || "vertical-table"; const cardType = $(".result-display-card-type").val() || "column"; // Get card type with fallback $("div#dw-checker-form > .dw-checker-wrapper") .removeClass("standard-table vertical-table cards div") .addClass(displayTypeSet + "-output-type"); console.log(cardType); // Set row limits based on display type let limitedData; if (displayTypeSet === "standard-table") { limitedData = processedSheetData.slice(0, 30); // Show 30 rows for standard-table } else { if (displayTypeSet === "cards" && cardType === "row") { limitedData = processedSheetData.slice(0, 10); } else { limitedData = processedSheetData.slice(0, 3); // Show 3 rows for other outputs } } // Prepare data for Handlebars template const resultsData = { displayType: displayTypeSet, cardType: cardType, // Pass card type to the template columnHeaders: Object.keys(limitedData[0] || {}), // Column headers for standard table results: limitedData, resultDivider: $(".result-divider").val() || "black", // Default fallback resultDividerWidth: $(".result-divider-width").val() || "1", // Default fallback headerColor: $("#result_header").val() || "black", // Default fallback valueColor: $("#result_value").val() || "black", // Default fallback }; // Debugging logs to verify data console.log("Results Data:", resultsData); // Determine which container to render into let targetContainer; if (["standard-table", "cards"].includes(displayTypeSet)) { targetContainer = $("#dw-checker-outside-results"); targetContainer.show(); // Show the outside container $(".dw-checker-results").hide(); // Hide the standard results container targetContainer = targetContainer.find(".dw-checker-wrapper"); // Do not hide the form } else { targetContainer = $(".dw-checker-results"); targetContainer.show(); // Show the standard results container $("#dw-checker-outside-results").hide(); // Hide the outside container // Hide the form (if needed) } // Check if Handlebars is available if (typeof Handlebars === "undefined") { console.error("Handlebars library is not loaded"); return; } // Compile and render the appropriate template let renderedResults = ""; // Check if Handlebars is available if (typeof Handlebars === "undefined") { console.error( "Handlebars library is not loaded. Using simple HTML output.", ); renderedResults = createSimpleHTML(resultsData); } else { switch (displayTypeSet) { case "vertical-table": const verticalTableTemplateSource = $( "#vertical-table-template", )?.html(); if (!verticalTableTemplateSource) { console.warn( "Vertical table template not found, using simple HTML", ); renderedResults = createSimpleHTML(resultsData); } else { const verticalTableTemplate = Handlebars.compile( verticalTableTemplateSource, ); renderedResults = verticalTableTemplate(resultsData); } break; case "div": const divTemplateSource = $("#div-template")?.html(); if (!divTemplateSource) { console.warn("Div template not found, using simple HTML"); renderedResults = createSimpleHTML(resultsData); } else { const divTemplate = Handlebars.compile(divTemplateSource); renderedResults = divTemplate(resultsData); } break; case "standard-table": const standardTableTemplateSource = $( "#standard-table-template", )?.html(); if (!standardTableTemplateSource) { console.warn( "Standard table template not found, using simple HTML", ); renderedResults = createSimpleHTML(resultsData); } else { const standardTableTemplate = Handlebars.compile( standardTableTemplateSource, ); renderedResults = standardTableTemplate(resultsData); } break; case "cards": const cardsTemplateSource = $("#cards-template")?.html(); if (!cardsTemplateSource) { console.warn("Cards template not found, using simple HTML"); renderedResults = createSimpleHTML(resultsData); } else { const cardsTemplate = Handlebars.compile(cardsTemplateSource); renderedResults = cardsTemplate(resultsData); } break; default: console.warn( "Unknown display type:", displayTypeSet, "using simple HTML", ); renderedResults = createSimpleHTML(resultsData); } } // Insert rendered HTML into the target container targetContainer.html(renderedResults); // Initialize DataTables for standard table if (displayTypeSet === "standard-table") { $(".dw-standard-table").DataTable({ paging: true, pageLength: 10, searching: false, // Hide search input info: false, // Hide "Showing X of Y entries" scrollX: false, // Disable horizontal scrolling by default responsive: true, autoWidth: true, deferRender: true, columnDefs: [ { targets: "th", className: "dt-left", width: "auto", }, { targets: "td", className: "dt-left", width: "auto", }, ], initComplete: function(settings, json) { var table = $(this).DataTable(); var columns = table.columns(); var totalWidth = table.table().container().width(); // Distribute width evenly among columns var columnWidth = Math.floor(totalWidth / columns.length); columns.each(function(index) { table.column(index).header().style.width = columnWidth + "px"; table.column(index).footer().style.width = columnWidth + "px"; }); // Force table redraw table.columns.adjust().draw(); }, drawCallback: function(settings) { var table = $(this).DataTable(); var tableWidth = table.table().container().width(); var contentWidth = table.table().node().scrollWidth; // Enable horizontal scrolling only when needed if (contentWidth > tableWidth) { table.table().container().css('overflow-x', 'auto'); } else { table.table().container().css('overflow-x', 'hidden'); } } }); initializePagination(targetContainer); } else if (displayTypeSet === "cards") { initializeCardPagination(); } } else { console.log("No data available in sheetData."); } } function initializeCardPagination() { const pages = $(".result-page"); let currentPage = 0; function showPage(pageIndex) { pages.hide(); $(pages[pageIndex]).show(); $(".current-page").text(`Data ${pageIndex + 1}`); } $(".prev-page").on("click", function () { currentPage = Math.max(0, currentPage - 1); showPage(currentPage); }); $(".next-page").on("click", function () { currentPage = Math.min(pages.length - 1, currentPage + 1); showPage(currentPage); }); showPage(currentPage); } function initializePagination(targetContainer) { let currentPage = 0; const pages = $(".result-page"); const totalPages = pages.length; function showPage(pageIndex) { pages.hide(); $(pages[pageIndex]).show(); $(".current-page").text(`Data ${pageIndex + 1}`); } $(".prev-page").on("click", function () { currentPage = Math.max(0, currentPage - 1); showPage(currentPage); }); $(".next-page").on("click", function () { currentPage = Math.min(totalPages - 1, currentPage + 1); showPage(currentPage); }); showPage(currentPage); } function updatePage(pageIndex) { $(".result-page").hide(); $(`.result-page[data-page="${pageIndex}"]`).show(); $(".current-page").text(`Data ${pageIndex + 1}`); } const cardTemplateSource = $("#cards-template")?.html(); const cardTemplate = Handlebars.compile(cardTemplateSource); const newCardData = { fields: [ { kolom: "Column 1", type: "text", label: "Label 1", placeholder: "Placeholder 1", match: "match-1", }, { kolom: "Column 2", type: "text", label: "Label 2", placeholder: "Placeholder 2", match: "match-2", }, { kolom: "Column 3", type: "text", label: "Label 3", placeholder: "Placeholder 3", match: "match-3", }, { kolom: "Column 4", type: "text", label: "Label 4", placeholder: "Placeholder 4", match: "match-4", }, ], }; const newCardHTML = cardTemplate(newCardData); change = function (event) { const visibility = $(event.target).is(":checked"); const border = $("#border_style").val(); const borderRadius = $("#border_radius").val(); const height = $("#height").val(); const placeholder = $("#placeholder").val(); }; // Removed duplicate setfields() function that was overriding the working one in admin-editor.js // The admin-editor.js version properly extracts headers from parsed CSV data function createSimpleHTML(data) { let html = "
No template available
"; return html; } function set_card_output_style() { const cardOutputStyle = $("#card_output_style").val(); const cardOutputStyleElement = $(".card-output-style"); cardOutputStyleElement.removeClass("style1 style2 style3 style4"); cardOutputStyleElement.addClass(cardOutputStyle); } function updateSecurityFieldRequirements() { const recaptchaEnabled = $("#recaptcha_enabled").is(":checked"); const turnstileEnabled = $("#turnstile_enabled").is(":checked"); if (recaptchaEnabled) { $("#recaptcha_field").prop("required", true); $("#turnstile_field").prop("required", false); } else if (turnstileEnabled) { $("#turnstile_field").prop("required", true); $("#recaptcha_field").prop("required", false); } else { $("#recaptcha_field").prop("required", false); $("#turnstile_field").prop("required", false); } } });