<!-- Main Content -->
<?php $is_view_only = isset($is_view_only) && $is_view_only; ?>
<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/' . $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 if ($is_view_only): ?>
            <div class="alert alert-info alert-dismissible fade show mb-3" role="alert">
                <i class="fas fa-eye"></i> <strong>View Only Mode:</strong> This document head has <?= $has_uploads ?> uploaded document(s) and cannot be edited.
            </div>
            <?php endif; ?>
            
            <form action="<?= base_url('companydocheads/save') ?>" method="post">
                <input type="hidden" name="company_id" value="<?= $company->id ?>">
                <input type="hidden" name="type_id" value="<?= $doc_head->id ?>">
                
                <!-- Basic Info -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="card bg-light">
                            <div class="card-body">
                                <h6 class="card-title text-primary"><i class="fas fa-file-alt"></i> Document Head Information</h6>
                                <table class="table table-sm table-borderless mb-0">
                                    <tr>
                                        <td width="40%"><strong>Authority:</strong></td>
                                        <td><?= htmlspecialchars($doc_head->authority_name) ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Document Head:</strong></td>
                                        <td><?= htmlspecialchars($doc_head->type_name) ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Alias:</strong></td>
                                        <td><?= htmlspecialchars($doc_head->alias_name) ?: '-' ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Frequency:</strong></td>
                                        <td><?= ucfirst($doc_head->frequency) ?></td>
                                    </tr>
                                    <!--<tr>
                                        <td><strong>Master Start Date:</strong></td>
                                        <td><?= $doc_head->document_start_date ? date('d-M-Y', strtotime($doc_head->document_start_date)) : '-' ?></td>
                                    </tr>-->
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card bg-light">
                            <div class="card-body">
                                <h6 class="card-title text-primary"><i class="fas fa-building"></i> Company Information</h6>
                                <table class="table table-sm table-borderless mb-0">
                                    <tr>
                                        <td width="40%"><strong>Company:</strong></td>
                                        <td><?= htmlspecialchars($company->company_name) ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Company Start Date:</strong></td>
                                        <td><strong class="text-primary"><?= date('d-M-Y', strtotime($company->co_start_date)) ?></strong></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Current Status:</strong></td>
                                        <td>
                                            <?php if ($company_settings && $company_settings->is_enabled): ?>
                                                <span class="badge bg-success">🟢 Active</span>
                                            <?php elseif ($company_settings && $company_settings->is_reviewed): ?>
                                                <span class="badge bg-warning text-dark">🟡 Reviewed</span>
                                            <?php elseif ($company_settings): ?>
                                                <span class="badge bg-danger">🔴 Pending Review</span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">⚪ Not Configured</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php //if ($company_settings && $company_settings->enabled_at): ?>
                                    <tr>
                                        <td><strong>Financial Year:</strong></td>
                                        <td><?= $company->fiscal_year ?></td>
                                    </tr>
                                    <?php //endif; ?>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Custom Settings -->
                <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-cog"></i> Custom Settings</h6>
                            </div>
                            <div class="card-body py-2">
                                <?php 
                                // Get due day - company settings first (if not empty), then master template
                                $due_day_value = '';
                                if ($company_settings && !empty($company_settings->custom_frequency_start_date)) {
                                    $due_day_value = $company_settings->custom_frequency_start_date;
                                } elseif (!empty($doc_head->frequency_start_date)) {
                                    $due_day_value = $doc_head->frequency_start_date;
                                }
                                // Determine due in same/next value
                                $due_in_same_next = '';
                                if ($company_settings && !empty($company_settings->custom_due_in_same_next_month)) {
                                    $due_in_same_next = $company_settings->custom_due_in_same_next_month;
                                } elseif (isset($doc_head->due_in_same_next_month) && $doc_head->due_in_same_next_month !== '' && $doc_head->due_in_same_next_month !== null) {
                                    $due_in_same_next = ($doc_head->due_in_same_next_month == '1' || $doc_head->due_in_same_next_month == 'N') ? '1' : '0';
                                }
                                ?>
                                <div class="row mb-2 align-items-center">
                                    <label for="custom_start_date" class="col-sm-5 col-form-label col-form-label-sm">
                                        Start Date <?php if (!$is_view_only): ?><span class="text-danger">*</span><?php endif; ?>
                                    </label>
                                    <div class="col-sm-7">
                                        <input type="date" class="form-control form-control-sm" id="custom_start_date" name="custom_start_date"
                                               value="<?= $company_settings ? $company_settings->custom_start_date : $doc_head->document_start_date ?>"
                                               min="<?= date('Y-m-d', strtotime($company->co_start_date)) ?>" <?= $is_view_only ? 'disabled' : 'required' ?>>
                                    </div>
                                </div>
                                
                                <div class="row mb-2 align-items-center">
                                    <label for="custom_frequency_start_date" class="col-sm-5 col-form-label col-form-label-sm">Due Day</label>
                                    <div class="col-sm-7">
                                        <input type="number" class="form-control form-control-sm" id="custom_frequency_start_date" name="custom_frequency_start_date"
                                               value="<?= $due_day_value ?>" placeholder="e.g., 7" min="1" max="31" <?= $is_view_only ? 'disabled' : 'required' ?>>
                                    </div>
                                </div>
                                
                                <div class="row mb-2 align-items-center">
                                    <label for="custom_due_in_same_next_month" class="col-sm-5 col-form-label col-form-label-sm">Due Month</label>
                                    <div class="col-sm-7">
                                        <select class="form-control form-control-sm" id="custom_due_in_same_next_month" name="custom_due_in_same_next_month" <?= $is_view_only ? 'disabled' : 'required' ?>>
                                            <option value="">-- Select --</option>
                                            <option value="0" <?= ($due_in_same_next === '0') ? 'selected' : '' ?>>Same Month</option>
                                            <option value="1" <?= ($due_in_same_next === '1') ? 'selected' : '' ?>>Next Month</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <!-- Next Due Date -->
                                <div class="row mb-2 align-items-center">
                                    <label class="col-sm-5 col-form-label col-form-label-sm">Next Due Date</label>
                                    <div class="col-sm-7">
                                        <span id="next_due_date_display" class="badge bg-success" style="font-size: 0.9rem; padding: 6px 12px;">-</span>
                                    </div>
                                </div>
                                
                                <small class="text-muted d-block mt-2" style="font-size: 0.7rem;">
                                    <i class="fas fa-info-circle"></i> Start date must be ≥ <?= date('d-M-Y', strtotime($company->co_start_date)) ?>
                                    <?php if (!empty($doc_head->frequency_start_date)): ?>
                                    | Template Due Day: <?= $doc_head->frequency_start_date ?>
                                    <?php endif; ?>
                                </small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <!-- Mandatory Documents - Editable -->
                        <div class="card">
                            <div class="card-header bg-info text-white">
                                <h6 class="mb-0"><i class="fas fa-list"></i> Documents <?php if (!$is_view_only): ?><small>(Select documents)</small><?php endif; ?></h6>
                            </div>
                            <div class="card-body" style="max-height: 280px; overflow-y: auto;">
                                <?php if (!$is_view_only && !empty($all_documents)): ?>
                                    <!-- Editable: Multi-select dropdown for documents -->
                                    <div class="mb-2">
                                        <select name="document[]" id="document_select" class="form-control" multiple="multiple" style="width:100%;">
                                            <?php foreach($all_documents as $doc): ?>
                                            <option value="<?= $doc->id ?>" <?= isset($selected_docs[$doc->id]) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($doc->document_name) ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <!-- Mandatory table -->
                                    <div id="documentOptions"></div>
                                <?php elseif (!empty($mandatory_docs)): ?>
                                    <!-- View-only display -->
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Document</th>
                                                <th>Mandatory</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php $i = 1; foreach ($mandatory_docs as $doc): ?>
                                            <tr>
                                                <td><?= $i++ ?></td>
                                                <td><?= htmlspecialchars($doc->document_name) ?></td>
                                                <td>
                                                    <?php 
                                                    $is_mandatory = ($doc->is_mandatory === true || $doc->is_mandatory === 't' || $doc->is_mandatory === '1');
                                                    ?>
                                                    <span class="badge bg-<?= $is_mandatory ? 'success' : 'secondary' ?>"><?= $is_mandatory ? 'Yes' : 'No' ?></span>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                <?php else: ?>
                                    <p class="text-muted mb-0">No documents configured.</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Reminders - Editable -->
                <?php 
                $freq = strtolower($doc_head->frequency ?? '');
                $is_one_time = ($freq === 'one time' || $freq === 'one-time' || $freq === 'onetime');
                ?>
                <div class="row mb-4" id="reminders_section" <?= $is_one_time ? 'style="display:none;"' : '' ?>>
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header bg-warning">
                                <h6 class="mb-0"><i class="fas fa-bell"></i> Reminders</h6>
                            </div>
                            <div class="card-body">
                                <?php if (!$is_view_only): ?>
                                    <!-- Editable Reminders -->
                                    <div class="row mb-3">
                                        <div class="col-md-4">
                                            <label class="form-label">No. of Reminders</label>
                                            <select id="no_of_reminders" name="no_of_reminders" class="form-control form-control-sm">
                                                <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>
                                        </div>
                                    </div>
                                    <div id="reminder_container"></div>
                                <?php elseif (!empty($reminders)): ?>
                                    <!-- View-only display -->
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Reminder #</th>
                                                <th>Days Before Due</th>
                                                <th>To User</th>
                                                <th>To Admin</th>
                                                <th>To Super Admin</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($reminders as $reminder): ?>
                                            <tr>
                                                <td><?= $reminder->reminder_no ?></td>
                                                <td><?= $reminder->days_before ?> days</td>
                                                <td><?= ($reminder->reminder_to_user === 't' || $reminder->reminder_to_user === 'true') ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>' ?></td>
                                                <td><?= ($reminder->reminder_to_admin === 't' || $reminder->reminder_to_admin === 'true') ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>' ?></td>
                                                <td><?= ($reminder->reminder_to_super_admin === 't' || $reminder->reminder_to_super_admin === 'true') ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>' ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                <?php else: ?>
                                    <p class="text-muted mb-0">
                                        <i class="fas fa-info-circle"></i> No reminders configured.
                                    </p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="row">
                    <div class="col-12">
                        <hr>
                        <div class="d-flex justify-content-between">
                            <a href="<?= base_url('type/allType/' . $company->id) ?>" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> <?= $is_view_only ? 'Back' : 'Cancel' ?>
                            </a>
                            <?php if (!$is_view_only): ?>
                            <div>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> Save
                                </button>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Choices.js for multi-select -->
