<style>
/* ======================= Card & Layout Styles ======================= */
.card {
  border: 1px solid #dee2e6;
  margin-bottom: 1rem;
}

.card-header {
  font-weight: 600;
  border-bottom: 2px solid rgba(0,0,0,.125);
}

.card-body {
  padding: 1.25rem;
}

/* Form Control Styles */
.form-control-sm {
  border-radius: 4px;
  border: 1px solid #ced4da;
}

.form-control-sm:focus {
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

/* Label Styles */
.col-form-label-sm {
  font-weight: 500;
  color: #495057;
  padding-top: calc(0.25rem + 1px);
  padding-bottom: calc(0.25rem + 1px);
  font-size: 0.875rem;
}

/* Validation error styles */
.validation-error-msg {
  color: #dc3545 !important;
  font-size: 0.75rem;
  display: block;
  margin-top: 0.25rem;
}

.form-control.is-invalid {
  border-color: #dc3545 !important;
}

.form-control.is-valid {
  border-color: #28a745 !important;
}

/* Badge Styles */
.badge {
  font-weight: 500;
}

#fiscal_year_box {
    display: none;
}

/* ======================= Choices.js Multi-Select Styles ======================= */
.choices {
    margin-bottom: 0.5rem;
}

.choices__inner {
    min-height: 38px;
    padding: 0.375rem 0.5rem;
    border: 1px solid #ced4da;
    border-radius: 4px;
    background: #fff;
}

.choices__list--multiple .choices__item {
    background: #0d6efd;
    border: none;
    border-radius: 3px;
    margin: 2px;
    font-size: 0.875rem;
}

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

