<style>
/* ======================= Form Styles ======================= */
.form-group {
  position: relative;
  margin-bottom: 1.5rem;
}

.form-group .icon {
  position: absolute;
  top: 50%;
  left: 8px;
  transform: translateY(-50%);
  color: #888;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px 10px 10px 35px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 6px;
  background: none;
  outline: none;
}

.form-group label {
  position: absolute;
  left: 35px;
  top: 50%;
  transform: translateY(-50%);
  color: #666;
  font-size: 14px;
  pointer-events: none;
  transition: 0.2s ease all;
}
/* Focus or filled */
.form-group input:focus + label,
.form-group input:not(:placeholder-shown) + label,
.form-group select:focus + label,
.form-group select:valid + label {
  top: -6px;
  left: 30px;
  font-size: 12px;
  color: #F05B23;
}

.form-group .hint {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* Validation error styles */
.validation-error {
  color: #dc3545 !important;
  font-size: 12px;
  display: block;
  margin-top: 5px;
}

.form-group input.validation-error,
.form-group select.validation-error {
  border-color: #dc3545 !important;
}

.form-group input.validation-valid,
.form-group select.validation-valid {
  border-color: #28a745 !important;
}

#fiscal_year_box {
    display:none;
    margin-top: 20px;  /* keeps spacing clean */
    position: relative;
    margin-bottom: 30px;
}

/* ======================= Choices.js Multi-Select Fix ======================= */
.choices-form-group {
    margin-bottom: 1.5rem;
}

.choices-form-group .choices-label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 600;
    color: #333;
    position: relative;
    top: auto;
    left: auto;
    transform: none;
    background: transparent;
    padding: 0;
}

.choices-form-group .choices {
    margin-top: 0.25rem;
}

.choices-form-group .choices__inner {
    min-height: 44px;
    padding: 0.5rem;
    border: 1px solid #ced4da;
    border-radius: 6px;
    background: #fff;
}

.choices-form-group .choices__list--multiple .choices__item {
    background: #3b82f6;
    border: none;
    border-radius: 4px;
    margin: 2px;
}

.choices-form-group .choices__input {
    margin-top: 4px;
    display: block;
    width: 100% !important;
}

</style>

<!-- ======================= Scripts / CSS ======================= -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="<?php echo base_url();?>public/assets/js/jquery.validate.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<script src="<?php echo base_url();?>public/assets/js/choices.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="<?php echo base_url();?>public/assets/css/choices.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">

