<datalist id="fixedSuggestions">
    <?php
        $result = mysqli_query($db, "SELECT * FROM `suggestions` WHERE `sug_for`='Fixed' ");
        while($row = mysqli_fetch_assoc($result)){
            echo '<option value="'.$row['title'].'"></option>';
        }
    ?>
</datalist>
<datalist id="addOnSuggestions">
    <?php
        $result = mysqli_query($db, "SELECT * FROM `suggestions` WHERE `sug_for`='Add On' ");
        while($row = mysqli_fetch_assoc($result)){
            echo '<option value="'.$row['title'].'"></option>';
        }
    ?>
</datalist>
<datalist id="deductionSuggestions">
    <?php
        $result = mysqli_query($db, "SELECT * FROM `suggestions` WHERE `sug_for`='Deduction' ");
        while($row = mysqli_fetch_assoc($result)){
            echo '<option value="'.$row['title'].'"></option>';
        }
    ?>
</datalist>

<script>
    // helper to dispatch a native input event (with fallback)
    function triggerNativeInput($el, trigger_name) {
        const el = $el && $el.get ? $el.get(0) : $el;
        if (!el) return;
        let ev;
        try {
            ev = new InputEvent(trigger_name, { bubbles: true, cancelable: true });
        } catch (err) {
            ev = document.createEvent('Event');
            ev.initEvent(trigger_name, true, true);
        }
        el.dispatchEvent(ev);
    }
   $(document).on('input', '.yearlyValue', function () {
        if ($(this).data('updating')) return; // prevent loop
        let salary_value = $(this).val().replaceAll(/[^\d]/g, '');
        let yearlyValue = parseFloat(salary_value) || 0;
        let monthlyValue = Math.ceil(yearlyValue / 12);

        let $monthly = $(this).siblings('.monthlyValue');
        $monthly.data('updating', true).val(monthlyValue);
        triggerNativeInput($monthly, 'input'); // trigger native input event for formatting
        $monthly.removeData('updating');
    });

    $(document).on('input', '.monthlyValue', function () {
        if ($(this).data('updating')) return; // prevent loop
        let salary_value = $(this).val().replaceAll(/[^\d]/g, '');
        let monthlyValue = parseFloat(salary_value) || 0;
        let yearlyValue = monthlyValue * 12;

        let $yearly = $(this).siblings('.yearlyValue');
        $yearly.data('updating', true).val(yearlyValue);
        triggerNativeInput($yearly, 'input'); // trigger native input event for formatting
        $yearly.removeData('updating');
    });

    $(document).on("input", ".fixed_pay, .addOn_pay, .deduction_pay", function() {
        let total_fixed_yearly = 0;
        let total_addon_yearly = 0;
        let total_deduction_yearly = 0;

        $(".fixed_pay").each(function() {
            let val = $(this).val().replaceAll(/[^\d]/g, '');
            total_fixed_yearly += parseFloat(val) || 0;
        });

        $(".addOn_pay").each(function() {
            let val = $(this).val().replaceAll(/[^\d]/g, '');
            total_addon_yearly += parseFloat(val) || 0;
        });

        $(".deduction_pay").each(function() {
            let val = $(this).val().replaceAll(/[^\d]/g, '');
            total_deduction_yearly += parseFloat(val) || 0;
        });

        let ctcYearly = total_fixed_yearly + total_addon_yearly;
        let netPayableYearly = total_fixed_yearly - total_deduction_yearly;

        let ctcMonthly = Math.ceil(ctcYearly / 12);
        let netPayableMonthly = Math.ceil(netPayableYearly / 12);

        $('#ctcYearly').data('updating', true).val(ctcYearly);
        triggerNativeInput($('#ctcYearly'), 'input'); // trigger native input event for formatting
        $('#ctcYearly').removeData('updating');

        $('#ctcMonthly').data('updating', true).val(ctcMonthly);
        triggerNativeInput($('#ctcMonthly'), 'input'); // trigger native input event for formatting
        $('#ctcMonthly').removeData('updating');

        $('#netPayableYearly').data('updating', true).val(netPayableYearly);
        triggerNativeInput($('#netPayableYearly'), 'input'); // trigger native input event for formatting
        $('#netPayableYearly').removeData('updating');

        $('#netPayableMonthly').data('updating', true).val(netPayableMonthly);
        triggerNativeInput($('#netPayableMonthly'), 'input'); // trigger native input event for formatting
        $('#netPayableMonthly').removeData('updating');
    });

    <?php if(isset($_GET['edit'])){ ?>
        setTimeout(()=>{
            $('.yearlyValue').trigger('input');
        }, 1000)
    <?php } ?>

    function populateSalaryFields(container_id, type, data=null){
        $(`#${container_id}`).append(`<div class="d-flex gap-1 mb-2">
                <input type="text" name="${type}Title[]" placeholder="Enter Title" class="form-control" list="${type}Suggestions" value="${data?.title??''}">
                <input type="text" name="${type}Monthly[]" placeholder="Enter Monthly Amount" class="form-control monthlyValue indianCurrencyFormat" value="">
                <input type="text" name="${type}Yearly[]" placeholder="Enter Yearly Amount" class="form-control yearlyValue indianCurrencyFormat ${type}_pay" value="${data?.yearly_amount??''}">
                <button type="button" class="btn btn-danger mb-1 remove-${type}"><i class="uil-minus"></i></button>
            </div>`);
    }

    $(document).on("click", ".add-fixed", function() {
        populateSalaryFields('employee_salary_fixed', 'fixed');
    });
    $(document).on("click", ".add-addOn", function() {
        populateSalaryFields('employee_salary_addOn', 'addOn');
    });

    $(document).on("click", ".add-deduction", function() {
        populateSalaryFields('employee_salary_deduction', 'deduction');
    });

    $(document).on("click", ".remove-addOn, .remove-deduction, .remove-fixed", function() {
        $(this).parent().remove();
    });

    function handle_salary_for_populate(salary_data, from_element_value=false){

        if(from_element_value){
            salary_data = JSON.parse(decodeURIComponent(salary_data));
        }

        console.log(salary_data);

        let fixed = JSON.parse(salary_data.fixed || '[]');
        let addOn = JSON.parse(salary_data.add_on || '[]');
        let deduction = JSON.parse(salary_data.deduction || '[]');

        $('#ctcYearly').data('updating', true).val(salary_data.ctc);
        triggerNativeInput($('#ctcYearly'), 'input'); // trigger native input event for formatting
        $('#ctcYearly').removeData('updating');
        $('#netPayableYearly').data('updating', true).val(salary_data.net_payable);
        triggerNativeInput($('#netPayableYearly'), 'input'); // trigger native input event for formatting
        $('#netPayableYearly').removeData('updating');

        if(fixed && fixed.length>0){
            $('#employee_salary_fixed').html('');
            fixed.forEach(item=>{
                populateSalaryFields('employee_salary_fixed', 'fixed', item);
            });
        }

        if(addOn && addOn.length>0){
            $('#employee_salary_addOn').html('');
            addOn.forEach(item=>{
                populateSalaryFields('employee_salary_addOn', 'addOn', item);
            });
        }

        if(deduction && deduction.length>0){
            $('#employee_salary_deduction').html('');
            deduction.forEach(item=>{
                populateSalaryFields('employee_salary_deduction', 'deduction', item);
            });
        }

        $('#editSalaryId').val(salary_data.id);
        $('#revisionDate')?.val(salary_data.revision_start_date ?? '');
        $('#revisionOldDate')?.val(salary_data.revision_start_date ?? '');
        $('#revisionEndDate')?.val(salary_data.revision_end_date ?? '');

        setTimeout(()=>{
            $('.yearlyValue').trigger('input');
        }, 1000);   
    }

    <?php if(isset($_GET['edit'])) { ?>
        handle_salary_for_populate(<?php echo json_encode($salary_data); ?>);
    <?php } ?>

    $(document).on('change', 'input[name="selected_salary"]', function() {
        $('#what_do_options').show();
    });


    function show_old_salaries(res) {
        let user_data = res.user_data;
        let salary_data = res.salary_data;
        console.log(salary_data)
        let salary_text = ``;
        if(salary_data && salary_data.length > 0){
            salary_text += `<h5>Please select salary Which you need to use. If your preferred salary is not in list then add:</h5>`;
            salary_data.forEach((salary, index) => {
                const salaryStr = JSON.stringify(salary);
                salary_text += `<div>
                    <input type="radio" name="selected_salary" value="${salary.id}" id="salary_${salary.id}" onchange="handle_salary_for_populate('${encodeURIComponent(salaryStr)}', true)">
                    <label for="salary_${salary.id}">
                        ${salary.revision_start_date=="" || salary.revision_start_date==null ? user_data.joining_date: salary.revision_start_date} 
                        - 
                        ${salary.revision_end_date=="" || salary.revision_end_date==null ? "Current": salary.revision_end_date}
                    </label>
                </div>`;

                if(salary.id == '<?php echo isset($edit_salary_id) ? $edit_salary_id : ''; ?>'){
                    handle_salary_for_populate(salary);
                }
            });
            
        }
        salary_text += `<div id="what_do_options">
                <h5 class="mb-0">What Do you want?</h5>
                <input type="radio" name="what_do" value="Insert" id="what_do_insert" <?php echo (!isset($_GET['edit'])) ? 'checked' : ''; ?>>
                <label for="what_do_insert">Insert (New Salary)</label>
                <input type="radio" name="what_do" value="Update" id="what_do_update" <?php echo (isset($_GET['edit'])) ? 'checked' : ''; ?>>
                <label for="what_do_update">Update (In Selected Salary)</label>
            </div>`;
        $('.show_old_salaries').html(salary_text);
        // console.log(salary_text)
        $('.show_old_salaries').show();
        <?php if(isset($_GET['edit']) || $currentPageName=='appraisal_letter') { ?>
        <?php } ?>
    }

</script>