<style>
.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;
}

/* When input or select has focus OR is 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; /* highlight color */
}

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

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

#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>

<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>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
<link rel="stylesheet" href="<?php echo base_url();?>public/assets/css/choices.min.css">
<script src="<?php echo base_url();?>public/assets/js/choices.min.js"></script>	

<!-- Bootstrap Multiselect / Choices -->
<link rel="stylesheet" href="<?php echo base_url();?>public/assets/css/choices.min.css">
<div class="content">
	<div class="formcard">
		<form class="type_form" id="type_form" method="post" action="<?php echo base_url();?>type/updateType">
			<input type="hidden" name="type_id" value="<?php echo $type_data['id'];?>">
			<input type="hidden" name="company_id" value="<?php echo $this->session->userdata('company_id');?>">
			<div class="form-group">
				<select name="authority_id" id="authority_id" class="form-control">
					<option value="">Select Authority</option>
					<?php foreach($authority_data as $aut) { ?>
						<option value="<?php echo $aut['id'];?>" 
					  <?php echo ($type_data['authority_id'] == $aut['id']) ? 'selected' : ''; ?>>
                      <?php echo $aut['authority_name'];?></option>
					<?php } ?>
				</select>
				<label for="authority name">Authority Name</label>
			</div>
			<div class="form-group">
				<input type="text" id="sub_tpe" name="sub_type" placeholder=" " value="<?php echo $type_data['type_name'];?>">
				<label for="typename">Document Head Name</label>
			</div>

			<div class="form-group">
				<input type="text" id="alias" name="alias" placeholder=" " value="<?php echo $type_data['alias_name'];?>">
				<label for="alias">Alias</label>
			</div>
			<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>
            <div class="form-group" id="document_Start_date_group">
                <input type="date" class="form-control" name="document_start_date" id="document_start_date"
                    value="<?= isset($type_data['document_start_date']) ? $type_data['document_start_date'] : '' ?>">
                <label for="document_start_date">Document Start Date</label>
            </div>
			<div class="form-group">
				<select name="frequency" id="frequency" class="form-control">
					<?php foreach($frequency as $freq) { ?>
						<option value="<?php echo $freq;?>" 
							<?php echo ($type_data['frequency'] == $freq) ? 'selected' : ''; ?>>
							<?php echo $freq;?>
						</option>
					<?php } ?>
				</select>
				<label for="frequency">Frequency</label>
			</div>
            <!-- Fiscal Year / Period Display -->
            <div id="fiscal_year_box" style="margin-top:15px; display:none;">
                <label style="font-size:14px;">Financial Year :</label>
                <span id="fiscal_year_value" style="font-weight:bold; margin-left:10px;"></span>
            </div>
            
			<div class="form-group" id="document_date_group">
				<input type="date" class="form-control" name="document_date" id="document_date" value="<?php echo $type_data['frequency_start_date'];?>">
				<label for="document_date">Document Date</label>
			</div>
			<!--<div class="form-group" id="start_date_group">
				<input type="date" class="form-control" name="frequency_start_date" id="frequency_start_date" value="<?php echo $type_data['frequency_start_date'];?>">
				<label  for="frequency_start_date">Frequency Start Date</label>
			</div>-->

            <div class="form-group" id="start_date_group">
                <input type="text" class="form-control" name="frequency_start_date" id="frequency_start_date" value="<?php echo $type_data['frequency_start_date'];?>" placeholder="Select Day & Month" readonly>
                <label for="frequency_start_date">Frequency Due Date</label>
            </div>
			
			<input type="hidden" id="monthSelect" class="form-control" value="<?php echo date('Y-m'); ?>" style="display:none">
			<div id="monthly_date">
                <div class="form-group">
                    <select id="dateDropdown" class="form-control" name="monthly_days">
                    <option value="">Select date</option>
                    </select>
                    <label for="dateDropdown">Select Date</label>
                </div>
			</div> 
            <div id="due_month_wrapper" style="display:none; margin-bottom: 20px;">
                <label style="font-size:14px; color:#666;">Due Month</label><br>

                <div style="margin-top:8px;">
                    <label style="margin-right:25px; cursor:pointer;">
                        <input type="radio" name="due_month" value="same"
                            <?= isset($type_data['due_in_same_next_month']) && $type_data['due_in_same_next_month'] == 0 ? 'checked' : '' ?>>
                        Same Month
                    </label>

                    <label style="cursor:pointer;">
                        <input type="radio" name="due_month" value="next"
                            <?= isset($type_data['due_in_same_next_month']) && $type_data['due_in_same_next_month'] == 1 ? 'checked' : '' ?>>
                        Next Month
                    </label>
                </div>
            </div>
            <!--<div class="form-group" id="document_Start_date_group">
				<input type="date" class="form-control" name="document_start_date" id="document_start_date">
				<label for="document_start_date">Document Start Date</label>
			</div>-->

			<?php 
				// selected docs (from DB)
				$document_types = explode(',', $type_data['document_name']); 
			?>

		<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="multiple">
				<option value="">Select Document</option>
				<?php foreach($document_data as $document) { ?>
				<option value="<?php echo $document['id']; ?>" 
					<?php echo (is_array($document_types) && in_array($document['id'], $document_types)) ? 'selected' : ''; ?>>
					<?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="">Select</option>
					<option value="1" <?= count($reminders) == 1 ? 'selected' : '' ?>>1</option>
					<option value="2" <?= count($reminders) == 2 ? 'selected' : '' ?>>2</option>
					<option value="3" <?= count($reminders) == 3 ? 'selected' : '' ?>>3</option>
					<option value="4" <?= count($reminders) == 4 ? 'selected' : '' ?>>4</option>
					<option value="5" <?= count($reminders) == 5 ? 'selected' : '' ?>>5</option>
				</select>
				<label for="no_of_reminders">No. of Reminders</label>
			</div>

			<!-- Reminder Container -->
			<div id="reminder_container"></div>
			
		<div class="formbtn-group">
		<button type="submit" class="formbtn formbtn-save">Update</button>
		<a href="<?= base_url('type/allType/' . $this->session->userdata('company_id')) ?>" class="formbtn formbtn-cancel">Cancel</a>
		</div>
		</form>
	</div>
</div>

<script>
$(document).ready(function() {
  function populateDates(selectedDate = '') {
    const dateDropdown = $('#dateDropdown');
    dateDropdown.empty().append('<option value="">Select date</option>');

    for (let day = 1; day <= 31; day++) {
      const dateStr = ('0' + day).slice(-2); // format 01, 02, etc.
      const selectedAttr = (dateStr === selectedDate) ? 'selected' : '';
      dateDropdown.append(`<option value="${dateStr}" ${selectedAttr}>${dateStr}</option>`);
    }
  }

  // PHP variable from DB (e.g. "05" for 5th day)
  const selectedDate = "<?php echo isset($type_data['frequency_start_date']) ? str_pad($type_data['frequency_start_date'], 2, '0', STR_PAD_LEFT) : ''; ?>";

  populateDates(selectedDate);

  // Optional: if you want to repopulate on month change (still 1–31)
  $('#monthSelect').on('change', function() {
    populateDates(selectedDate);
  });
});

$(document).ready(function(){
    // 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)

    // 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;
    }
    
    // Initialize Choices.js multi-select - 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>
              `);
            }
          };
        }
    });

    // Load document groups and process existing selections
    $.ajax({
      url: "<?php echo base_url(); ?>type/getAllDocumentGroups",
      type: "POST",
      dataType: "json",
      success: function(res) {
        documentGroups = res.groups || {};
        console.log("Document groups loaded:", documentGroups);
        
        // Process existing selections to identify locked children
        let currentSelection = docChoices.getValue(true) || [];
        currentSelection.forEach(docId => {
          if (documentGroups[docId] && documentGroups[docId].length > 0) {
            // This is a parent - lock its children
            documentGroups[docId].forEach(childId => {
              if (currentSelection.includes(childId.toString())) {
                lockedChildDocs.add(childId.toString());
              }
            });
          }
        });
        
        // Rebuild the table with parent/child indicators
        rebuildMandatoryTableWithGroups();
      }
    });

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

    // 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">' + 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 Document Head Name
        if (!$('#sub_type').val() || !$('#sub_type').val().trim()) {
            showError('#sub_type', '⚠ Document Head Name is required');
        }
        
        // Validate Alias
        if (!$('#alias').val() || !$('#alias').val().trim()) {
            showError('#alias', '⚠ Alias is required');
        }
        
        // 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;
    });

    let fiscalStartMonth = null; // 0-based month index
    let fiscalYearStr = '';      // e.g., "April - March"

function loadFinancialYear() {
        let freq = $("#frequency").val();

        // Hide for One Time / empty
        if (!freq || freq === "One Time") {
            $("#fiscal_year_box").hide();
            return;
        }

        if (fiscalStartMonth !== null) {
            renderFiscalOutput(freq);
            return;
        }

        // Call backend to get fiscal year string (Ex: "Apr - Mar", "Jul - Jun")
        $.ajax({
            url: "<?php echo base_url(); ?>type/getFiscalYear",
            type: "POST",
            dataType: "json",
            success: function (res) {
                if (res.fiscal_year) {
                    fiscalYearStr = res.fiscal_year;
                    fiscalStartMonth = fiscalYearToStartMonth(res.fiscal_year); // convert FY to 0-based start month
                    renderFiscalOutput(freq);
                } else {
                    $("#fiscal_year_box").hide();
                }
            }
        });
    }

    // 👉 Run on page load
    loadFinancialYear();

    function fiscalYearToStartMonth(fy) {
    if (!fy) return 0;

    let start = fy.split("-")[0].trim().toLowerCase();

    const map = {
        "jan": 0, "january": 0,
        "feb": 1, "february": 1,
        "mar": 2, "march": 2,
        "apr": 3, "april": 3,
        "may": 4,
        "jun": 5, "june": 5,
        "jul": 6, "july": 6,
        "aug": 7, "august": 7,
        "sep": 8, "september": 8,
        "oct": 9, "october": 9,
        "nov": 10, "november": 10,
        "dec": 11, "december": 11
    };

    return map[start] ?? 0;  // fallback to Jan
}

const monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

function renderFiscalOutput(freq) {
    let FSM = fiscalStartMonth;
    let html = "";

    if (freq === "Yearly" || freq === "Monthly") {
        html = fiscalYearStr;
    }
    else if (freq === "Half Yearly") {
        html =
            `<div>H1: ${monthNames[FSM]} – ${monthNames[(FSM + 5) % 12]}</div>
             <div>H2: ${monthNames[(FSM + 6) % 12]} – ${monthNames[(FSM + 11) % 12]}</div>`;
    }
    else if (freq === "Quarterly") {
        function range(start, len) {
            return `${monthNames[start % 12]} – ${monthNames[(start + len - 1) % 12]}`;
        }
        html =
            `<div>Q1: ${range(FSM,3)}</div>
             <div>Q2: ${range(FSM+3,3)}</div>
             <div>Q3: ${range(FSM+6,3)}</div>
             <div>Q4: ${range(FSM+9,3)}</div>`;
    }

    $("#fiscal_year_value").html(html);
    $("#fiscal_year_box").show();
}


    // Show/Hide date fields based on frequency
    function toggleDateFields(value) {
        if (value === "Monthly") {
            $('#monthly_date').show();
            $('#due_month_wrapper').show();
            $('#document_date_group').hide();
            $('#start_date_group').hide();
            $('#frequency_start_date, #document_date').val('');
        } 
        else if (value === "Yearly" || value === "Half Yearly" || value === "Quarterly") {
            $('#start_date_group').show();
            $('#due_month_wrapper').show();
            $('#monthly_date').hide();
            $('#document_date_group').hide();
            $('#monthly_days').val('');
        } 
        else if (value === "One Time") {
            $('#document_date_group').show();
            $('#monthly_date').hide();
            $('#start_date_group').hide();
            $('#due_month_wrapper').hide();
            $('#frequency_start_date').val('');
            $('#monthly_days').val('');
        } 
        else {
            $('#monthly_date, #start_date_group, #document_date_group, #due_month_wrapper').hide();
            $('#frequency_start_date').val('');
            $('#monthly_days').val('');
        }
    }

    toggleDateFields($('#frequency').val());

    $('#frequency').change(function () {
        toggleDateFields($(this).val());
        loadFinancialYear();
    });

    // ✅ Pass PHP array (doc_id => mandatory) into JS
    var mandatoryData = <?php echo json_encode($selected_docs); ?>;

    // Function to rebuild the mandatory table with parent-child support
    function rebuildMandatoryTableWithGroups() {
        let selectedDocs = docChoices.getValue(true) || []; 
        let container = $('#documentOptions');

        // First, check for newly selected parents and auto-add children
        selectedDocs.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 (!selectedDocs.includes(childId.toString())) {
                // Need to add this child
                setTimeout(() => {
                  docChoices.setChoiceByValue(childId.toString());
                  lockedChildDocs.add(childId.toString());
                  rebuildMandatoryTableWithGroups();
                }, 100);
              } else {
                lockedChildDocs.add(childId.toString());
              }
            });
          }
        });

        // Update locked children list based on current parents
        let updatedLockedDocs = new Set();
        selectedDocs.forEach(docId => {
          if (documentGroups[docId]) {
            documentGroups[docId].forEach(childId => {
              if (selectedDocs.includes(childId.toString())) {
                updatedLockedDocs.add(childId.toString());
              }
            });
          }
        });
        lockedChildDocs = updatedLockedDocs;

        // Create table if not exists
        if (!container.find('table').length) {
            let table = `
                <table class="table table-bordered">
                    <thead class="thead-light">
                        <tr>
                            <th>Document Name</th>
                            <th>Type</th>
                            <th>Mandatory</th>
                            <th>Non-Mandatory</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            `;
            container.html(table);
        }

        let tbody = container.find('tbody');

        // Remove rows for docs that are no longer selected
        tbody.find('tr').each(function () {
            let docId = $(this).data('docid').toString();
            if (!selectedDocs.includes(docId)) {
                $(this).remove();
            }
        });

        // Add rows for selected docs
        selectedDocs.forEach(docId => {
            let docName = getDocNameById(docId);
            let isParent = documentGroups[docId] && documentGroups[docId].length > 0;
            
            // Check if this document is a child of any selected parent
            let isChildOfSelected = false;
            selectedDocs.forEach(parentId => {
              if (documentGroups[parentId] && documentGroups[parentId].includes(docId.toString())) {
                isChildOfSelected = true;
              }
            });
            
            let typeLabel = '';
            if (isParent) {
              typeLabel = '<span class="badge bg-primary" style="background:#007bff;color:#fff;padding:3px 8px;border-radius:4px;">Parent</span>';
            } else if (isChildOfSelected) {
              typeLabel = '<span class="badge bg-info" style="background:#17a2b8;color:#fff;padding:3px 8px;border-radius:4px;">Child</span>';
            }

            if (!tbody.find('tr[data-docid="' + docId + '"]').length) {
                // ✅ Check DB value (mandatoryData[docId]) → 1 = mandatory, 0 = non-mandatory
                // For auto-added children, force mandatory
                let isMandatory = isChildOfSelected ? 1 : ((mandatoryData[docId] !== undefined) ? mandatoryData[docId] : 1);

                // For auto-added children, disable the radio buttons
                let mandatoryChecked = isMandatory == 1 ? 'checked' : '';
                let mandatoryDisabled = isChildOfSelected ? 'disabled' : '';
                let nonMandatoryChecked = isMandatory == 0 ? 'checked' : '';
                let nonMandatoryDisabled = isChildOfSelected ? 'disabled' : '';
                let lockedIcon = isChildOfSelected ? ' <i class="fa fa-lock text-muted" title="Auto-added child document"></i>' : '';

                let row = `
                    <tr data-docid="${docId}" data-locked="${isChildOfSelected ? '1' : '0'}">
                        <td>${docName}${lockedIcon}</td>
                        <td style="text-align:center;">${typeLabel}</td>
                        <td style="text-align:center;">
                            <input type="radio" name="mandatory[${docId}]" value="1" ${mandatoryChecked} ${mandatoryDisabled}>
                            ${isChildOfSelected ? '<input type="hidden" name="mandatory[' + docId + ']" value="1">' : ''}
                        </td>
                        <td style="text-align:center;">
                            <input type="radio" name="mandatory[${docId}]" value="0" ${nonMandatoryChecked} ${nonMandatoryDisabled}>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            } else {
                // Update existing row with type label if needed
                let existingRow = tbody.find('tr[data-docid="' + docId + '"]');
                if (existingRow.find('td:eq(1)').html() !== typeLabel) {
                    existingRow.find('td:eq(1)').html(typeLabel);
                }
            }
        });
    }

    // On change of document select
    $('#choices-multiple-remove-button').on('change', function () {
        rebuildMandatoryTableWithGroups();
    });

    // 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());
          });
          
          // Rebuild table after auto-removal
          rebuildMandatoryTableWithGroups();
        }, 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);
          });
          
          // Rebuild table after auto-addition
          rebuildMandatoryTableWithGroups();
        }, 50);
      }
    });
});