<!-- ======================= HTML ======================= -->
<div class="content">
  <div class="formcard">
    <?php 
    $message_type = $this->session->flashdata('message_type');
    $message_name = $this->session->flashdata('message_name');
    if ($message_type && $message_name): 
    ?>
    <div class="alert alert-<?php echo ($message_type == 'error') ? 'danger' : 'success'; ?> alert-dismissible fade show" role="alert">
      <?php echo $message_name; ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>
    
    <form class="type_form" id="type_form" method="post" action="<?php echo base_url();?>type/saveType">

      <!-- Authority -->
      <div class="form-group">
        <select name="authority_id" id="authority_id" class="form-control">
          <option value="">Select Authority</option>
          <?php foreach($authority as $aut) { ?>
          <option value="<?php echo $aut['id'];?>"><?php echo $aut['authority_name'] . " - (" . $aut['alias_name'] . ")";?></option>
          <?php } ?>
        </select>
        <label for="authority name">Authority Name</label>
      </div>

      <!-- Document Head Name -->
      <div class="form-group">
        <input type="text" id="sub_tpe" name="sub_type" placeholder=" ">
        <label for="typename">Document Head Name</label>
      </div>

      <!-- Alias -->
      <div class="form-group">
        <input type="text" id="alias" name="alias" placeholder=" ">
        <label for="alias">Alias</label>
      </div>

      <!-- Document Type -->
      <div class="form-group">
        <select name="doc_type" id="doc_type" class="form-control">
          <option value="Primary">Primary</option>
          <option value="Secondary">Secondary</option>
        </select>
        <label for="authority name">Document Type</label>
      </div>

      <!-- Document Start Date -->
      <div class="form-group" id="document_Start_date_group">
        <input type="date" class="form-control" name="document_start_date" id="document_start_date" placeholder=" ">
        <label for="document_start_date">Document Start Date</label>
        <input type="hidden" id="company_start_date" value="<?php echo date('Y-m-d', strtotime($company_data[0]['co_start_date'])); ?>">
      </div>

      <!-- Frequency -->
      <div class="form-group">
        <select name="frequency" id="frequency" class="form-control">
          <?php foreach($frequency as $freq) { ?>
            <option value="<?php echo $freq;?>"><?php echo $freq;?></option>
          <?php } ?>
        </select>
        <label for="frequency">Frequency</label>
      </div>

      <!-- Fiscal Year / Period Display -->
      <div id="fiscal_year_box" style="margin-top:1px; display:none;">
        <label style="font-size:14px;">Financial Year :</label>
        <span id="fiscal_year_value" style="font-weight:bold; margin-left:10px;"></span>
      </div>
    
      <!-- Frequency Due Date Dropdown -->
      <div id="monthly_date">
        <div class="form-group">
          <select id="dateDropdown" class="form-control" name="monthly_days">
            <option value="">Frequency due date</option>
          </select>
          <label for="dateDropdown">Frequency due Date</label>
        </div>
      </div>

      <!-- Next Due Date -->
      <div id="next_due_date_wrapper" style="margin-top:10px;">
        <label style="font-size:14px;">Next Due Date :</label>
        <span id="next_due_date_label" style="font-weight:bold;"></span>
        <input type="hidden" id="next_due_date" name="next_due_date">
      </div>

      <!-- Same / Next Month -->
      <div id="due_month_wrapper" style="display:flex; align-items:center; gap:20px; margin-bottom:20px;">
        <label style="font-size:14px; color:#666;">Due Month :</label>
        <label style="margin-right:25px; cursor:pointer;">
          <input type="radio" name="due_month" value="same" checked>
          Same Month
        </label>
        <label style="cursor:pointer;">
          <input type="radio" name="due_month" value="next">
          Next Month
        </label>
      </div>

      <!-- Document Multi-select -->
      <div class="choices-form-group">
        <label class="choices-label" for="choices-multiple-remove-button">Document</label>
        <select name="document[]" id="choices-multiple-remove-button" class="form-control" multiple>
          <?php foreach($document_data as $document) { ?>
          <option value="<?php echo $document['id'];?>"><?php echo $document['document_name'];?></option>
          <?php } ?>
        </select>
      </div>

      <!-- Dynamic Mandatory Table -->
      <div id="documentOptions" class="mt-3"></div>

      <!-- No. of reminders. -->
      <div class="form-group" id="noofreminders">
          <select id="no_of_reminders" name="no_of_reminders" class="form-control">
              <option value=""></option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
          </select>
          <label for="no_of_reminders">No. of Reminders</label>
      </div>

      <!-- Dynamic Reminder Table Container -->
      <div id="reminder_container"></div>

      <!-- Buttons -->
      <div class="formbtn-group">
        <button type="submit" class="formbtn formbtn-save">Create</button>
        <a href="javascript:history.back()" class="formbtn formbtn-cancel">Cancel</a>
      </div>
    </form>
  </div>
</div>

<input type="hidden" id="monthSelect" class="form-control" value="<?php echo date('Y-m'); ?>" style="display:none">

<!-- ======================= JavaScript ======================= -->