<link rel="stylesheet" href="<?= base_url() ?>public/assets/css/choices.min.css">
<script src="<?= base_url() ?>public/assets/js/choices.min.js"></script>

<script>
// Document selection data
var mandatoryData = <?= json_encode($selected_docs ?? []) ?>;
var existingReminders = <?= json_encode(array_map(function($r) {
    return [
        'reminder_no' => $r->reminder_no,
        'days_before' => $r->days_before,
        'reminder_to_user' => $r->reminder_to_user,
        'reminder_to_admin' => $r->reminder_to_admin,
        'reminder_to_super_admin' => $r->reminder_to_super_admin
    ];
}, $reminders ?? [])) ?>;
var isViewOnly = <?= $is_view_only ? 'true' : 'false' ?>;

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

// 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;
}

// Build mandatory table when documents change
function rebuildMandatoryTable() {
    let selectedDocs = docChoices.getValue(true) || [];
    let container = $('#documentOptions');
    
    if (selectedDocs.length === 0) {
        container.html('<p class="text-muted small">Select documents above</p>');
        return;
    }
    
    let html = '<table class="table table-sm table-bordered"><thead><tr><th>Document</th><th>Mandatory</th><th>Non-Mandatory</th></tr></thead><tbody>';
    
    selectedDocs.forEach(docId => {
        let docName = $('#document_select option[value="' + docId + '"]').text();
        let isMandatory = mandatoryData[docId] === '1' || mandatoryData[docId] === 1;
        let isLocked = lockedChildDocs.has(docId.toString());
        let isChildOfSelected = false;
        
        // Check if this document is a child of any selected parent
        selectedDocs.forEach(parentId => {
            if (documentGroups[parentId] && documentGroups[parentId].includes(docId.toString())) {
                isChildOfSelected = true;
            }
        });
        
        html += '<tr>';
        html += '<td>' + (isLocked ? '<i class="fa fa-lock text-muted" style="margin-right: 5px;"></i>' : '') + docName + '</td>';
        
        // Disable mandatory selection for child documents
        if (isChildOfSelected) {
            html += '<td class="text-center"><input type="radio" name="mandatory[' + docId + ']" value="1" checked disabled></td>';
            html += '<td class="text-center"><input type="radio" name="mandatory[' + docId + ']" value="0" disabled></td>';
            // Add hidden input to ensure child is always mandatory
            html += '<input type="hidden" name="mandatory[' + docId + ']" value="1">';
        } else {
            html += '<td class="text-center"><input type="radio" name="mandatory[' + docId + ']" value="1" ' + (isMandatory ? 'checked' : '') + '></td>';
            html += '<td class="text-center"><input type="radio" name="mandatory[' + docId + ']" value="0" ' + (!isMandatory ? 'checked' : '') + '></td>';
        }
        
        html += '</tr>';
    });
    
    html += '</tbody></table>';
    container.html(html);
}

