<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Complete Genform</title>
  <style>
    .field { margin: 1em 0; }
    label { font-weight: bold; display: block; margin-bottom: 0.3em; }
    .button-container { margin: 1em 0; }
    button { padding: 0.5em 1em; margin-right: 0.5em; }
    .text-input { margin-top: 0.5em; display: none; }
  </style>
</head>
<body>
  <div class="button-container">
    <button onclick="saveForm()">Save Form</button>
    <button onclick="loadForm()">Load Form</button>
  </div>
  <div id="formContainer"></div>
  <script>
    const schema = {
      "grouping": {
        "data_type": "grouping",
        "name": ["General Information"],
        "label": {
          "en": ["General Information"],
          "th": ["General Information"]
        },
        "type": ["segment"]
      },
      "Respondent Information": {
        "data_type": "section",
        "type": "section",
        "label": {
          "en": "Respondent Information",
          "th": "ข้อมูลผู้กรอกแบบประเมิน"
        },
        "segment": ["General Information"]
      },
      "Basic Information": {
        "data_type": "section",
        "type": "section",
        "label": {
          "en": "Basic Information",
          "th": "ข้อมูลเบื้องต้น"
        },
        "segment": ["General Information"]
      },
      "respondent_name": {
        "data_type": "string",
        "type": "field",
        "label": {
          "en": "Respondent Name",
          "th": "1 ชื่อผู้กรอกแบบประเมิน"
        },
        "section": "Respondent Information",
        "segment": ["General Information"],
        "required": true,
        "score": 1,
        "value": "test",
        "weight": 1
      },
      "respondent_position": {
        "data_type": "string",
        "type": "field",
        "label": {
          "en": "Respondent Position",
          "th": "2 ตำแหน่งของผู้กรอกแบบประเมิน"
        },
        "section": "Respondent Information",
        "segment": ["General Information"],
        "required": true,
        "score": 1,
        "value": "",
        "weight": 1
      },
      "respondent_email": {
        "data_type": "string",
        "type": "field",
        "label": {
          "en": "Respondent Email",
          "th": "3 อีเมลของผู้กรอกแบบประเมิน"
        },
        "section": "Respondent Information",
        "segment": ["General Information"],
        "required": true,
        "score": 1,
        "value": "",
        "weight": 1
      },
      "company_name": {
        "data_type": "string",
        "type": "field",
        "label": {
          "en": "Company name",
          "th": "1 ชื่อบริษัท"
        },
        "section": "Basic Information",
        "segment": ["General Information"],
        "required": true,
        "score": 1,
        "value": "",
        "weight": 1
      },
      "certifications": {
        "data_type": "checktext",
        "type": "field",
        "label": {
          "en": "Has your company received any sustainability-related certifications? (Multiple selections allowed)",
          "th": "บริษัทของท่านได้รับการรับรองในด้านต่าง ๆ ที่เกี่ยวข้องกับความยั่งยืนหรือไม่ (โปรดเลือกได้มากกว่า 1 ข้อ)"
        },
        "section": "Basic Information",
        "segment": ["General Information"],
        "required": true,
        "score": 1,
        "options": {
          "en": [
            "Not certified in any system",
            "ISO 14001",
            "ISO 50001",
            "ISO 45001",
            "SA 8000 / TLS 8001 / ISO 26000",
            "Green Industry Certificate by Ministry of Industry, CFO, CFP",
            "Others (please specify)"
          ],
          "th": [
            "ยังไม่ได้รับการรับรองระบบใด ๆ",
            "ISO 14001",
            "ISO 50001",
            "ISO 45001",
            "SA 8000 / TLS 8001 / ISO 26000",
            "Green Industry Certificate by Ministry of Industry, CFO, CFP",
            "อื่น ๆ (โปรดระบุ)"
          ]
        },
        "weights": [1, 1, 1, 1, 1, 1, 1, 1],
        "value": { "check": [], "text": "" }
      },
      "business_type": {
        "data_type": "radiotext",
        "type": "field",
        "label": {
          "en": "Business type",
          "th": "3 ประเภทธุรกิจ"
        },
        "section": "Basic Information",
        "segment": ["General Information"],
        "required": true,
        "score": 1,
        "options": {
          "en": [
            "1. Construction",
            "2. General procurement",
            "3. Advertising and PR",
            "4. Rental/Leasing",
            "5. IT services",
            "6. Consulting",
            "7. Outsourcing",
            "8. Others (please specify)"
          ],
          "th": [
            "1. งานก่อสร้าง",
            "2. จัดซื้อจัดจ้างทั่วไป",
            "3. งานสื่อโฆษณาและประชาสัมพันธ์",
            "4. งานเช่า / เช่าซื้อ",
            "5. งานเทคโนโลยีสารสนเทศ",
            "6. งานที่ปรึกษา",
            "7. งานจ้างบุคคลภายนอก",
            "8. อื่น ๆ (โปรดระบุ)"
          ]
        },
        "weights": [1, 1, 1, 1, 1, 1, 1, 1],
        "value": { "radio": null, "text": "" }
      },
      "employee_count": {
        "data_type": "string",
        "type": "field",
        "label": {
          "en": "Please specify number of employees",
          "th": "4 กรุณาระบุจำนวนพนักงาน"
        },
        "section": "Basic Information",
        "segment": ["General Information"],
        "required": true,
        "score": 1,
        "value": "",
        "weight": 1
      },
      "foreign_workers": {
        "data_type": "string",
        "type": "field",
        "label": {
          "en": "Foreign labor information",
          "th": "5 ข้อมูลแรงงานต่างด้าว หรือต่างชาติ"
        },
        "section": "Basic Information",
        "segment": ["General Information"],
        "required": false,
        "score": 1,
        "value": "",
        "weight": 1
      },
      "business_registration": {
        "data_type": "radiotext",
        "type": "field",
        "label": {
          "en": "Business registration or factory license",
          "th": "6 หนังสือจดทะเบียนการค้าหรือใบอนุญาตประกอบกิจการโรงงาน"
        },
        "section": "Basic Information",
        "segment": ["General Information"],
        "required": true,
        "score": 1,
        "options": {
          "en": [
            "Has (specify reference number)",
            "Doesn't have"
          ],
          "th": [
            "มี (ระบุหมายเลขอ้างอิงหนังสือดังกล่าว เช่น ภ.พ.20 หรือ ร.ง.4)",
            "ไม่มี"
          ]
        },
        "weights": [1, 1],
        "value": { "radio": null, "text": "" }
      },
      "subcontractors": {
        "data_type": "checktext",
        "type": "field",
        "label": {
          "en": "Does your company have subcontractors for any activities?",
          "th": "7 บริษัทมีคู่ค้าที่เป็นลักษณะงานรับจ้างเหมาช่วงในกิจกรรมใดบ้าง?"
        },
        "section": "Basic Information",
        "segment": ["General Information"],
        "required": true,
        "score": 1,
        "options": {
          "en": [
            "No subcontracting",
            "Construction/Equipment installation",
            "Transportation",
            "IT services",
            "Security/Cleaning services",
            "Others (please specify)"
          ],
          "th": [
            "ไม่มีการจ้างเหมาช่วง",
            "งานก่อสร้าง / ติดตั้งอุปกรณ์ต่าง ๆ",
            "งานขนส่ง",
            "งานข้อมูลงาน IT",
            "งานรักษาความปลอดภัย/ แม่บ้าน",
            "อื่น ๆ (โปรดระบุ)"
          ]
        },
        "weights": [1, 1, 1, 1, 1, 1],
        "value": { "check": [], "text": "" }
      },
      "code_of_conduct": {
        "data_type": "radio",
        "type": "field",
        "label": {
          "en": "Is your company aware of and has received communication about the content and expectations of Krungthai Bank's Code of Conduct for Business Partners?",
          "th": "8 บริษัททราบหรือได้รับการสื่อสารถึงเนื้อหาความคาดหวังของจรรยาบรรณในการดำเนินธุรกิจของคู่ค้าของธนาคารกรุงไทย จำกัด (มหาชน)"
        },
        "section": "Basic Information",
        "segment": ["General Information"],
        "required": true,
        "score": 1,
        "options": {
          "en": [
            "Fully aware and clearly communicated",
            "Partially aware",
            "Not aware/Never received communication"
          ],
          "th": [
            "ทราบและได้รับการสื่อสารอย่างชัดเจน",
            "ทราบบางส่วน",
            "ไม่ทราบ / ไม่เคยได้รับการสื่อสาร"
          ]
        },
        "weights": [1, 1, 1],
        "value": ""
      }
    };
    const lang = "en";

    function genform(containerId, schema) {
      const container = document.getElementById(containerId);
      container.innerHTML = "";

      for (const key in schema) {
        const field = schema[key];
        if (field.type !== "field") continue;

        const div = document.createElement("div");
        div.className = "field";
        div.dataset.key = key;

        const label = document.createElement("label");
        label.textContent = field.label?.[lang] || key;
        div.appendChild(label);

        const input = createInputElement(key, field, lang);
        div.appendChild(input);

        container.appendChild(div);
      }

      listenform(containerId, schema);
    }

    function createInputElement(key, field, lang) {
      const type = field.data_type;
      const wrapper = document.createElement("div");

      if (type === "string") {
        const input = document.createElement("input");
        input.type = "text";
        input.name = key;
        input.value = field.value || "";
        wrapper.appendChild(input);
      }

      else if (type === "radio" || type === "radiotext") {
        const selected = field.value?.radio ?? field.value;
        const options = field.options?.[lang] || [];
        options.forEach((opt, i) => {
          const label = document.createElement("label");
          label.style.display = "block";
          const radio = document.createElement("input");
          radio.type = "radio";
          radio.name = key;
          radio.value = i;
          radio.checked = selected === i;
          label.appendChild(radio);
          label.appendChild(document.createTextNode(" " + opt));
          wrapper.appendChild(label);
        });

        if (type === "radiotext") {
          const textInput = document.createElement("input");
          textInput.type = "text";
          textInput.name = `${key}_text`;
          textInput.className = "text-input";
          textInput.placeholder = "Specify details (e.g., Others or Reference Number)";
          textInput.value = field.value?.text || "";
          textInput.style.display = (selected === options.length - 1 || (key === "business_registration" && selected === 0)) ? "block" : "none";
          wrapper.appendChild(textInput);
        }
      }

      else if (type === "checktext") {
        const selected = field.value?.check || [];
        const options = field.options?.[lang] || [];
        options.forEach((opt, i) => {
          const label = document.createElement("label");
          label.style.display = "block";
          const check = document.createElement("input");
          check.type = "checkbox";
          check.name = key;
          check.value = i;
          check.checked = selected.includes(i);
          label.appendChild(check);
          label.appendChild(document.createTextNode(" " + opt));
          wrapper.appendChild(label);
        });

        const textInput = document.createElement("input");
        textInput.type = "text";
        textInput.name = `${key}_text`;
        textInput.className = "text-input";
        textInput.placeholder = "Specify details (e.g., Others)";
        textInput.value = field.value?.text || "";
        textInput.style.display = selected.includes(options.length - 1) ? "block" : "none";
        wrapper.appendChild(textInput);
      }

      return wrapper;
    }

    function listenform(containerId, schema) {
      const container = document.getElementById(containerId);

      container.querySelectorAll("input").forEach((input) => {
        input.addEventListener("change", () => {
          const key = input.name.split("_")[0];
          const field = schema[key];
          const type = field.data_type;

          if (type === "string") {
            field.value = container.querySelector(`input[name='${key}']`).value;
          }

          else if (type === "radio" || type === "radiotext") {
            const val = container.querySelector(`input[name='${key}']:checked`)?.value;
            const textInput = container.querySelector(`input[name='${key}_text']`);
            if (type === "radiotext") {
              const textValue = textInput ? textInput.value : "";
              field.value = { radio: val ? parseInt(val) : null, text: textValue };
              if (textInput) {
                textInput.style.display = (val && (parseInt(val) === field.options[lang].length - 1 || (key === "business_registration" && parseInt(val) === 0))) ? "block" : "none";
              }
            } else {
              field.value = val ? parseInt(val) : null;
            }
          }

          else if (type === "checktext") {
            const selected = Array.from(container.querySelectorAll(`input[name='${key}']:checked`)).map(e => parseInt(e.value));
            const textInput = container.querySelector(`input[name='${key}_text']`);
            const textValue = textInput ? textInput.value : "";
            field.value = { check: selected, text: textValue };
            if (textInput) {
              textInput.style.display = selected.includes(field.options[lang].length - 1) ? "block" : "none";
            }
          }

          console.log("Updated:", key, field.value);
        });
      });
    }

    function isFieldAnswered(field) {
      const type = field.data_type;
      if (type === "string") return !!field.value;
      if (type === "radio") return field.value !== null && field.value !== "";
      if (type === "radiotext") return field.value?.radio !== null;
      if (type === "checktext") return Array.isArray(field.value?.check) && field.value.check.length > 0;
      return true;
    }

    function saveForm() {
      try {
        const formData = {};
        for (const key in schema) {
          if (schema[key].type === "field") {
            formData[key] = schema[key].value;
          }
        }
        localStorage.setItem("formData", JSON.stringify(formData));
        alert("Form data saved successfully!");
      } catch (e) {
        console.error("Error saving form data:", e);
        alert("Failed to save form data.");
      }
    }

    function loadForm() {
      try {
        const savedData = localStorage.getItem("formData");
        if (savedData) {
          const formData = JSON.parse(savedData);
          for (const key in formData) {
            if (schema[key] && schema[key].type === "field") {
              schema[key].value = formData[key];
            }
          }
          genform("formContainer", schema);
          alert("Form data loaded successfully!");
        } else {
          alert("No saved form data found.");
        }
      } catch (e) {
        console.error("Error loading form data:", e);
        alert("Failed to load form data.");
      }
    }

    genform("formContainer", schema);
  </script>
</body>
</html>