<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
body { background: #f8f9fa; }
.upload-entry { background: #fff; border: 1px solid #ddd; border-radius: 8px; padding: 15px; margin-bottom: 15px; position: relative; }
.delete-row-btn { position: absolute; top: 10px; right: 10px; }
.upload-box { border: 2px dashed #ccc; border-radius: 10px; padding: 15px; text-align: center; background: #fafafa; position: relative; cursor:pointer; }
.upload-box:hover { background: #f1f1f1; }
.upload-box.disabled-child { 
    background: #e9ecef; 
    opacity: 0.6; 
    cursor: not-allowed; 
    border-color: #adb5bd;
}
.upload-box.disabled-child:hover { background: #e9ecef; }
.upload-box.parent-doc { border-color: #0d6efd; background: #f0f7ff; }
.upload-box.child-doc { border-color: #6c757d; }
.upload-box.child-doc.enabled { border-color: #198754; background: #f0fff4; }
.parent-badge { 
    position: absolute; 
    top: 5px; 
    right: 5px; 
    font-size: 0.7rem; 
    padding: 2px 6px; 
}
.child-badge {
    position: absolute;
    top: 5px;
    left: 5px;
    font-size: 0.7rem;
    padding: 2px 6px;
}
.file-actions button { margin: 3px; }
#addRowBtnFloating { position: fixed; bottom: 20px; right: 20px; z-index: 9999; border-radius: 50px; padding: 12px 20px; }
#backToDashboardBtn { position: fixed; bottom: 20px; left: 20px; z-index: 9999; border-radius: 50px; padding: 12px 20px; background: #6c757d; border-color: #6c757d; }
#loader-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255,255,255,0.7);
    z-index: 9999;

    display: flex;               /* keep flex */
    justify-content: center;     /* center horizontally */
    align-items: center;         /* center vertically */

    opacity: 0;                  /* hide instead of display:none */
    pointer-events: none;
    transition: opacity 0.2s ease-in-out;
}
.drop-overlay { position: absolute; top:0; left:0; width:100%; height:100%; background: rgba(0,123,255,0.1); display:flex; align-items:center; justify-content:center; font-weight:bold; font-size:0.9rem; pointer-events:none; display:none; }
.upload-box.dragover { border: 2px dashed #007bff; }
.mandatory-modal-body .child-doc-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 15px;
    border: 2px solid #dee2e6;
    border-radius: 8px;
    margin-bottom: 10px;
    background: #fff;
    cursor: pointer;
    transition: all 0.2s ease;
}
.mandatory-modal-body .child-doc-item:hover {
    background: #f8f9fa;
}
.mandatory-modal-body .child-doc-item.is-mandatory {
    border-color: #198754;
    background: rgba(25, 135, 84, 0.05);
}
.mandatory-modal-body .child-doc-item.is-optional {
    border-color: #dc3545;
    background: rgba(220, 53, 69, 0.05);
}
.mandatory-modal-body .form-check-input {
    width: 1.2em;
    height: 1.2em;
}
.mandatory-modal-body .form-check-input:checked {
    background-color: #198754;
    border-color: #198754;
}
.mandatory-label {
    font-size: 0.85rem;
    color: #198754;
    font-weight: 600;
}
.optional-label {
    font-size: 0.85rem;
    color: #dc3545;
    font-weight: 600;
}
.mandatory-heading {
    display: inline-block;
    padding: 6px 16px;
    border-radius: 20px;
    font-weight: 600;
    font-size: 0.9rem;
    margin-right: 10px;
}
.mandatory-heading.green {
    background: #198754;
    color: white;
}
.mandatory-heading.red {
    background: #dc3545;
    color: white;
}
</style>
 
<div class="content">
  <div class="card">
    <input type="hidden" id="company_id" value="<?= $details->id; ?>">
    <!--<div class="card-header d-flex justify-content-between align-items-center">
        <h4 class="card-title"><?= $details->company_name; ?> / Upload Documents</h4>
        <?php /* <button type="button" id="addRowBtn" class="btn btn-success btn-sm"><i class="fa fa-plus"></i> Add Row</button> */ ?>
    </div> -->
    <div class="card-body">
        <form id="uploadForm" enctype="multipart/form-data">
            <div id="rowsContainer"></div>
        </form>
    </div>
  </div>
</div>

<?php 
// Use preset values from controller (decrypted from encrypted URL or fallback to GET)
$fromDashboard = (isset($preset_authority_id) && $preset_authority_id != '') && (isset($preset_type_id) && $preset_type_id != ''); 

// Debug output (remove in production)
if (ENVIRONMENT !== 'production') {
    echo "<!-- DEBUG: preset_authority_id=" . ($preset_authority_id ?? 'NULL') . ", preset_type_id=" . ($preset_type_id ?? 'NULL') . ", fromDashboard=" . ($fromDashboard ? 'true' : 'false') . " -->";
}
?>
<button id="addRowBtnFloating" class="btn btn-primary shadow-lg" <?= $fromDashboard ? 'style="display:none;"' : '' ?>>+ Add Row</button>
<?php if (isset($preset_from) && $preset_from === 'dashboard'): ?>
<button id="backToDashboardBtn" class="btn btn-secondary shadow-lg"><i class="fa fa-arrow-left"></i> Back to Dashboard</button>
<?php endif; ?>
<div id="loader-overlay"><i class="fa fa-spinner fa-spin fa-3x"></i></div>

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

    const now = new Date();
    $('#yearSelect').val(now.getFullYear());
    $('#monthSelect').val(("0"+(now.getMonth()+1)).slice(-2));

    let entryCount = 0;
    let company_id = "<?= $details->id ?>";
    
    // Pre-selected values from dashboard (passed securely from controller)
    const preselectedAuthorityId = "<?= isset($preset_authority_id) ? $preset_authority_id : '' ?>";
    const preselectedTypeId = "<?= isset($preset_type_id) ? $preset_type_id : '' ?>";
    const preselectedMonth = "<?= isset($preset_month) ? $preset_month : '' ?>";
    const preselectedYear = "<?= isset($preset_year) ? $preset_year : '' ?>";
    const isReadonly = "<?= isset($preset_readonly) && $preset_readonly == '1' ? 'true' : 'false' ?>" === "true";
    const fromDashboard = "<?= isset($preset_from) ? $preset_from : '' ?>";
    
    // Return parameters for dashboard redirect
    const returnTab = "<?= isset($return_tab) ? $return_tab : 'favourite' ?>";
    const returnYear = "<?= isset($return_year) ? $return_year : 'all' ?>";
    const returnCompanies = "<?= isset($return_companies) ? $return_companies : '' ?>";
    
    // Back to Dashboard button handler
    $('#backToDashboardBtn').on('click', function() {
        if (fromDashboard === 'dashboard') {
            let dashboardUrl = '<?= base_url("dashboard/dashboard") ?>';
            dashboardUrl += '?year=' + returnYear;
            if (returnCompanies) {
                dashboardUrl += '&companies=' + encodeURIComponent(returnCompanies);
            }
            dashboardUrl += '&active_tab=' + returnTab;
            window.location.href = dashboardUrl;
        } else {
            window.history.back();
        }
    });
    
    // Permission flags
    const canEdit = <?= isset($can_edit) && $can_edit ? 'true' : 'false' ?>;
    const canDelete = <?= isset($can_delete) && $can_delete ? 'true' : 'false' ?>;
    
    // Debug: Log pre-selected values
    console.log("=== PRESELECTED VALUES FROM DASHBOARD ===");
    console.log("Authority ID:", preselectedAuthorityId, "(type:", typeof preselectedAuthorityId, ")");
    console.log("Type ID:", preselectedTypeId, "(type:", typeof preselectedTypeId, ")");
    console.log("Month:", preselectedMonth);
    console.log("Year:", preselectedYear);
    console.log("Readonly:", isReadonly, "(type:", typeof isReadonly, ")");
    console.log("From:", fromDashboard);
    console.log("Has preselected values:", preselectedAuthorityId !== "" && preselectedTypeId !== "");

    // Enable "Add Row" buttons immediately (don't wait for year/month)
    $("#addRowBtnFloating").prop("disabled", false);

    // NOTE: addRow() is called at the END of this script, after all handlers are registered

    // Show loader functions
    //function showLoader(){ $("#loader-overlay").fadeIn(200); }
    //function hideLoader(){ $("#loader-overlay").fadeOut(200); }

    function showLoader(){
    $("#loader-overlay")
        .css({opacity: 1, "pointer-events": "auto"});
    }

    function hideLoader(){
        $("#loader-overlay")
            .css({opacity: 0, "pointer-events": "none"});
    }
    
    // Lock Year, Month, Authority, Document Head when coming from dashboard
    function lockFieldsForDashboard(entry) {
        // Disable and style the fields
        entry.find('.yearSelect').prop('disabled', true).css({
            'background-color': '#e9ecef',
            'cursor': 'not-allowed',
            'opacity': '0.8'
        });
        entry.find('.monthSelect').prop('disabled', true).css({
            'background-color': '#e9ecef',
            'cursor': 'not-allowed',
            'opacity': '0.8'
        });
        entry.find('.authority').prop('disabled', true).css({
            'background-color': '#e9ecef',
            'cursor': 'not-allowed',
            'opacity': '0.8'
        });
        entry.find('.type').prop('disabled', true).css({
            'background-color': '#e9ecef',
            'cursor': 'not-allowed',
            'opacity': '0.8'
        });
        
        // Add a lock icon badge
        if (!entry.find('.locked-badge').length) {
            entry.prepend(`
                <div class="locked-badge alert alert-info py-2 px-3 mb-3" style="display: flex; align-items: center; gap: 10px;">
                    <i class="fa fa-lock"></i>
                    <span>Year, Month, Authority and Document Head are locked. You can only upload documents for the selected period.</span>
                </div>
            `);
        }
        
        console.log("Fields locked for dashboard upload");
    }

    // Old supportive alert removed - child documents now stay disabled until mandatory status is set

    // 🆕 Show modal to set child documents as mandatory or optional
    function showMandatoryModal(parentDocId, childDocs, typeId, month, year, entry) {
        // Build the list of sub documents with individual toggles (default: mandatory)
        let childItems = childDocs.map(child => `
            <div class="child-doc-row" data-child-id="${child.id}">
                <div class="child-doc-toggle">
                    <input type="checkbox" class="child-mandatory-check" id="child_${child.id}" data-child-id="${child.id}" checked>
                    <label for="child_${child.id}">${child.document_name}</label>
                </div>
                <span class="child-status-badge mandatory">Mandatory</span>
            </div>
        `).join('');

        Swal.fire({
            title: '<i class="fa fa-folder-tree text-primary"></i> Sub Documents',
            html: `
                <style>
                    .mandatory-quick-btns { display: flex; gap: 10px; justify-content: center; margin-bottom: 15px; }
                    .mandatory-quick-btns button { padding: 8px 20px; border-radius: 6px; border: none; cursor: pointer; font-weight: 500; transition: all 0.2s; }
                    .mandatory-quick-btns .btn-yes { background: #10b981; color: white; }
                    .mandatory-quick-btns .btn-yes:hover { background: #059669; }
                    .mandatory-quick-btns .btn-no { background: #6b7280; color: white; }
                    .mandatory-quick-btns .btn-no:hover { background: #4b5563; }
                    .child-doc-list { max-height: 250px; overflow-y: auto; border: 1px solid #e5e7eb; border-radius: 8px; padding: 10px; }
                    .child-doc-row { display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; border-radius: 6px; margin-bottom: 5px; transition: all 0.2s; cursor: pointer; }
                    .child-doc-row:last-child { margin-bottom: 0; }
                    .child-doc-row.is-mandatory { background: #d1fae5; border: 1px solid #10b981; }
                    .child-doc-row.is-optional { background: #f3f4f6; border: 1px solid #9ca3af; }
                    .child-doc-toggle { display: flex; align-items: center; gap: 10px; }
                    .child-doc-toggle input[type="checkbox"] { width: 18px; height: 18px; accent-color: #10b981; cursor: pointer; }
                    .child-doc-toggle label { cursor: pointer; font-weight: 500; color: #374151; margin: 0; }
                    .child-status-badge { padding: 3px 10px; border-radius: 12px; font-size: 0.75rem; font-weight: 600; }
                    .child-status-badge.mandatory { background: #10b981; color: white; }
                    .child-status-badge.optional { background: #9ca3af; color: white; }
                </style>
                <div class="text-start mb-3">
                    <p class="text-muted mb-2">Set sub documents as mandatory or optional for compliance.</p>
                </div>
                <div class="mandatory-quick-btns">
                    <button type="button" class="btn-yes" id="setAllMandatory"><i class="fa fa-check me-1"></i> Yes - All Mandatory</button>
                    <button type="button" class="btn-no" id="setAllOptional"><i class="fa fa-times me-1"></i> No - All Optional</button>
                </div>
                <div class="child-doc-list">
                    ${childItems}
                </div>
                <div class="mt-2 text-start">
                    <small class="text-muted"><i class="fa fa-info-circle"></i> Click on a row or checkbox to toggle individual documents.</small>
                </div>
            `,
            showCancelButton: false,
            confirmButtonText: '<i class="fa fa-save"></i> Save Settings',
            confirmButtonColor: '#0d6efd',
            allowOutsideClick: false,
            allowEscapeKey: false,
            width: '500px',
            didOpen: () => {
                // Function to update row appearance
                function updateRowAppearance(row, isMandatory) {
                    const badge = row.querySelector('.child-status-badge');
                    if (isMandatory) {
                        row.classList.remove('is-optional');
                        row.classList.add('is-mandatory');
                        badge.textContent = 'Mandatory';
                        badge.classList.remove('optional');
                        badge.classList.add('mandatory');
                    } else {
                        row.classList.remove('is-mandatory');
                        row.classList.add('is-optional');
                        badge.textContent = 'Optional';
                        badge.classList.remove('mandatory');
                        badge.classList.add('optional');
                    }
                }

                // Initialize all rows as mandatory
                document.querySelectorAll('.child-doc-row').forEach(row => {
                    updateRowAppearance(row, true);
                });

                // "Yes - All Mandatory" button
                document.getElementById('setAllMandatory').addEventListener('click', function() {
                    document.querySelectorAll('.child-mandatory-check').forEach(cb => {
                        cb.checked = true;
                        updateRowAppearance(cb.closest('.child-doc-row'), true);
                    });
                });

                // "No - All Optional" button
                document.getElementById('setAllOptional').addEventListener('click', function() {
                    document.querySelectorAll('.child-mandatory-check').forEach(cb => {
                        cb.checked = false;
                        updateRowAppearance(cb.closest('.child-doc-row'), false);
                    });
                });

                // Individual checkbox change
                document.querySelectorAll('.child-mandatory-check').forEach(cb => {
                    cb.addEventListener('change', function() {
                        updateRowAppearance(this.closest('.child-doc-row'), this.checked);
                    });
                });

                // Row click to toggle
                document.querySelectorAll('.child-doc-row').forEach(row => {
                    row.addEventListener('click', function(e) {
                        if (e.target.tagName === 'INPUT') return;
                        const cb = this.querySelector('.child-mandatory-check');
                        cb.checked = !cb.checked;
                        updateRowAppearance(this, cb.checked);
                    });
                });
            },
            preConfirm: () => {
                // Collect the mandatory status for each child
                let childMandatory = {};
                document.querySelectorAll('.child-mandatory-check').forEach(cb => {
                    childMandatory[cb.dataset.childId] = cb.checked ? 1 : 0;
                });
                return childMandatory;
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Save the mandatory status
                saveMandatoryStatus(parentDocId, result.value, typeId, month, year, entry);
            }
        });
    }

    // 🆕 Save mandatory status to server
    function saveMandatoryStatus(parentDocId, childMandatory, typeId, month, year, entry) {
        showLoader();
        
        // Debug logging
        console.log('Saving mandatory status:', {
            parent_document_id: parentDocId,
            company_id: company_id,
            type_id: typeId,
            month: month,
            year: year,
            child_mandatory: childMandatory
        });
        
        $.ajax({
            url: "<?= site_url('upload/saveChildMandatoryStatus'); ?>",
            type: "POST",
            data: {
                parent_document_id: parentDocId,
                company_id: company_id,
                type_id: typeId,
                month: month,
                year: year,
                child_mandatory: childMandatory
            },
            success: function(res) {
                hideLoader();
                console.log('Save mandatory status response:', res);
                let response = JSON.parse(res);
                
                if (response.status) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Settings Saved!',
                        text: 'Document uploaded and sub requirements configured successfully.',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        // Reload documents to reflect the changes
                        loadDocuments(entry);
                    });
                } else {
                    console.error('Save mandatory status failed:', response.error);
                    Swal.fire('Error', response.error || 'Failed to save settings', 'error');
                    loadDocuments(entry);
                }
            },
            error: function(xhr, status, error) {
                hideLoader();
                console.error('Save mandatory status AJAX error:', status, error);
                Swal.fire('Error', 'Failed to save mandatory settings', 'error');
                loadDocuments(entry);
            }
        });
    }

  // Reusable function to filter months based on selected year
function filterMonths(entry) {
    let yearSelect = entry.find('.yearSelect');
    let monthSelect = entry.find('.monthSelect');

    let selectedYear = parseInt(yearSelect.val());
    let now = new Date();
    let currentYear = now.getFullYear();
    let currentMonth = now.getMonth() + 1;
    
    // Get company start date from data attributes
    let companyStartYear = parseInt(yearSelect.data('company-start-year')) || 2024;
    let companyStartMonth = parseInt(yearSelect.data('company-start-month')) || 1;

    // Reset visibility
    monthSelect.find('option').show();

    // Apply filter for CURRENT YEAR (hide future months)
    if (selectedYear === currentYear) {
        monthSelect.find('option').each(function () {
            let val = parseInt($(this).val());
            if (val > currentMonth) {
                $(this).hide();
            }
        });
    }
    
    // Apply filter for COMPANY START YEAR (hide months before company start)
    if (selectedYear === companyStartYear) {
        monthSelect.find('option').each(function () {
            let val = parseInt($(this).val());
            if (val && val < companyStartMonth) {
                $(this).hide();
            }
        });
    }

    // Auto-fix invalid selection
    let selectedMonth = parseInt(monthSelect.val());
    
    // Fix for current year (can't select future months)
    if (selectedYear === currentYear && (selectedMonth > currentMonth || !selectedMonth)) {
        let fixed = ("0" + currentMonth).slice(-2);
        monthSelect.val(fixed);
    }
    
    // Fix for company start year (can't select months before company started)
    if (selectedYear === companyStartYear && selectedMonth < companyStartMonth) {
        let fixed = ("0" + companyStartMonth).slice(-2);
        monthSelect.val(fixed);
    }
}

    // MAIN addRow() FUNCTION
    function addRow() {
        entryCount++;

        let html = `
        <div class="upload-entry border rounded p-3 mb-4" data-entry="${entryCount}">
            <div class="row mb-3">
                <div class="col-md-6">
                    <label class="form-label">Year</label>
                    <select class="form-select yearSelect" name="year[${entryCount}]" required 
                            data-company-start-year="<?= date('Y', strtotime($company->co_start_date ?? '2024-01-01')) ?>"
                            data-company-start-month="<?= date('m', strtotime($company->co_start_date ?? '2024-01-01')) ?>">
                        <option value="">Select Year</option>
                        <?php 
                            $currentYear = date("Y");
                            // Use company start date year instead of fixed 2024
                            $startYear = $company && !empty($company->co_start_date) 
                                ? (int)date('Y', strtotime($company->co_start_date)) 
                                : 2024;
                            for ($y = $currentYear; $y >= $startYear; $y--): 
                        ?>
                            <option value="<?= $y ?>"><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Month</label>
                    <select class="form-select monthSelect" name="month[${entryCount}]" required>
                        <option value="">Select Month</option>
                        <?php 
                        $months = [
                            "01" => "January", "02" => "February", "03" => "March",
                            "04" => "April", "05" => "May", "06" => "June",
                            "07" => "July", "08" => "August", "09" => "September",
                            "10" => "October", "11" => "November", "12" => "December"
                        ];
                        foreach ($months as $num => $name): ?>
                            <option value="<?= $num ?>"><?= $name ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            ${entryCount > 1 ? `
            <button type="button" class="btn btn-danger btn-sm delete-row-btn mb-2">
                <i class="fa fa-trash"></i>
            </button>` : ''}

            <div class="row mb-3">
                <div class="col-md-6">
                    <label class="form-label">Authority</label>
                    <select class="form-select authority" name="authority[${entryCount}]">
                        <option value="">Select Authority</option>
                        <?php foreach($authorities as $a): ?>
                        <option value="<?= $a['authority_id'] ?>"><?= $a['authority_name']." (".$a['alias_name'].")" ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Document Head dd</label>
                    <select class="form-select type" name="type[${entryCount}]">
                        <option value="">Select Document Head</option>
                    </select>
                </div>
            </div>

            <div class="documents"></div>
        </div>`;

        // Append
        $("#rowsContainer").append(html);

        // Auto-select current year/month OR pre-selected from dashboard
        let now = new Date();
        let currentYear = preselectedYear || now.getFullYear();
        let currentMonth = preselectedMonth || ("0" + (now.getMonth() + 1)).slice(-2);

        let lastRow = $("#rowsContainer .upload-entry").last();
        lastRow.find(".yearSelect").val(currentYear);
        lastRow.find(".monthSelect").val(currentMonth);

        // 🔥 Apply month filtering immediately (fixes December issue)
        filterMonths(lastRow);
        
        // If authority is pre-selected, auto-select it and load types
        if (preselectedAuthorityId && entryCount === 1) {
            console.log("Auto-selecting authority:", preselectedAuthorityId);
            lastRow.find(".authority").val(preselectedAuthorityId);
            
            // Verify authority was selected
            if (lastRow.find(".authority").val() === preselectedAuthorityId) {
                console.log("Authority selected successfully, triggering change to load types");
                // Trigger change to load types
                lastRow.find(".authority").trigger('change');
            } else {
                console.log("Authority NOT found. Available:", lastRow.find(".authority option").map((i,o) => $(o).val()).get());
            }
        }

        // Smooth scroll
        $('html,body').animate({ scrollTop: lastRow.offset().top }, 500);

        updateDeleteButtons();
    }

    // When year changes → reset Month, Authority, Document Head, and clear documents
    $(document).on("change", ".yearSelect", function () {
        let entry = $(this).closest(".upload-entry");
        filterMonths(entry);
        
        // Reset dependent dropdowns
        entry.find(".monthSelect").val("");
        entry.find(".authority").val("");
        entry.find(".type").html('<option value="">Select Document Head</option>');
        
        // Clear documents and warnings
        entry.find(".documents").html('');
        entry.find(".frequency-warning").remove();
        entry.find(".upload-progress").remove();
        entry.removeData('frequencyCheck');
    });
    
    // When month changes → reset Authority, Document Head, and clear documents
    $(document).on("change", ".monthSelect", function () {
        let entry = $(this).closest(".upload-entry");
        
        // Reset dependent dropdowns
        entry.find(".authority").val("");
        entry.find(".type").html('<option value="">Select Document Head</option>');
        
        // Clear documents and warnings
        entry.find(".documents").html('');
        entry.find(".frequency-warning").remove();
        entry.find(".upload-progress").remove();
        entry.removeData('frequencyCheck');
    });

    // Load documents for a row
    function loadDocuments(entry){
        let type_id = entry.find(".type").val();
        let month = entry.find('.monthSelect').val();
        let year = entry.find('.yearSelect').val();
        let docContainer = entry.find(".documents");

        if(!type_id || !month || !year){ docContainer.html(''); return; }

        $.post("<?= site_url('upload/getDocuments'); ?>", {
            type_id, company_id, months: month, years: year
        }, function(res){
            let docs;
            try {
                docs = JSON.parse(res);
            } catch(e) {
                console.error("Failed to parse documents response:", res);
                docContainer.html('<div class="alert alert-danger">Failed to load documents</div>');
                return;
            }
            
            // Check if response is an error
            if (docs.error) {
                console.error("Error loading documents:", docs.error);
                docContainer.html('<div class="alert alert-danger">' + docs.error + '</div>');
                return;
            }
            
            // Ensure docs is an array
            if (!Array.isArray(docs)) {
                console.error("Invalid documents response:", docs);
                docContainer.html('<div class="alert alert-danger">Invalid response from server</div>');
                return;
            }
            
            docContainer.html('');
            let row = $('<div class="row"></div>');

            // Upload states
            let uploadedDocs = docs.filter(d => d.file_name);
            let uploadedCount = uploadedDocs.length;
            let totalDocs = docs.length;

            let anyUploaded = uploadedCount > 0;
            let allUploaded = uploadedCount === totalDocs;

            // ✅ Create progress bar only if not already present
            let progressContainer = entry.find(".upload-progress");

            if (progressContainer.length === 0) {
                progressContainer = $(`
                    <div class="upload-progress mb-3">
                        <label class="form-label">Upload Progress</label>
                        <div class="progress">
                            <div class="progress-bar" role="progressbar" style="width: 0%;" 
                                aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
                        </div>
                    </div>
                `);
                //entry.prepend(progressContainer);
                entry.find(".authority").closest(".row").after(progressContainer);
            }

            docs.forEach((d,i)=>{
                let uploaded = d.file_name ? true : false;
                let isParent = (d.is_parent == 1 || d.is_parent === true);
                let isChild = (d.is_child == 1 || d.is_child === true);
                let isDisabled = (d.is_disabled == 1 || d.is_disabled === true);
                
                // Debug logging for parent-child status
                if (isParent || isChild) {
                    console.log(`Document ${d.id} (${d.document_name}): isParent=${isParent}, isChild=${isChild}, isDisabled=${isDisabled}, parent_uploaded=${d.parent_uploaded}, mandatory_status_set=${d.mandatory_status_set}`);
                }
                
                let col = $('<div class="col-md-3 mb-3"></div>');
                let boxClasses = 'upload-box border p-3 text-center rounded';

                // Type label - Master or Sub (positioned top-right)
                // Sub badge: green (bg-success) if active/enabled, gray (bg-secondary) if disabled
                let typeLabel = '';
                if (isParent) {
                    typeLabel = '<span class="badge bg-primary position-absolute" style="top:5px;right:5px;font-size:10px;">Master</span>';
                } else if (isChild) {
                    let subBadgeClass = isDisabled ? 'bg-secondary' : 'bg-success';
                    typeLabel = `<span class="badge ${subBadgeClass} position-absolute" style="top:5px;right:5px;font-size:10px;">Sub</span>`;
                }

                // Show upload button - disabled for child documents until parent uploaded & mandatory set
                // Also check edit permission
                let uploadBtnHtml = '';
                if (!uploaded && canEdit) {
                    if (isChild && isDisabled) {
                        uploadBtnHtml = '<button type="button" class="btn btn-secondary btn-sm" disabled><i class="fa fa-upload"></i> Upload</button>';
                    } else {
                        uploadBtnHtml = '<button type="button" class="btn btn-primary btn-sm uploadNew"><i class="fa fa-upload"></i> Upload</button>';
                    }
                } else if (!uploaded && !canEdit) {
                    uploadBtnHtml = '<span class="badge bg-warning text-dark">View Only</span>';
                }

                col.append(`<div class="${boxClasses} position-relative" data-doc-id="${d.id}">
                    ${typeLabel}
                    <strong>${d.document_name}</strong><br>
                    ${uploaded ? `<span class="badge bg-success mb-1">Uploaded</span><br><a href="<?= base_url() ?>${d.file_path}" target="_blank">${d.file_name}</a>` : ''}
                    <input type="file" class="file-input d-none" accept="application/pdf" ${isDisabled ? 'disabled' : ''}/>
                    <div class="file-actions mt-2">
                        ${uploadBtnHtml}
                    </div>
                    <div class="drop-overlay border border-primary rounded p-3 mt-2 text-muted" style="display:none;">Drag & Drop File Here</div>
                    <small class="text-muted d-block mt-3">PDF only, max 10MB</small>
                </div>`);
                
                row.append(col);
                if((i+1)%4==0){ docContainer.append(row); row=$('<div class="row"></div>'); }
            });

            if(row.children().length>0){ docContainer.append(row); }
            
            // Initialize drag/drop
            initDragDrop(docContainer);

            // ✅ Update progress bar
            //let totalDocs = docs.length;
            //let uploadedCount = docs.filter(d => d.file_name).length;
            let progressPercent = Math.round((uploadedCount / totalDocs) * 100);
            progressContainer.find(".progress-bar")
                .css("width", progressPercent + "%")
                .attr("aria-valuenow", progressPercent)
                .text(progressPercent + "%");

            // ✅ Disable dropdowns only if any document is uploaded in this row
            if(anyUploaded){
                entry.find('.yearSelect, .monthSelect, .authority, .type').prop('disabled', true);
            } else {
                entry.find('.yearSelect, .monthSelect, .authority, .type').prop('disabled', false);
            }

            // If all documents are uploaded, show message before replacing with new row
            if(allUploaded){
                Swal.fire({
                    icon: 'success',
                    title: 'All documents uploaded!',
                    text: 'This entry has all documents uploaded. A new upload entry will be created.',
                    confirmButtonText: 'OK'
                }).then(() => {
                    entry.remove(); // remove the current row
                    addRow();       // add new blank row
                    updateDeleteButtons(); 
                });
            }
        });
    }

    // Drag & drop / file upload handling
    function initDragDrop(container){
        container.find(".upload-box").each(function(){
            let box = $(this), fileInput = box.find(".file-input"), overlay = box.find(".drop-overlay");
            
            // Check if this is a disabled child document (has 'disabled-child' class)
            let isDisabledChild = box.hasClass('disabled-child');
            
            box.find(".uploadNew").off("click").on("click", function(){
                // Re-check in case class changed dynamically
                if (box.hasClass('disabled-child')) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Parent Document Required',
                        text: 'Please upload the parent document first before uploading this sub document.',
                        confirmButtonText: 'OK'
                    });
                    return;
                }
                fileInput.trigger("click");
            });
            
            box.on("dragover", e=>{ 
                e.preventDefault(); 
                if (!box.hasClass('disabled-child')) overlay.show(); 
            });
            box.on("dragleave", e=>{ e.preventDefault(); overlay.hide(); });
            box.on("drop", e=>{
                e.preventDefault(); overlay.hide();
                if (box.hasClass('disabled-child')) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Parent Document Required',
                        text: 'Please upload the parent document first before uploading this sub document.',
                        confirmButtonText: 'OK'
                    });
                    return;
                }
                let files = e.originalEvent.dataTransfer.files;
                if(files.length>0){ fileInput[0].files = files; fileInput.trigger("change"); }
            });

            fileInput.off("change").on("change", function(){
                let file = this.files[0]; if(!file) return;
                let entry = box.closest(".upload-entry");
                //let month = $('#monthSelect').val(), year = $('#yearSelect').val();
                let month = entry.find('.monthSelect').val(), year = entry.find('.yearSelect').val();
                let formData = new FormData();
                formData.append("file", file);
                formData.append("company_id", company_id);
                formData.append("type_id", entry.find(".type").val());
                formData.append("document_id", box.data("doc-id"));
                formData.append("month", month); formData.append("year", year);

                showLoader();
                $.ajax({
                    url:"<?= site_url('upload/doUpload'); ?>",
                    type:"POST",
                    data:formData,
                    processData:false,
                    contentType:false,
                    success:function(res){
                        hideLoader();
                        let response = JSON.parse(res);
                        if(response.status){
                            // Check if this is a parent document that needs mandatory setup
                            if (response.needs_mandatory_setup && response.child_docs && response.child_docs.length > 0) {
                                showMandatoryModal(
                                    response.document_id,
                                    response.child_docs,
                                    entry.find(".type").val(),
                                    month,
                                    year,
                                    entry
                                );
                            } else {
                                Swal.fire({icon:'success', title:'File uploaded!', timer:1200, showConfirmButton:false});
                                // reload documents
                                loadDocuments(entry);
                            }
                        } else {
                            // Check if this is a frequency-related error
                            if (response.frequency_error) {
                                Swal.fire({
                                    icon: 'warning',
                                    title: 'Upload Not Allowed',
                                    html: response.error,
                                    confirmButtonText: 'OK'
                                });
                            } else {
                                Swal.fire("❌ Error", response.error, "error");
                            }
                        }
                    },
                    error:function(){ hideLoader(); Swal.fire("❌ Error", "Upload failed.", "error"); }
                });
            });
        });
    }

    // Event bindings
    $("#addRowBtn, #addRowBtnFloating").on("click", addRow);

    $("#monthSelect, #yearSelect").on("change", function(){
        //let month = $('#monthSelect').val(), year = $('#yearSelect').val();
        let month =  entry.find('.monthSelect').val(), year = entry.find(".yearSelect").val();
        if(month && year){
            $("#addRowBtn, #addRowBtnFloating").prop("disabled", false);
            if(entryCount===0){ $("#addRowBtn").trigger("click"); }
            $("#rowsContainer .upload-entry").each(function(){ loadDocuments($(this)); });
        }
    });

    $(document).on("change", ".authority", function(){
        let authority_id = $(this).val(), entry = $(this).closest(".upload-entry"), typeSelect = entry.find(".type"),
           company_id = $("#company_id").val(); // 👈 assuming you have a hidden/input field for company
        let month =  entry.find('.monthSelect').val(), year = entry.find(".yearSelect").val();
        
        // Reset Document Head and clear documents when Authority changes
        typeSelect.html('<option value="">Select Document Head</option>');
        entry.find(".documents").html('');
        entry.find(".frequency-warning").remove();
        entry.find(".upload-progress").remove();
        entry.removeData('frequencyCheck');
        
        console.log("=== AUTHORITY CHANGE HANDLER ===");
        console.log("Authority ID:", authority_id);
        console.log("Company ID:", company_id);
        console.log("Month:", month, "Year:", year);
        
        if(authority_id){
            console.log("Making AJAX call to getTypes...");
            $.ajax({
                url: "<?= site_url('upload/getTypes'); ?>",
                type: "POST",
                data: {authority_id: authority_id, company_id: company_id, month: month, year: year},
                success: function(res){
                    console.log("===== RAW TYPES RESPONSE =====");
                    console.log("Response:", res);
                    
                    let types;
                    try {
                        types = JSON.parse(res);
                    } catch(e) {
                        console.error("JSON Parse Error:", e);
                        console.log("Raw response was:", res);
                        return;
                    }
                    
                    console.log("Parsed types:", types);
                    console.log("Number of types:", types.length);

                    typeSelect.html('<option value="">Select Document Head</option>');
                    
                    types.forEach(t => {
                        console.log("Adding TYPE:", t.id, t.type_name); 
                        // ⭐ Include Alias (if available)
                        let label = t.alias_name
                            ? `${t.type_name} (${t.alias_name})`   // Name + Alias
                            : t.type_name;                    // Only Name if alias empty

                        typeSelect.append(`
                            <option 
                                value="${t.id}"
                                data-auth="${t.authority_id}"
                                data-frequency="${t.frequency}"
                                data-start="${t.document_start_date}"
                            >
                                ${label}
                            </option>
                        `);
                    });
                    
                    // Auto-select type if pre-selected from dashboard
                    console.log("=== TYPE PRE-SELECTION ===");
                    console.log("preselectedTypeId:", preselectedTypeId, "type:", typeof preselectedTypeId);
                    console.log("entry number:", entry.data("entry"), "type:", typeof entry.data("entry"));
                    
                    if (preselectedTypeId && parseInt(entry.data("entry")) === 1) {
                        console.log("Attempting to auto-select type:", preselectedTypeId);
                        
                        // List all available option values
                        let availableOptions = typeSelect.find('option').map((i,o) => ({val: $(o).val(), text: $(o).text().trim()})).get();
                        console.log("Available options:", availableOptions);
                        
                        // Set the value
                        typeSelect.val(preselectedTypeId);
                        
                        // Check if it was set correctly (compare as strings)
                        let selectedVal = typeSelect.val();
                        console.log("After setting - selected value:", selectedVal, "type:", typeof selectedVal);
                        
                        if (selectedVal && selectedVal.toString() === preselectedTypeId.toString()) {
                            console.log("✓ Type selected successfully, triggering change to load documents");
                            typeSelect.trigger('change');
                            
                            // Lock fields if readonly mode (from dashboard)
                            if (isReadonly) {
                                console.log("Locking fields in readonly mode");
                                setTimeout(function() {
                                    lockFieldsForDashboard(entry);
                                }, 500);
                            }
                        } else {
                            console.log("✗ Type NOT found or not selected. Selected:", selectedVal, "Expected:", preselectedTypeId);
                        }
                    } else {
                        console.log("Skipping auto-select: preselectedTypeId=" + preselectedTypeId + ", entryNum=" + entry.data("entry"));
                    }
                },
                error: function(xhr, status, error) {
                    console.error("=== AJAX ERROR ===");
                    console.error("Status:", status);
                    console.error("Error:", error);
                    console.error("Response:", xhr.responseText);
                }
            });
            setTimeout(() => restrictDuplicateCombinations(), 200);
        } else { typeSelect.html('<option value="">Select Document Head</option>'); }
    });

    //$(document).on("change", ".type", function(){ restrictDuplicateCombinations(); loadDocuments($(this).closest(".upload-entry")); });
    $(document).on("change", ".type", function () {

    let entry = $(this).closest(".upload-entry");
    let opt = $(this).find("option:selected");
    let typeSelect = $(this);

    let selectedAuth = entry.find(".authority").val();
    let selectedType = $(this).val();
    let selectedYear = entry.find(".yearSelect").val();
    let selectedMonth = entry.find(".monthSelect").val();
    let currentRowId = entry.data("entry");

    let frequency = opt.data("frequency");
    let rawStart = opt.data("start"); 
    let startDate = opt.attr("data-start") || opt.data("start") || "";

    console.log("Final startDate =", startDate);
    
    if (!selectedAuth || !selectedType || !selectedYear || !selectedMonth) return;

    // 🔍 Check if due based on frequency (server-side validation)
    // Show all documents but display warning if not due - validation happens at upload time
    showLoader();
    $.ajax({
        url: "<?= site_url('upload/checkUploadAllowed'); ?>",
        type: "POST",
        data: {
            company_id: company_id,
            type_id: selectedType,
            month: selectedMonth,
            year: selectedYear
        },
        success: function(res) {
            hideLoader();
            let response;
            try {
                response = JSON.parse(res);
            } catch(e) {
                console.error("Failed to parse frequency check response:", res);
                checkDuplicatesAndLoad(entry, typeSelect, selectedAuth, selectedType, selectedYear, selectedMonth, currentRowId, null);
                return;
            }
            
            console.log("Frequency check result:", response);
            console.log("Status:", response.status, "Allowed:", response.allowed);
            if (response.doc_start_date) {
                console.log("Document start date:", response.doc_start_date);
            }
            
            // Store the frequency check result in entry data for later use
            entry.data('frequencyCheck', response);
            
            // Proceed with duplicate check and load documents
            // Pass the frequency check result to show warning if needed
            checkDuplicatesAndLoad(entry, typeSelect, selectedAuth, selectedType, selectedYear, selectedMonth, currentRowId, response);
        },
        error: function(xhr, status, error) {
            hideLoader();
            console.error("Frequency check failed:", error);
            // Proceed anyway on error
            checkDuplicatesAndLoad(entry, typeSelect, selectedAuth, selectedType, selectedYear, selectedMonth, currentRowId, null);
        }
    });
    });
    
    // Helper function for duplicate check and document loading
    function checkDuplicatesAndLoad(entry, typeSelect, selectedAuth, selectedType, selectedYear, selectedMonth, currentRowId, frequencyCheck) {

    // Remove any existing frequency warning and due date info
    entry.find('.frequency-warning').remove();
    entry.find('.due-date-info').remove();
    
    // Handle all "not allowed" statuses with appropriate popups
    if (frequencyCheck && frequencyCheck.allowed === false) {
        let iconType = 'warning';
        let titleText = 'Cannot Upload';
        let confirmColor = '#f0ad4e';
        
        // Customize based on status
        if (frequencyCheck.status === 'one_time_uploaded') {
            iconType = 'error';
            titleText = 'Already Uploaded';
            confirmColor = '#dc3545';
        } else if (frequencyCheck.status === 'not_due') {
            titleText = 'Document Not Due';
        } else if (frequencyCheck.status === 'before_start') {
            titleText = 'Period Not Available';
        }
        
        let messageHtml = frequencyCheck.message;
        if (frequencyCheck.next_due) {
            messageHtml += `<br><br><strong>Next Due:</strong> ${frequencyCheck.next_due}`;
        }
        
        Swal.fire({
            icon: iconType,
            title: titleText,
            html: messageHtml,
            confirmButtonText: 'OK',
            confirmButtonColor: confirmColor
        });
        
        // Reset the document head selection
        typeSelect.val("");
        entry.find(".documents").html('');
        entry.find(".upload-progress").remove();
        entry.removeData('frequencyCheck');
        return; // Don't proceed with loading documents
    }
    
    // Show popup ONLY if ALL documents are uploaded (not for partial uploads)
    if (frequencyCheck && frequencyCheck.status === 'all_uploaded') {
        Swal.fire({
            icon: 'info',
            title: 'All Documents Uploaded',
            html: `${frequencyCheck.message}<br><br>You can view or modify the uploaded documents below.`,
            confirmButtonText: 'OK',
            confirmButtonColor: '#17a2b8'
        });
    }
    // No popup for partial uploads - just load documents silently
    
    // Show adjusted due date info only if adjusted due to Sunday/Holiday (not natural month-end)
    else if (frequencyCheck && frequencyCheck.allowed && frequencyCheck.status === 'due' && frequencyCheck.adjusted_reason) {
        let infoMsg = `<strong>Due Date:</strong> ${frequencyCheck.adjusted_due_formatted} <small class="text-muted">(${frequencyCheck.adjusted_reason})</small>`;
        
        let infoBanner = `
            <div class="due-date-info alert alert-info py-2 px-3 mb-3" style="display: flex; align-items: center; gap: 10px;">
                <i class="fa fa-info-circle"></i>
                <span>${infoMsg}</span>
            </div>
        `;
        entry.find('.documents').before(infoBanner);
    }

    let duplicateFound = false;

    // Check all OTHER rows
    $(".upload-entry").each(function () {
            let rowEntry = $(this);
            let rowId = rowEntry.data("entry");

            if (rowId === currentRowId) return; // skip current row

            let rowAuth = rowEntry.find(".authority").val();
            let rowType = rowEntry.find(".type").val();
            let rowYear = rowEntry.find(".yearSelect").val();
            let rowMonth = rowEntry.find(".monthSelect").val();

            if (!rowAuth || !rowType || !rowYear || !rowMonth) return;

            // ❌ Block only if ALL FOUR match
            if (
                rowAuth == selectedAuth &&
                rowType == selectedType &&
                rowYear == selectedYear &&
                rowMonth == selectedMonth
            ) {
                duplicateFound = true;
            }
        });

        if (duplicateFound) {
            typeSelect.val(""); // reset user selection

            Swal.fire({
                icon: "warning",
                title: "Duplicate Combination",
                text: "This Authority + Document Head already exists for the same Year and Month.",
                confirmButtonText: "OK"
            });

            restrictDuplicateCombinations();
            return;
        }

        // 👍 Allowed — because month or year are different
        restrictDuplicateCombinations();
        loadDocuments(entry);
    }

    $(document).on("click", ".delete-row-btn", function(){
        let row = $(this).closest(".upload-entry");
        Swal.fire({
            title:'Are you sure?', 
            text:"This row will be removed!", 
            icon:'warning', 
            showCancelButton:true, 
            confirmButtonText:'Yes, delete it!'
        }).then(result=>{ 
                if (result.isConfirmed) {
                row.fadeOut(400, () => {
                    row.remove();
                    updateDeleteButtons();   // 👈 ADD THIS HERE
                });
            }
        });
    });

    // ✅ NOW call addRow() - AFTER all event handlers are registered
    console.log("=== All handlers registered, now calling addRow() ===");
    addRow();

});