// Initialize Choices.js after document groups are loaded
function initializeDocumentSelect() {
    if (!isViewOnly && document.getElementById('document_select')) {
        // STEP 1: Get initially selected documents from the select element BEFORE Choices.js initializes
        let selectElement = document.getElementById('document_select');
        let initiallySelectedDocs = Array.from(selectElement.selectedOptions).map(opt => opt.value);
        
        // STEP 2: Identify which selected documents are children of other selected documents
        // This must happen BEFORE Choices.js initialization so the template can use lockedChildDocs
        initiallySelectedDocs.forEach(docId => {
            initiallySelectedDocs.forEach(parentId => {
                if (documentGroups[parentId] && documentGroups[parentId].includes(docId.toString())) {
                    // This is a child document - lock it
                    lockedChildDocs.add(docId.toString());
                }
            });
        });
        
        console.log("Initially locked child documents:", Array.from(lockedChildDocs));
        
        // STEP 3: Now initialize Choices.js - the template will correctly use lockedChildDocs
        docChoices = new Choices('#document_select', {
            removeItemButton: true,
            maxItemCount: 50,
            searchResultLimit: 50,
            renderChoiceLimit: 50,
            placeholder: true,
            placeholderValue: 'Select documents...',
            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>
                        `);
                    }
                };
            }
        });
        
        // Handle document removal (prevent removal of locked children, auto-remove children when parent removed)
        document.getElementById('document_select').addEventListener('removeItem', function(event) {
            let removedValue = event.detail.value;
            
            // If trying to remove a locked child, re-add it and show alert
            if (lockedChildDocs.has(removedValue.toString())) {
                setTimeout(() => {
                    docChoices.setChoiceByValue(removedValue.toString());
                    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
                    document.getElementById('document_select').dispatchEvent(new Event('change'));
                }, 50);
            }
        });
        
        // Handle document addition (auto-add and lock children when parent added)
        document.getElementById('document_select').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 this child
                        lockedChildDocs.add(childIdStr);
                    });
                    // Trigger change to rebuild table
                    document.getElementById('document_select').dispatchEvent(new Event('change'));
                }, 50);
            }
        });
        
        // Listen for document changes
        document.getElementById('document_select').addEventListener('change', function() {
            rebuildMandatoryTable();
        });
        
        // Initial build
        rebuildMandatoryTable();
    }
}

$(document).ready(function() {
    // Load document groups first, then initialize
    $.ajax({
        url: '<?= base_url("type/getDocumentGroups") ?>',
        type: "POST",
        dataType: "json",
        success: function(res) {
            documentGroups = res.groups || {};
            console.log("Document groups loaded:", documentGroups);
            // Initialize Choices.js after groups are loaded
            initializeDocumentSelect();
        },
        error: function() {
            console.error("Failed to load document groups");
            // Initialize anyway, but without group functionality
            initializeDocumentSelect();
        }
    });
    
    // Get company fiscal year start month (0-indexed)
    const fiscalYear = '<?= $company->fiscal_year ?? "April-March" ?>';
    const fiscalStartMonth = getFiscalStartMonth(fiscalYear);
    const frequency = '<?= strtolower($doc_head->frequency ?? "monthly") ?>';
    
    // ============= REMINDERS =============
    const defaultDays = [30, 15, 7, 3, 2];
    
    function createDaysDropdown(name, selectedValue) {
        let html = '<select name="' + name + '" class="form-control form-control-sm" style="width:100px;">';
        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-sm table-bordered"><thead><tr>';
        html += '<th style="width:80px">Reminder</th>';
        html += '<th style="width:120px">Days Before</th>';
        html += '<th></th>';
        html += '<th>Send To</th>';
        html += '</tr></thead><tbody>';
        
        for (let i = 1; i <= count; i++) {
            let existingReminder = existingReminders.find(r => r.reminder_no == i);
            let preset = defaultDays[i - 1] || 7;
            
            if (existingReminder) {
                preset = existingReminder.days_before;
            }
            
            let userChecked = existingReminder && (existingReminder.reminder_to_user === 't' || existingReminder.reminder_to_user === 'true') ? 'checked' : '';
            let adminChecked = existingReminder && (existingReminder.reminder_to_admin === 't' || existingReminder.reminder_to_admin === 'true') ? 'checked' : '';
            let superAdminChecked = existingReminder && (existingReminder.reminder_to_super_admin === 't' || existingReminder.reminder_to_super_admin === 'true') ? 'checked' : '';
            
            if (!existingReminder) {
                userChecked = 'checked';
            }
            
            html += '<tr>';
            html += '<td>#' + i + '</td>';
            html += '<td>' + createDaysDropdown("reminder_days[" + i + "]", preset) + '</td>';
            html += '<td>Days</td>';
            html += '<td>';
            html += '<label class="me-2"><input type="checkbox" name="reminder_to[' + i + '][]" value="User" ' + userChecked + '> User</label>';
            html += '<label class="me-2"><input type="checkbox" name="reminder_to[' + i + '][]" value="Admin" ' + adminChecked + '> Admin</label>';
            html += '<label><input type="checkbox" name="reminder_to[' + i + '][]" value="Super Admin" ' + superAdminChecked + '> Super Admin</label>';
            html += '</td>';
            html += '</tr>';
        }
        
        // System reminders (display only)
        html += '<tr class="table-secondary"><td>System #1</td><td>0 (Same day)</td><td>Days</td><td>All Users</td></tr>';
        html += '<tr class="table-secondary"><td>System #2</td><td>-1 (Day after)</td><td>Days</td><td>All Users</td></tr>';
        html += '</tbody></table>';
        
        $("#reminder_container").html(html);
    }
    
    // Build reminders on page load
    if (!isViewOnly) {
        let reminderCount = existingReminders.length;
        if (reminderCount > 0) {
            buildReminderTable(reminderCount);
        }
    }
    
    // Handle no_of_reminders change
    $('#no_of_reminders').change(function() {
        let count = parseInt($(this).val()) || 0;
        buildReminderTable(count);
    });
    
    function getFiscalStartMonth(fy) {
        const map = {
            "January": 0, "February": 1, "March": 2, "April": 3, "May": 4, "June": 5,
            "July": 6, "August": 7, "September": 8, "October": 9, "November": 10, "December": 11
        };
        return map[fy.split("-")[0].trim()] ?? 0;
    }
    
    function calculateNextDueDate() {
        const startDate = $('#custom_start_date').val();
        const dueDay = parseInt($('#custom_frequency_start_date').val(), 10);
        const dueMonth = $('#custom_due_in_same_next_month').val(); // "0" = same, "1" = next
        
        if (!startDate || !dueDay || isNaN(dueDay) || dueMonth === '') {
            $('#next_due_date_display').text('-').removeClass('bg-success bg-warning').addClass('bg-secondary');
            return;
        }
        
        const dueMonthChoice = (dueMonth === '1') ? 'next' : 'same';
        const nextDue = getNextDueDateUniversal({
            fiscalStartMonth0: fiscalStartMonth,
            frequency: frequency,
            dueDay: dueDay,
            documentStartDate: startDate,
            holidaysArr: [],
            dueMonthChoice: dueMonthChoice
        });
        
        if (nextDue) {
            // Format date for display
            const d = new Date(nextDue + 'T00:00:00');
            const options = { day: '2-digit', month: 'short', year: 'numeric' };
            const formatted = d.toLocaleDateString('en-GB', options);
            $('#next_due_date_display').text(formatted).removeClass('bg-secondary bg-warning').addClass('bg-success');
        } else {
            $('#next_due_date_display').text('-').removeClass('bg-success bg-warning').addClass('bg-secondary');
        }
    }
    
    // Next due date calculation (simplified from add_type.php)
    function getNextDueDateUniversal(params) {
        const {
            fiscalStartMonth0 = 0,
            frequency,
            dueDay,
            documentStartDate,
            holidaysArr = [],
            dueMonthChoice = "same"
        } = 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();
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        // 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
        const fiscalMonths = [];
        for (let i = 0; i < 12; i++) {
            fiscalMonths.push((fiscalStartMonth0 + i) % 12);
        }
        
        // Map frequency -> period end months based on start date month
        // For yearly: the period is the START MONTH of the document
        // For other frequencies: use fiscal year periods
        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") {
            // For yearly, the period is based on the document start month, not fiscal year end
            periods = [startMonth];
        } else {
            periods = fiscalMonths.slice();
        }
        
        const candidates = [];
        
        // Start from document start year, not just today's year
        const searchStartYear = Math.min(startYear, today.getFullYear());
        
        // Check from start year to 2 years in the future
        for (let year = searchStartYear; year <= today.getFullYear() + 2; year++) {
            for (const periodMonth of periods) {
                let dueYear = year;
                let dueMonthIdx = periodMonth;
                
                // Adjust for "next month"
                if (dueMonthChoice === "next") {
                    dueMonthIdx += 1;
                    if (dueMonthIdx > 11) {
                        dueMonthIdx = 0;
                        dueYear++;
                    }
                }
                
                const dueDate = setSafeDate(dueYear, dueMonthIdx, dueDay);
                
                // Check if due date is in the future (or today) and period >= start date
                const periodDate = new Date(year, periodMonth, 1);
                const startDateObj = new Date(start.getFullYear(), start.getMonth(), 1);
                
                // For the first due date, period must be >= start month/year
                // And due date must be >= today
                if (periodDate >= startDateObj && dueDate >= today) {
                    candidates.push(dueDate);
                }
            }
        }
        
        if (candidates.length === 0) return "";
        
        // Sort and return the earliest future due date
        candidates.sort((a, b) => a - b);
        return toISODate(candidates[0]);
    }
    
    function setSafeDate(year, month, day) {
        // Get last day of month to avoid overflow
        const lastDay = new Date(year, month + 1, 0).getDate();
        const safeDay = Math.min(day, lastDay);
        return new Date(year, month, safeDay);
    }
    
    function toISODate(d) {
        const yyyy = d.getFullYear();
        const mm = String(d.getMonth() + 1).padStart(2, '0');
        const dd = String(d.getDate()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd}`;
    }
    
    // Bind change events
    $('#custom_start_date, #custom_frequency_start_date, #custom_due_in_same_next_month').on('change keyup', function() {
        calculateNextDueDate();
    });
    
    // Initial calculation
    calculateNextDueDate();
});
</script>