$('#frequency_start_date').datepicker({
    format: "dd-MM",
    autoclose: true,
    todayHighlight: true,
    endDate: new Date()
});

// ================ REMINDERS ================
// Existing reminders from database
var existingReminders = <?= json_encode($reminders ?? []) ?>;

// 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 selected = (i == selectedValue) ? 'selected' : '';
        html += `<option value="${i}" ${selected}>${i}</option>`;
    }
    html += `</select>`;
    return html;
}

function buildReminderTable(count) {
    let html = "";

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

    html += `
        <table class="table table-bordered mt-3">
            <thead class="thead-light">
                <tr>
                    <th style="width:80px">Reminder</th>
                    <th style="width:140px">Days Before</th>
                    <th></th>
                    <th>Send To</th>
                </tr>
            </thead>
            <tbody>
    `;

    for (let i = 1; i <= count; i++) {
        // Check if we have existing data for this reminder
        let existingReminder = existingReminders.find(r => r.reminder_no == i);
        let preset = defaultDays[i - 1] || 7;
        
        if (existingReminder) {
            preset = existingReminder.days_before;
        }

        // Check existing values for checkboxes
        let userChecked = existingReminder && (existingReminder.reminder_to_user === 't' || existingReminder.reminder_to_user === true || existingReminder.reminder_to_user === '1') ? 'checked' : '';
        let adminChecked = existingReminder && (existingReminder.reminder_to_admin === 't' || existingReminder.reminder_to_admin === true || existingReminder.reminder_to_admin === '1') ? 'checked' : '';
        let superAdminChecked = existingReminder && (existingReminder.reminder_to_super_admin === 't' || existingReminder.reminder_to_super_admin === true || existingReminder.reminder_to_super_admin === '1') ? 'checked' : '';
        
        // If no existing reminder, default user checked
        if (!existingReminder) {
            userChecked = 'checked';
        }

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

    // Default System Reminders (always shown)
    html += `
                <tr class="table-secondary">
                    <td>Default / System Rem#1</td>
                    <td>0 (Same day)</td>
                    <td>Days</td>
                    <td>User | Admin | Super Admin</td>
                </tr>
                <tr class="table-secondary">
                    <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);
}

// On change of no_of_reminders dropdown
$('#no_of_reminders').change(function() {
    let count = parseInt($(this).val()) || 0;
    buildReminderTable(count);
});

// Hide reminders for One Time frequency
function toggleRemindersVisibility() {
    const freq = $("#frequency").val();
    if (freq === "One Time") {
        $("#noofreminders").hide();
        $("#reminder_container").html("");
    } else {
        $("#noofreminders").show();
        // Rebuild reminders table
        let count = parseInt($('#no_of_reminders').val()) || 0;
        if (count > 0) {
            buildReminderTable(count);
        } else if (existingReminders.length > 0) {
            // If no count selected but we have existing reminders, use that count
            buildReminderTable(existingReminders.length);
        }
    }
}

// On frequency change
$('#frequency').on('change', function() {
    toggleRemindersVisibility();
});

// On page load - build reminder table and handle visibility
$(document).ready(function() {
    const freq = $("#frequency").val();
    
    // Only show reminders for non-One Time frequencies
    if (freq !== "One Time") {
        $("#noofreminders").show();
        let reminderCount = existingReminders.length;
        if (reminderCount > 0) {
            buildReminderTable(reminderCount);
        }
    } else {
        $("#noofreminders").hide();
        $("#reminder_container").html("");
    }
});
</script>