function updateDeleteButtons(){
    let rows = $(".upload-entry");

    if(rows.length === 1){
        rows.find(".delete-row-btn").hide();   // hide delete on the only block
    } else {
        rows.find(".delete-row-btn").show();   // show delete on all
        rows.first().find(".delete-row-btn").hide(); // but hide first block
    }
}

function getUsedCombinations(){
    let used = [];
    $(".upload-entry").each(function(){
        let auth = $(this).find(".authority").val();
        let type = $(this).find(".type").val();
        if(auth && type){
            used.push(auth + "-" + type);
        }
    });
    return used;
}

function restrictDuplicateCombinations(){
    let used = getUsedCombinations();

    $(".upload-entry").each(function(){
        let entry = $(this);
        let selectedAuth = entry.find(".authority").val();
        let selectedType = entry.find(".type").val();

        entry.find(".type option").each(function(){

            let optType = $(this).val();
            if(!optType) return;

            // Get REAL authority from option
            let optAuth = $(this).data("auth");

            if(!optAuth) return;

            let combo = optAuth + "-" + optType;

            // Disable if combination already used and not the one selected in this row
            if(used.includes(combo) && !(optType == selectedType && optAuth == selectedAuth)){
                $(this).prop("disabled", true);
            } else {
                $(this).prop("disabled", false);
            }
        });
    });
}

