<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; }
.file-actions button { margin: 3px; }
#addRowBtnFloating { position: fixed; bottom: 20px; right: 20px; z-index: 9999; border-radius: 50px; padding: 12px 20px; }
#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; }
</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>

<button id="addRowBtnFloating" class="btn btn-primary shadow-lg">+ Add Row</button>
<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 (query parameters)
    const preselectedAuthorityId = "<?= $this->input->get('authority_id') ?? '' ?>";
    const preselectedTypeId = "<?= $this->input->get('type_id') ?? '' ?>";
    const preselectedMonth = "<?= $this->input->get('month') ?? '' ?>";
    const preselectedYear = "<?= $this->input->get('year') ?? '' ?>";

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

    // Automatically create the first row when page loads
    addRow();

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

    // ✅ Show supportive alert only if main document is uploaded
    function showSupportiveAlert(docs){
        let alerts = [];
        docs.forEach(main => {
            if(main.has_supportive_docs && main.file_name){ // only if main uploaded
                let missing = main.supportive_docs.filter(s => !s.file_name);
                if(missing.length > 0){
                    alerts.push(`<b>${main.document_name}</b>: ${missing.map(s => s.document_name).join(", ")}`);
                }
            }
        });
        if(alerts.length > 0){
            Swal.fire({
                icon:'warning',
                title:'Supportive Documents Missing',
                html: alerts.join('<br>'),
                confirmButtonText:'OK'
            });
        }
    }

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

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

    // Apply filter only for CURRENT YEAR
    if (selectedYear === currentYear) {
        monthSelect.find('option').each(function () {
            let val = parseInt($(this).val());
            if (val > currentMonth) {
                $(this).hide();
            }
        });
    }

    // Auto-fix invalid selection
    let selectedMonth = parseInt(monthSelect.val());
    if (selectedYear === currentYear && (selectedMonth > currentMonth || !selectedMonth)) {
        let fixed = ("0" + currentMonth).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>
                        <option value="">Select Year</option>
                        <?php 
                            $currentYear = date("Y");
                            $startYear = 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</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) {
            lastRow.find(".authority").val(preselectedAuthorityId);
            // Trigger change to load types
            lastRow.find(".authority").trigger('change');
        }

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

        updateDeleteButtons();
    }

    // When year changes → re-filter months
    $(document).on("change", ".yearSelect", function () {
        filterMonths($(this).closest(".upload-entry"));
    });

    // 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 = JSON.parse(res);
            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 mandatoryMark = d.has_supportive_docs ? ' <span class="text-danger">*</span>' : '';
                let col = $('<div class="col-md-3 mb-3"></div>');

                col.append(`<div class="upload-box border p-3 text-center rounded" data-doc-id="${d.id}">
                    <strong>${d.document_name}${mandatoryMark}</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"/>
                    <div class="file-actions mt-2">
                        ${uploaded ? '' : '<button type="button" class="btn btn-primary btn-sm uploadNew"><i class="fa fa-upload"></i> Upload</button>'}
                        <!--<button type="button" class="btn btn-primary btn-sm uploadNew"><i class="fa fa-upload"></i>${uploaded?" Modify":" Upload"}</button>-->
                    </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); }
            initDragDrop(docContainer);

            // ✅ Show supportive alert after rendering
            showSupportiveAlert(docs);

            // ✅ 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");
            box.find(".uploadNew").off("click").on("click", ()=>fileInput.trigger("click"));
            box.on("dragover", e=>{ e.preventDefault(); overlay.show(); });
            box.on("dragleave", e=>{ e.preventDefault(); overlay.hide(); });
            box.on("drop", e=>{
                e.preventDefault(); overlay.hide();
                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){
                            Swal.fire({icon:'success', title:'File uploaded!', timer:1200, showConfirmButton:false});
                            // reload documents
                            $.post("<?= site_url('upload/getDocuments'); ?>", {
                                type_id: entry.find(".type").val(),
                                company_id,
                                months: month,
                                years: year
                            }, function(r){
                                let updatedDocs = JSON.parse(r);
                                loadDocuments(entry); // re-render
                                setTimeout(()=>showSupportiveAlert(updatedDocs), 500);
                            });
                        } 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();
        if(authority_id){
            $.post("<?= site_url('upload/getTypes'); ?>", {authority_id: authority_id,company_id: company_id,month:month,year:year}, function(res){
                let types = JSON.parse(res);

                console.log("===== RAW TYPES RESPONSE =====");
                console.log(types);

                typeSelect.html('<option value="">Select Document Head</option>');
                //types.forEach(t=>typeSelect.append('<option value="'+t.id+'">'+t.type_name+'</option>'));
                /*types.forEach(t=> 
                    //typeSelect.append('<option data-auth="'+ t.authority_id +'" value="'+ t.id +'">'+ t.type_name +'</option>')
                    typeSelect.append(`<option value="${t.id}" data-auth="${t.authority_id}" data-frequency="${t.frequency}" data-start="${t.frequency_start_date}">${t.type_name} </option>`)
                ); */
                    types.forEach(t => {

                    console.log("TYPE ROW:", t); 
                    // ⭐ 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
                if (preselectedTypeId && entry.data("entry") === 1) {
                    typeSelect.val(preselectedTypeId);
                    // Trigger change to load documents
                    typeSelect.trigger('change');
                }
            });
            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 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") || "";

    // Check if rawStart already contains a year using regex (ends with -YYYY)
    /*if (/-(19|20)\d{2}$/.test(rawStart)) {
        // Already contains year → use as-is
        startDate = rawStart;
    } else {
        // No year present → append selected year
        startDate = rawStart + "-" + selectedYear;
    }*/

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

    // 🔍 Check if due this month
    /*if (!isDueThisMonth(frequency, startDate,selectedMonth,selectedYear)) {

        let dueMonth = getNextDueDate(frequency, selectedMonth, selectedYear);

        Swal.fire({
            icon: "warning",
            title: "Not Due This Month",
            html: `This document is not due in the current month.<br><br>
                   <b>Next Due:</b> ${dueMonth}`
        });

        $(this).val(""); // reset selection
        return;
    }*/

    let duplicateFound = false;

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

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

            let rowAuth = $(this).find(".authority").val();
            let rowType = $(this).find(".type").val();
            let rowYear = $(this).find(".yearSelect").val();
            let rowMonth = $(this).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) {
            $(this).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
                });
            }
        });
    });

});

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>