/* Alert Styles */
.alert-sm {
    padding: 0.5rem 0.75rem;
    font-size: 0.875rem;
}
</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="card position-relative shadow-sm rounded-4">
    <div class="fab-top-group" style="display: flex; gap: 8px; position: absolute; top: 8px; right: 25px; z-index: 10;">
      <a href="<?= base_url('type/allType/' . $this->session->userdata('company_id')) ?>" class="btn btn-outline-secondary btn-sm" title="Back to List" style="border-radius: 50%; width: 36px; height: 36px; padding: 0; display: flex; align-items: center; justify-content: center;">
        <i class="fa fa-arrow-left"></i>
      </a>
    </div>
    
    <div class="card-body">
      <?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">
        <input type="hidden" id="company_start_date" value="<?php echo date('Y-m-d', strtotime($company_data[0]['co_start_date'])); ?>">
        
        <!-- Basic Information Section -->
        <div class="row mb-4">
          <div class="col-md-6">
            <div class="card">
              <div class="card-header bg-primary text-white py-2">
                <h6 class="mb-0"><i class="fas fa-info-circle"></i> Basic Information</h6>
              </div>
              <div class="card-body">
                <!-- Authority -->
                <div class="row mb-3 align-items-center">
                  <label for="authority_id" class="col-sm-4 col-form-label col-form-label-sm">
                    Authority <span class="text-danger">*</span>
                  </label>
                  <div class="col-sm-8">
                    <select name="authority_id" id="authority_id" class="form-control form-control-sm">
                      <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>
                  </div>
                </div>

                <!-- Document Head Name -->
                <div class="row mb-3 align-items-center">
                  <label for="sub_tpe" class="col-sm-4 col-form-label col-form-label-sm">
                    Document Head <span class="text-danger">*</span>
                  </label>
                  <div class="col-sm-8">
                    <input type="text" id="sub_tpe" name="sub_type" class="form-control form-control-sm" placeholder="Enter document head name">
                  </div>
                </div>

                <!-- Alias -->
                <div class="row mb-3 align-items-center">
                  <label for="alias" class="col-sm-4 col-form-label col-form-label-sm">
                    Alias <span class="text-danger">*</span>
                  </label>
                  <div class="col-sm-8">
                    <input type="text" id="alias" name="alias" class="form-control form-control-sm" placeholder="Enter alias">
                  </div>
                </div>

                <!-- Document Type -->
                <div class="row mb-3 align-items-center">
                  <label for="doc_type" class="col-sm-4 col-form-label col-form-label-sm">
                    Document Type
                  </label>
                  <div class="col-sm-8">
                    <select name="doc_type" id="doc_type" class="form-control form-control-sm">
                      <option value="Primary">Primary</option>
                      <option value="Secondary">Secondary</option>
                    </select>
                  </div>
                </div>

                <!-- Frequency -->
                <div class="row mb-3 align-items-center">
                  <label for="frequency" class="col-sm-4 col-form-label col-form-label-sm">
                    Frequency <span class="text-danger">*</span>
                  </label>
                  <div class="col-sm-8">
                    <select name="frequency" id="frequency" class="form-control form-control-sm">
                      <?php foreach($frequency as $freq) { ?>
                        <option value="<?php echo $freq;?>"><?php echo $freq;?></option>
                      <?php } ?>
                    </select>
                  </div>
                </div>

                <!-- Fiscal Year Display -->
                <div id="fiscal_year_box" class="row mb-2" style="display:none;">
                  <label class="col-sm-4 col-form-label col-form-label-sm">Financial Year</label>
                  <div class="col-sm-8">
                    <span id="fiscal_year_value" class="badge bg-info" style="font-size: 0.85rem; padding: 6px 12px;"></span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="col-md-6">
            <div class="card">
              <div class="card-header bg-success text-white py-2">
                <h6 class="mb-0"><i class="fas fa-calendar-alt"></i> Schedule Settings</h6>
              </div>
              <div class="card-body">
                <!-- Document Start Date -->
                <div class="row mb-3 align-items-center" id="document_Start_date_group">
                  <label for="document_start_date" class="col-sm-4 col-form-label col-form-label-sm">
                    Start Date <span class="text-danger">*</span>
                  </label>
                  <div class="col-sm-8">
                    <input type="date" class="form-control form-control-sm" name="document_start_date" id="document_start_date">
                    <small class="text-muted" style="font-size: 0.7rem;">
                      <i class="fas fa-info-circle"></i> Must be ≥ Company Start Date
                    </small>
                  </div>
                </div>

                <!-- Frequency Due Date -->
                <div id="monthly_date">
                  <div class="row mb-3 align-items-center">
                    <label for="dateDropdown" class="col-sm-4 col-form-label col-form-label-sm">
                      Due Day <span class="text-danger">*</span>
                    </label>
                    <div class="col-sm-8">
                      <select id="dateDropdown" class="form-control form-control-sm" name="monthly_days">
                        <option value="">Select due day</option>
                      </select>
                    </div>
                  </div>
                </div>

                <!-- Due Month -->
                <div id="due_month_wrapper" class="row mb-3 align-items-center">
                  <label class="col-sm-4 col-form-label col-form-label-sm">Due Month</label>
                  <div class="col-sm-8">
                    <div class="form-check form-check-inline">
                      <input class="form-check-input" type="radio" name="due_month" id="due_same" value="same" checked>
                      <label class="form-check-label" for="due_same">Same Month</label>
                    </div>
                    <div class="form-check form-check-inline">
                      <input class="form-check-input" type="radio" name="due_month" id="due_next" value="next">
                      <label class="form-check-label" for="due_next">Next Month</label>
                    </div>
                  </div>
                </div>

                <!-- Next Due Date Display -->
                <div id="next_due_date_wrapper" class="row mb-2 align-items-center">
                  <label class="col-sm-4 col-form-label col-form-label-sm">Next Due Date</label>
                  <div class="col-sm-8">
                    <span id="next_due_date_label" class="badge bg-success" style="font-size: 0.9rem; padding: 6px 12px;">-</span>
                    <input type="hidden" id="next_due_date" name="next_due_date">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Documents Section -->
        <div class="row mb-4">
          <div class="col-md-6">
            <div class="card">
              <div class="card-header bg-info text-white py-2">
                <h6 class="mb-0"><i class="fas fa-file-alt"></i> Documents <span class="text-danger">*</span></h6>
              </div>
              <div class="card-body">
                <div class="mb-2">
                  <select name="document[]" id="choices-multiple-remove-button" class="form-control form-control-sm" 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>
              </div>
            </div>
          </div>

          <div class="col-md-6">
            <div class="card">
              <div class="card-header bg-warning text-dark py-2">
                <h6 class="mb-0"><i class="fas fa-bell"></i> Reminders</h6>
              </div>
              <div class="card-body">
                <!-- No. of reminders -->
                <div class="row mb-3 align-items-center" id="noofreminders">
                  <label for="no_of_reminders" class="col-sm-5 col-form-label col-form-label-sm">
                    No. of Reminders
                  </label>
                  <div class="col-sm-7">
                    <select id="no_of_reminders" name="no_of_reminders" class="form-control form-control-sm">
                      <option value="">Select</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>
                  </div>
                </div>

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

        <!-- Buttons -->
        <div class="row">
          <div class="col-12 text-center">
            <button type="submit" class="btn btn-primary btn-lg px-5">
              <i class="fas fa-save"></i> Create Document Head
            </button>
            <a href="<?= base_url('type/allType/' . $this->session->userdata('company_id')) ?>" class="btn btn-secondary btn-lg px-5 ms-2">
              <i class="fas fa-times"></i> Cancel
            </a>
          </div>
        </div>
      </form>
    </div>
  </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,
    callbackOnCreateTemplates: function(template) {
      return {
        item: (classNames, data) => {
          const isLocked = lockedChildDocs.has(data.value);
          return template(`
            <div class="${classNames.item} ${data.highlighted ? classNames.highlightedState : classNames.itemSelectable}" data-item data-id="${data.id}" data-value="${data.value}" ${data.active ? 'aria-selected="true"' : ''} ${data.disabled ? 'aria-disabled="true"' : ''}>
              ${isLocked ? '<i class="fa fa-lock" style="opacity: 0.5; margin-right: 5px;"></i>' : ''}
              ${data.label}
              <button type="button" class="${classNames.button}" data-button ${isLocked ? 'style="display:none;"' : ''}>Remove item</button>
            </div>
          `);
        },
        choice: (classNames, data) => {
          const isChild = isDocumentChild(data.value);
          return template(`
            <div class="${classNames.item} ${classNames.itemChoice} ${data.disabled ? classNames.itemDisabled : classNames.itemSelectable}" data-select-text="${this.config.itemSelectText}" data-choice ${data.disabled ? 'data-choice-disabled aria-disabled="true"' : 'data-choice-selectable'} data-id="${data.id}" data-value="${data.value}" ${data.groupId > 0 ? 'role="treeitem"' : 'role="option"'}>
              ${isChild ? '<i class="fa fa-lock text-muted" style="margin-right: 5px; font-size: 0.9em;"></i>' : ''}
              ${data.label}
            </div>
          `);
        }
      };
    }
  });
  
  // Helper function to check if a document is a child of any document
  function isDocumentChild(docId) {
    for (let parentId in documentGroups) {
      if (documentGroups[parentId].includes(docId.toString())) {
        return true;
      }
    }
    return false;
  }
  
  // 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>
        `);
      }
    });
  });

  // Handle document removal (auto-remove children when parent removed)
  document.getElementById('choices-multiple-remove-button').addEventListener('removeItem', function(event) {
    let removedValue = event.detail.value;
    
    // Check if trying to remove a locked child document directly
    if (lockedChildDocs.has(removedValue)) {
      // Prevent removal - re-add the item
      setTimeout(() => {
        docChoices.setChoiceByValue(removedValue);
        Swal.fire({
          icon: 'warning',
          title: 'Cannot Remove Child',
          html: '<i class="fa fa-lock"></i> This is a child document that is automatically included with its parent.<br><br>Remove the parent document first to remove this child.',
          confirmButtonText: 'OK'
        });
      }, 50);
      return;
    }
    
    // Check if this is a parent document - if so, auto-remove its children
    if (documentGroups[removedValue] && documentGroups[removedValue].length > 0) {
      let childrenToRemove = documentGroups[removedValue];
      setTimeout(() => {
        childrenToRemove.forEach(childId => {
          // Unlock the child
          lockedChildDocs.delete(childId.toString());
          // Remove the child
          docChoices.removeActiveItemsByValue(childId.toString());
        });
        
        // Trigger change to rebuild table
        $('#choices-multiple-remove-button').trigger('change');
      }, 50);
    }
  });
  
  // Handle document addition (auto-add and lock children when parent added)
  document.getElementById('choices-multiple-remove-button').addEventListener('addItem', function(event) {
    let addedValue = event.detail.value;
    
    // Check if this is a parent document - if so, auto-add its children
    if (documentGroups[addedValue] && documentGroups[addedValue].length > 0) {
      let childrenToAdd = documentGroups[addedValue];
      setTimeout(() => {
        childrenToAdd.forEach(childId => {
          let childIdStr = childId.toString();
          // Only add if not already selected
          if (!docChoices.getValue(true).includes(childIdStr)) {
            docChoices.setChoiceByValue(childIdStr);
          }
          // Lock the child
          lockedChildDocs.add(childIdStr);
        });
        
        // Trigger change to rebuild table
        $('#choices-multiple-remove-button').trigger('change');
      }, 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').removeClass('is-invalid').removeClass('is-valid');
      
      // Helper function to show error
      function showError(element, message) {
          $(element).addClass('is-invalid');
          var errorSpan = $('<span class="validation-error-msg">' + message + '</span>');
          
          // Insert error message after the form control
          $(element).closest('.col-sm-8, .col-sm-7').append(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 Documents (Choices.js multi-select)
      var selectedDocs = docChoices.getValue(true);
      if (!selectedDocs || selectedDocs.length === 0) {
          $('#choices-multiple-remove-button').closest('.card-body').prepend('<div class="alert alert-danger alert-sm validation-error-msg">⚠ Please select at least one document</div>');
          errors.push('Documents required');
          if (!firstErrorElement) {
              firstErrorElement = '#choices-multiple-remove-button';
          }
      }
      
      // Validate frequency-related fields (only if not "One Time")
      var freq = $('#frequency').val().toLowerCase();
      if (freq !== 'one time' && freq !== 'one-time' && freq !== 'onetime') {
          // Validate Document Start Date (not required for One Time)
          if (!$('#document_start_date').val()) {
              showError('#document_start_date', '⚠ Document start date is required');
          }
          
          // Validate No. of Reminders
          if (!$('#no_of_reminders').val()) {
              showError('#no_of_reminders', '⚠ Please select No. of Reminders');
          }
          
          // Validate Frequency Due Date (Due Day)
          if (!$('#dateDropdown').val()) {
              showError('#dateDropdown', '⚠ Please select Due Day');
          }
      }
      
      // 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>