/*function getNextDueDate(frequency, selectedMonth, selectedYear) {

    console.log("---- getNextDueDate DEBUG ----");
    console.log("frequency =", frequency);
    console.log("selectedMonth (raw) =", selectedMonth);
    console.log("selectedYear (raw) =", selectedYear);

    // 🔥 Fixed Base Start Date
    const baseStart = new Date(2024, 0, 1); // 1 Jan 2024

    // Convert selectedMonth to 0–11
    selectedMonth = selectedMonth - 1;

    // Base indexes
    let baseVal = baseStart.getFullYear() * 12 + baseStart.getMonth();

    // Selected date index
    let selVal = selectedYear * 12 + selectedMonth;
    
    // Difference in months between selection and base
    let diff = selVal - baseVal;
    if (diff < 0) diff = 0; // Don't go backward

    let nextDiff = 0;

    switch (frequency.toLowerCase()) {
        case "monthly":
            nextDiff = diff + 1;
            break;

        case "quarterly":
            nextDiff = diff + (3 - (diff % 3));
            break;

        case "half yearly":
            nextDiff = diff + (6 - (diff % 6));
            break;

        case "yearly":
            nextDiff = diff + (12 - (diff % 12));
            break;

        case "one time":
            return "Completed (One Time)";
    }

    // Calculate Next Due (in monthIndex form)
    let nextMonthIndex = (baseVal + nextDiff) % 12;
    let nextYear = Math.floor((baseVal + nextDiff) / 12);

    // Build date
    let nextDate = new Date(nextYear, nextMonthIndex, 1);

    return `${nextDate.toLocaleString("default", { month: "long" })} ${nextYear}`;
}

function isDueThisMonth(frequency, startDate, selectedMonth, selectedYear) {

    // 🔥 NEW: Fixed base start date for ALL frequency types
    //const baseStart = new Date(2024, 0, 1); // 1 Jan 2024
    const baseStart = startDate;

    selectedMonth = selectedMonth - 1;

    console.log("---- DEBUG ----");
    console.log("frequency =", frequency);
    console.log("BASE START =", baseStart);
    console.log("Document START =", baseStart);
    console.log("selectedMonth =", selectedMonth, "(0-based)");
    console.log("selectedYear =", selectedYear);
    
    let d = new Date(startDate);
    let baseM = d.getMonth();   // 0 (Jan)
    let baseY = d.getFullYear();

    let sVal = selectedYear * 12 + selectedMonth;
    let stVal = baseY * 12 + baseM;

    let diff = sVal - stVal;
    console.log("diff =", diff);

    if (diff < 0) {
        console.log("❌ BEFORE BASE DATE → NOT DUE");
        return false;
    }

    switch (frequency.toLowerCase()) {

        case "one time":
            console.log("Case: one time");
            // Only due if month & year match
            return diff === 0;

        case "monthly":
            console.log("Case: monthly");
            // Always due every month
            return true;

        case "yearly":
            console.log("Case: yearly");
            // Due every year in same month
            return diff % 12 === 0;

        case "quarterly":
            console.log("Case: quarterly");
            // Diff in months from start to now            
            return diff % 3 === 0;

        case "half yearly":
            console.log("Case: half year");
            return diff % 6 === 0;

        default:
            console.log("Case: degault");
            return false;
    }
}*/

</script>