<script>
$(document).ready(function(){

    // Default days array based on reminder number
    const defaultDays = [30, 15, 7, 3, 2];

    function createDaysDropdown(name, selectedValue) {
        let html = `<select name="${name}" class="form-control" style="width:120px;">`;
        for (let i = 1; i <= 100; i++) {
            let sel = (i === selectedValue) ? "selected" : "";
            html += `<option value="${i}" ${sel}>${i}</option>`;
        }
        html += `</select>`;
        return html;
    }

    $('#no_of_reminders').change(function() {
        let count = parseInt($(this).val());
        let html = "";

        if (!count) {
            $("#reminder_container").html("");
            return;
        }

        html += `
            <table class="table table-bordered mt-3">
                <thead>
                    <tr>
                        <th>Reminder #</th>
                        <th>Before No. of Days</th>
                        <th>#Days</th>
                        <th>Reminder To</th>
                    </tr>
                </thead>
                <tbody>
        `;

        for (let i = 1; i <= count; i++) {
            let preset = defaultDays[i - 1];  // pick 30, 15, 7, 3, 2

            html += `
                <tr>
                    <td>Reminder #${i}</td>
                    <td>${createDaysDropdown("reminder_days[" + i + "]", preset)}</td>
                    <td>Days</td>
                    <td>
                        <input type="checkbox" name="reminder_to[${i}][]" value="User" checked> User
                        <input type="checkbox" name="reminder_to[${i}][]" value="Admin"> Admin
                        <input type="checkbox" name="reminder_to[${i}][]" value="Super Admin"> Super Admin
                    </td>
                </tr>
            `;
        }

        // Default System Reminders
        html += `
                <tr>
                    <td>Default / System Rem#1</td>
                    <td>0 (Same day)</td>
                    <td>Days</td>
                    <td>User | Admin | Super Admin</td>
                </tr>
                <tr>
                    <td>Default / System Rem#2</td>
                    <td>-1 (Day passed)</td>
                    <td>Days</td>
                    <td>User | Admin | Super Admin</td>
                </tr>
            </tbody>
            </table>
        `;

        $("#reminder_container").html(html);
    });



  console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);
  // --------------------- Config / Constants ---------------------
  const monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  const holidays = ["2024-01-26","2024-03-08","2024-03-25","2024-08-15","2024-10-02","2024-12-25"];

  // --------------------- Basic Helpers ---------------------
  function toISODate(d){ return d.toISOString().split("T")[0]; }
  function daysInMonth(y, m) { return new Date(y, m+1, 0).getDate(); }

  function setSafeDate(year, month, day) {
        let last = daysInMonth(year, month);
        let safeDay = Math.min(day, last);
        //return new Date(year, month, safeDay);
        return new Date(Date.UTC(year, month, safeDay));
    }

  // fiscalYearToStartMonth returns 0-based month index (0 = Jan)
  function fiscalYearToStartMonth(fy){
    const map={"Jan":0,"Feb":1,"March":2,"Mar":2,"April":3,"Apr":3,"May":4,"June":5,"Jun":5,"July":6,"Jul":6,"August":7,"Aug":7,"September":8,"Sep":8,"October":9,"Oct":9,"November":10,"Nov":10,"December":11,"Dec":11};
    return map[fy.split("-")[0].trim()] ?? 0;
  }

  // --------------------- Weekend / Holiday helpers ---------------------
  function isHolidayOrWeekendDate(d, holidaysArr){
    const dow = d.getDay();
    return dow === 0 || dow === 6 || holidaysArr.includes(toISODate(d));
  }

  /*function adjustBackward(date, holidaysArr){
    let d = new Date(date);
    let tries = 0;
    while(isHolidayOrWeekendDate(d, holidaysArr) && tries < 14){
      d.setDate(d.getDate() - 1);
      tries++;
    }
    return d;
  }*/

  // --------------------- Dynamic Period Generator ---------------------
  // fiscalStartMonth0 = 0..11, frequency string (case-insensitive)
  function generatePeriods(fiscalStartMonth0, frequency){
    const freq = (frequency || "").toString().trim().toLowerCase();
    // Build fiscal months sequence as 0..11 indices starting from fiscalStartMonth0
    const fiscalMonths = [];
    for(let i=0;i<12;i++){
      fiscalMonths.push((fiscalStartMonth0 + i) % 12);
    }

    if(freq === "yearly") {
      return [ fiscalMonths[11] ]; // last month of fiscal year
    }
    if(freq === "half yearly" || freq === "half_yearly" || freq === "half-yearly" || freq === "halfyearly") {
      return [ fiscalMonths[5], fiscalMonths[11] ]; // H1 end, H2 end (0-based)
    }
    if(freq === "quarterly") {
      return [ fiscalMonths[2], fiscalMonths[5], fiscalMonths[8], fiscalMonths[11] ]; // Q ends
    }
    if(freq === "monthly") {
      return fiscalMonths.slice(); // all months in FY order
    }
    if(freq === "onetime" || freq === "one-time" || freq === "one time") {
      return ["ONETIME"];
    }

    // default fallback to monthly
    return fiscalMonths.slice();
  }
 
// ---------- Robust next-due-date implementation ----------
function getNextDueDateUniversal(params) {
  const {
    fiscalStartMonth0 = 0,
    frequency,
    dueDay,
    documentStartDate,   // "YYYY-MM-DD"
    holidaysArr = [],
    dueMonthChoice = "same" // "same" or "next"
  } = params;

  if (!documentStartDate || !frequency || !dueDay) return "";

  const freq = frequency.toString().trim().toLowerCase();
  const start = new Date(documentStartDate + "T00:00:00");
  const startYear = start.getFullYear();
  const startMonth = start.getMonth(); // 0–11

  // ONE-TIME: stay in same month/year as start
  if (freq === "onetime" || freq === "one-time" || freq === "one time") {
    return toISODate(setSafeDate(startYear, startMonth, dueDay));
  }

  // Build fiscal month sequence (0–11) starting from fiscalStartMonth0
  const fiscalMonths = [];
  for (let i = 0; i < 12; i++) {
    fiscalMonths.push((fiscalStartMonth0 + i) % 12);
  }

  // Map frequency -> period end months
  let periods = [];
  if (freq === "monthly") {
    periods = fiscalMonths.slice();
  } else if (freq === "quarterly") {
    periods = [fiscalMonths[2], fiscalMonths[5], fiscalMonths[8], fiscalMonths[11]];
  } else if (
    freq === "half yearly" ||
    freq === "half-yearly" ||
    freq === "half_yearly" ||
    freq === "halfyearly"
  ) {
    periods = [fiscalMonths[5], fiscalMonths[11]];
  } else if (freq === "yearly" || freq === "annual") {
    periods = [fiscalMonths[11]];
  } else {
    // fallback: monthly
    periods = fiscalMonths.slice();
  }

  const candidates = [];

  // 1) Same fiscal year as document start: only months >= document's month
  for (let i = 0; i < periods.length; i++) {
    const m0 = periods[i];
    if (m0 < startMonth) continue;  // this whole period ends before doc's month
    const cand = setSafeDate(startYear, m0, dueDay);
    // Note: we DO NOT compare cand < start here (we allow earlier day in same month)
    candidates.push(cand);
  }

  // 2) If nothing left in same year, go to next year (all periods)
  if (!candidates.length) {
    for (let i = 0; i < periods.length; i++) {
      const m0 = periods[i];
      const cand = setSafeDate(startYear + 1, m0, dueDay);
      candidates.push(cand);
    }
  }

  // Pick earliest candidate
  candidates.sort((a, b) => a - b);
  let chosen = candidates[0];

  // If "next" month option selected, shift by +1 calendar month
  if (chosen && dueMonthChoice === "next") {
    let y = chosen.getFullYear();
    let m = chosen.getMonth() + 1;
    if (m > 11) { m = 0; y += 1; }
    chosen = setSafeDate(y, m, dueDay);
  }

  console.log("FISCAL START", fiscalStartMonth0, "FREQ", frequency, "DOC START", documentStartDate, "DUEDAY", dueDay);
  console.log("PERIOD MONTHS:", periods);
  console.log("CANDIDATES:", candidates.map(d => toISODate(d)));
  console.log("CHOSE:", toISODate(chosen));

  return toISODate(chosen);
}

// UI wrapper that uses company fiscal month and updates label
function updateNextDueDate() {
  const docStart = $("#document_start_date").val();
  const freq = $("#frequency").val();
  const dueDay = parseInt($("#dateDropdown").val(), 10);
  const dueMonthChoice = $("input[name='due_month']:checked").val() || "same";

  if (!docStart || !freq) {
    $("#next_due_date_label").text("");
    $("#next_due_date").val("");
    return;
  }

  // If frequency is NOT one-time, ensure a due day is selected
  if (!(freq.toLowerCase().includes("one") && freq.toLowerCase().includes("time")) && (!dueDay || isNaN(dueDay))) {
    $("#next_due_date_label").text("");
    $("#next_due_date").val("");
    return;
  }

  const fiscalStartMonth0 = (typeof window.fiscalStartMonth === "number") ? window.fiscalStartMonth : 0;

  const nextDue = getNextDueDateUniversal({
    fiscalStartMonth0,
    frequency: freq,
    dueDay,
    documentStartDate: docStart,
    holidaysArr: [],         // unused for now, but kept for parity
    dueMonthChoice
  });

  $("#next_due_date_label").text(nextDue);
  $("#next_due_date").val(nextDue); 
}

// wire up (call after elements exist)
$("#frequency, #document_start_date, #dateDropdown, input[name='due_month']").off("change.updateDue").on("change.updateDue", updateNextDueDate);
updateNextDueDate();

  // --------------------- UI Integration: old helpers removed / replaced ---------------------
  // Keep only the necessary UI helpers (populate dropdown etc.)
  function populateDates(year,month){
    const dateDropdown=$('#dateDropdown');
    dateDropdown.empty().append('<option value="">Frequency due date</option>');
    for(let day=1;day<=31;day++){
      dateDropdown.append(`<option value="${day}">${day}</option>`);
    }
  }

  // initialize date dropdown
  let initialMonth = $('#monthSelect').val() ? $('#monthSelect').val().split('-') : [new Date().getFullYear(), new Date().getMonth()];
  populateDates(initialMonth[0], initialMonth[1]);
  $('#monthSelect').on('change',function(){ const [y,m]=$(this).val().split('-'); populateDates(y,m); });

  // Store all documents for reference
  const allDocumentsData = [
    <?php foreach($document_data as $document) { ?>
    { id: '<?php echo $document['id'];?>', name: '<?php echo addslashes($document['document_name']);?>' },
    <?php } ?>
  ];

  // Store document groups (parent -> children mapping)
  let documentGroups = {};
  let lockedChildDocs = new Set(); // Track children that are locked (auto-added due to parent)

  // Load document groups on page init
  $.ajax({
    url: "<?php echo base_url(); ?>type/getAllDocumentGroups",
    type: "POST",
    dataType: "json",
    success: function(res) {
      documentGroups = res.groups || {};
      console.log("Document groups loaded:", documentGroups);
    }
  });

  // Choices.js init - store reference
  const docChoices = new Choices('#choices-multiple-remove-button', {
    removeItemButton: true,
    maxItemCount: 50,
    searchResultLimit: 50,
    renderChoiceLimit: 50
  });
  
  // Document start date min
  $("#document_start_date").attr("min",$("#company_start_date").val());
  $("#document_start_date").on("change",function(){
      /*if(new Date($(this).val())<new Date($("#company_start_date").val())){
        alert("Document Start Date must be >= Company Start Date"); $(this).val("");
      }*/

      let doc = $(this).val();
      let comp = $("#company_start_date").val();

      if (!doc || !comp) return;

      console.log("Doc date:", doc);
      console.log("Company date:", comp);

      if (new Date(doc) < new Date(comp)) {
          alert("Document Start Date must be ≥ Company Start Date");
          $(this).val("");
      }
  });

  // --------------------- getNextDueDate (hook for UI) ---------------------
  function getNextDueDate(){
    const compVal=$("#company_start_date").val();
    const docVal=$("#document_start_date").val();
    const freq=$("#frequency").val();
    const dayStr=$("#dateDropdown").val();
    const dueMonthChoice=$("input[name='due_month']:checked").val()||"same";

    if(!compVal || !freq || !dayStr) return "";

    const dueDay = parseInt(dayStr,10);
    const docDateStr = docVal ? docVal : compVal;
    // window.fiscalStartMonth is 0-based (set by AJAX below)
    const fiscalStartMonth0 = (typeof window.fiscalStartMonth === "number") ? window.fiscalStartMonth : 0;

    const next = getNextDueDateUniversal({
      fiscalStartMonth0,
      frequency: freq,
      dueDay,
      documentStartDate: docDateStr,
      currentDate: new Date().toISOString().split("T")[0],
      holidaysArr: holidays,
      dueMonthChoice: dueMonthChoice
    });

    return next;
  }

  // Trigger update on changes
  $("#frequency, #dateDropdown, #document_start_date, input[name='due_month']").on("change",function(){
    let next=getNextDueDate();
    $("#next_due_date_label").text(next||"");
  });

  // --------------------- Fiscal Year / Period Display (AJAX) ---------------------
  $("#frequency").on("change",function(){
    let freq=$(this).val();
    if(freq==="Yearly"||freq==="Half Yearly"||freq==="Quarterly"||freq==="Monthly"){
      $.ajax({
        url:"<?php echo base_url(); ?>type/getFiscalYear",
        type:"POST",
        dataType:"json",
        success:function(res){
          let fy=res.fiscal_year;
          window.fiscalStartMonth=fiscalYearToStartMonth(fy); // 0-based
          window.fiscalYearStr=fy;
          let FSM=window.fiscalStartMonth;
          let html="";
          if(freq==="Yearly"||freq==="Monthly"){ html=fy; }
          else if(freq==="Half Yearly"){ html=`<span style="margin-right:15px;">H1: ${monthNames[FSM]} – ${monthNames[(FSM+5)%12]}</span><span>H2: ${monthNames[(FSM+6)%12]} – ${monthNames[(FSM+11)%12]}</span>`;}
          else if(freq==="Quarterly"){ function range(s,a){return `${monthNames[s%12]} – ${monthNames[(s+a-1)%12]}`;} html=`<span style="margin-right:10px;">Q1: ${range(FSM,3)}</span><span style="margin-right:10px;">Q2: ${range(FSM+3,3)}</span><span style="margin-right:10px;">Q3: ${range(FSM+6,3)}</span><span>Q4: ${range(FSM+9,3)}</span>`;}
          $("#fiscal_year_value").html(html); $("#fiscal_year_box").show();
        }
      });
    } else { $("#fiscal_year_box").hide(); }
  });

  // Initial triggers
  $("#frequency").trigger("change");
  $("#frequency, #dateDropdown, #document_start_date").trigger("change");

  // --------------------- Document Multi-select table ---------------------
  // Helper to get document name by ID
  function getDocNameById(docId) {
    let doc = allDocumentsData.find(d => d.id === docId.toString());
    return doc ? doc.name : 'Unknown';
  }

  // Helper to add children to selection
  function autoAddChildren(parentId) {
    let childIds = documentGroups[parentId] || [];
    if (childIds.length === 0) return;

    let currentSelection = docChoices.getValue(true) || [];
    let needsUpdate = false;

    childIds.forEach(childId => {
      if (!currentSelection.includes(childId.toString())) {
        // Add child to selection
        docChoices.setChoiceByValue(childId.toString());
        lockedChildDocs.add(childId.toString());
        needsUpdate = true;
      } else {
        // Already selected, just mark as locked
        lockedChildDocs.add(childId.toString());
      }
    });

    if (needsUpdate) {
      // Trigger change to update table
      $('#choices-multiple-remove-button').trigger('change');
    }
  }

  // Handle document selection changes
  $('#choices-multiple-remove-button').on('change', function(){
    let selected = $(this).val() || [];
    let container = $('#documentOptions');
    
    // Check for newly selected parents and auto-add children
    selected.forEach(docId => {
      if (documentGroups[docId] && documentGroups[docId].length > 0) {
        // This is a parent document - auto-add children
        let childIds = documentGroups[docId];
        childIds.forEach(childId => {
          if (!selected.includes(childId.toString())) {
            // Need to add this child
            setTimeout(() => {
              docChoices.setChoiceByValue(childId.toString());
              lockedChildDocs.add(childId.toString());
              $('#choices-multiple-remove-button').trigger('change');
            }, 100);
          } else {
            lockedChildDocs.add(childId.toString());
          }
        });
      }
    });

    // Check if any locked children were removed (shouldn't happen, but reset if parent removed)
    let updatedLockedDocs = new Set();
    selected.forEach(docId => {
      if (documentGroups[docId]) {
        documentGroups[docId].forEach(childId => {
          if (selected.includes(childId.toString())) {
            updatedLockedDocs.add(childId.toString());
          }
        });
      }
    });
    lockedChildDocs = updatedLockedDocs;

    // Build/update the mandatory options table
    if (!container.find('table').length) {
      container.html(`
        <table class="table table-bordered">
          <thead class="thead-light">
            <tr>
              <th style="text-align:left;">Document Name</th>
              <th style="text-align:center;">Type</th>
              <th style="text-align:center;">Mandatory</th>
              <th style="text-align:center;">Non-Mandatory</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      `);
    }
    
    let tbody = container.find('tbody');
    
    // Remove rows for unselected documents
    tbody.find('tr').each(function() {
      if (!selected.includes($(this).data('docid').toString())) {
        $(this).remove();
      }
    });
    
    // Add/update rows for selected documents
    selected.forEach(docId => {
      let docName = getDocNameById(docId);
      let isLocked = lockedChildDocs.has(docId.toString());
      let isParent = documentGroups[docId] && documentGroups[docId].length > 0;
      
      // Check if this document is a child of any selected parent
      let isChildOfSelected = false;
      selected.forEach(parentId => {
        if (documentGroups[parentId] && documentGroups[parentId].includes(docId.toString())) {
          isChildOfSelected = true;
        }
      });
      
      let typeLabel = '';
      if (isParent) {
        typeLabel = '<span class="badge bg-primary">Parent</span>';
      } else if (isChildOfSelected) {
        typeLabel = '<span class="badge bg-info">Child</span>';
      }

      if (!tbody.find('tr[data-docid="' + docId + '"]').length) {
        // For auto-added children, mandatory is pre-selected and locked
        let mandatoryChecked = isChildOfSelected ? 'checked disabled' : 'checked';
        let nonMandatoryDisabled = isChildOfSelected ? 'disabled' : '';
        let lockedIcon = isChildOfSelected ? ' <i class="fa fa-lock text-muted" title="Auto-added child document"></i>' : '';
        
        tbody.append(`
          <tr data-docid="${docId}" data-locked="${isChildOfSelected ? '1' : '0'}">
            <td style="text-align:left;">${docName}${lockedIcon}</td>
            <td style="text-align:center;">${typeLabel}</td>
            <td style="text-align:center;">
              <input type="radio" name="mandatory[${docId}]" value="1" ${mandatoryChecked}>
              ${isChildOfSelected ? '<input type="hidden" name="mandatory[' + docId + ']" value="1">' : ''}
            </td>
            <td style="text-align:center;">
              <input type="radio" name="mandatory[${docId}]" value="0" ${nonMandatoryDisabled}>
            </td>
          </tr>
        `);
      }
    });
  });

  // Prevent removal of locked child documents
  document.getElementById('choices-multiple-remove-button').addEventListener('removeItem', function(event) {
    let removedValue = event.detail.value;
    
    if (lockedChildDocs.has(removedValue)) {
      // Prevent removal - re-add the item
      setTimeout(() => {
        docChoices.setChoiceByValue(removedValue);
        alert('This document is a child of a selected parent and cannot be removed. Remove the parent document first.');
      }, 50);
    }
  });

  // Custom form validation with manual submit handling
  $("#type_form").on('submit', function(e) {
      var errors = [];
      var firstErrorElement = null;
      
      // Clear previous errors
      $('.validation-error-msg').remove();
      $('.form-control, select, input').css('border-color', '');
      
      // Helper function to show error
      function showError(element, message) {
          $(element).css('border-color', '#dc3545');
          var errorSpan = $('<span class="validation-error-msg" style="color:#dc3545;font-size:12px;display:block;margin-top:5px;">' + message + '</span>');
          
          if ($(element).closest('.choices-form-group').length) {
              $(element).closest('.choices-form-group').find('.choices').after(errorSpan);
          } else if ($(element).closest('.form-group').length) {
              $(element).after(errorSpan);
          } else {
              $(element).after(errorSpan);
          }
          
          if (!firstErrorElement) {
              firstErrorElement = element;
          }
          errors.push(message);
      }
      
      // Validate Authority
      if (!$('#authority_id').val()) {
          showError('#authority_id', '⚠ Please select Authority');
      }
      
      // Validate Document Head Name
      if (!$('#sub_tpe').val().trim()) {
          showError('#sub_tpe', '⚠ Document Head Name is required');
      }
      
      // Validate Alias
      if (!$('#alias').val().trim()) {
          showError('#alias', '⚠ Alias is required');
      }
      
      // Validate Document Start Date
      if (!$('#document_start_date').val()) {
          showError('#document_start_date', '⚠ Document start date is required');
      }
      
      // Validate Documents (Choices.js multi-select)
      var selectedDocs = docChoices.getValue(true);
      if (!selectedDocs || selectedDocs.length === 0) {
          showError('#choices-multiple-remove-button', '⚠ Select at least one document');
      }
      
      // Validate frequency-related fields (only if not "One Time")
      var freq = $('#frequency').val().toLowerCase();
      if (freq !== 'one time' && freq !== 'one-time') {
          // Validate No. of Reminders
          if (!$('#no_of_reminders').val()) {
              showError('#no_of_reminders', '⚠ Please select No. of Reminders');
          }
          
          // Validate Frequency Due Date
          if (!$('#dateDropdown').val()) {
              showError('#dateDropdown', '⚠ Please select Frequency Due Date');
          }
      }
      
      // If there are errors, prevent form submission
      if (errors.length > 0) {
          e.preventDefault();
          
          // Scroll to first error
          if (firstErrorElement) {
              $('html, body').animate({
                  scrollTop: $(firstErrorElement).offset().top - 100
              }, 300);
          }
          
          return false;
      }
      
      // Form is valid, allow submission
      return true;
  });

  // Hide/show frequency-related fields dynamically
  function toggleFrequencyFields() {
      const freq = $("#frequency").val().toLowerCase();
      if(freq === "one time" || freq === "one-time" || freq === "one time") {
          $("#monthly_date, #next_due_date_wrapper, #due_month_wrapper, #noofreminders").hide();
      } else {
          $("#monthly_date, #next_due_date_wrapper, #due_month_wrapper, #noofreminders").show();
      }
  }

  // Trigger on frequency change
  $("#frequency").on("change", function(){
      toggleFrequencyFields();
      //$("#type_form").valid(); // re-validate after toggling
  });

  // Initial check on page load
  toggleFrequencyFields();


});

$("#dateDropdown").on("change", function () {
    let freq = $("#frequency").val();
    let docStart = $("#document_start_date").val();
    let freqDue = $("#dateDropdown").val();

    if (freqDue !== "") {   // only if user selected a due date

        if (freq === "") {
            alert("Please select Frequency first.");
            $("#dateDropdown").val("");
            return;
        }

        if (docStart === "") {
            alert("Please select Document Start Date first.");
            $("#dateDropdown").val("");
            return;
        }
    }
});

</script>
