<?php
include "pin/header.php";
include "pin/sidenav.php";

$user_id = $_SESSION['user_id'];
$emp_id = $_SESSION['emp_id'];
$user_role = $_SESSION['user_role'];


$edit = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM `fnf` WHERE `id`='$_GET[edit]' "));
$user_data = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM users WHERE employee_id='$edit[employee_id]'"));
$fnf_details = $edit['fnf_details'];
?>

<style>
    .gap-1 {
        gap: 1rem;
    }
</style>
<!-- ============================================================== -->
<!-- Start Page Content here -->
<!-- ============================================================== -->

<div class="content-page">
    <div class="content">
        <div class="container-fluid">

            <div class="mt-5"></div>

            <form id="form_submit" class="needs-validation" novalidate>

                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body p-4">
                                <h4 class="header-title mt-1 mb-2">
                                    FNF Calculation
                                </h4>

                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="employee_id">Employee<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="employee_id" class="form-control custom-select-picker-ajax" data-search="employees" data-param="<?php echo htmlspecialchars(json_encode(['default'=>$edit['employee_id'], 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Employee" id="employee_id" required <?php echo isset($_GET['edit']) ? 'disabled' : ''; ?>>
                                                <option></option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="name">Name<span class="text-danger">*</span></label>
                                            <input type="text" name="name" required placeholder="Enter Name" class="form-control" id="name" value="<?php echo $user_data['name']; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="joiningDate">Joining Date<span class="text-danger">*</span></label>
                                            <input type="date" name="joiningDate" required class="form-control" id="joiningDate" value="<?php echo (isset($user_data['joining_date']) ? ((!empty($user_data['joining_date'])) ? date("Y-m-d", strtotime($user_data['joining_date'])) : '') : ''); ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="designation">Designation<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="designation" class="form-control custom-select-picker-ajax" data-search="designations" data-param="<?php echo htmlspecialchars(json_encode(['default'=>$user_data['designation'], 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Designation" id="designation" required>
                                                <option></option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="last_working_date">Last Working Date</label>
                                            <input type="date" name="last_working_date" class="form-control" id="last_working_date" value="<?php echo (isset($user_data['working_status_date']) ? ((!empty($user_data['working_status_date'])) ? date("Y-m-d", strtotime($user_data['working_status_date'])) : '') : ''); ?>">
                                        </div>
                                    </div>

                                </div>

                                <hr class="mb-2 mt-4">

                                <div>
                                    <div class="form-group">
                                        <label for="fnf_months">FNF Months</label>
                                        <div class="d-flex gap-1 mb-2">
                                            <input type="text" name="fnf_months" id="fnf_months" class="form-control flatpickr_date" placeholder="Select FNF Months" style="width:50%;">
                                            <button type="button" class="btn btn-primary" id="calculate_data">Calculate&nbsp;Data</button>
                                        </div>
                                    </div>


                                    <div id="calculated_data"></div>

                                </div>

                                <hr>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="net_payable">Net Payable</label>
                                            <input type="text" name="net_payable" class="form-control" id="net_payable" value="" placeholder="Net Payable" readonly>
                                        </div>
                                    </div>
                                </div>


                                <?php if (isset($edit['id'])) { ?>
                                    <input type="hidden" name="edit_id" value="<?php echo $edit['id']; ?>">
                                    <input class="btn btn-primary mr-1" name="update_fnf" type="hidden">
                                <?php } else { ?>
                                    <input class="btn btn-primary mr-1" name="add_fnf" type="hidden">
                                <?php } ?>


                                <div class="form-group text-right mb-0 mt-4">
                                    <?php if (isset($edit['id'])) { ?>
                                        <button class="btn btn-primary mr-1" name="update_fnf" type="submit">Update FNF</button>
                                    <?php } else { ?>
                                        <button class="btn btn-primary mr-1" name="add_fnf" type="submit">Add FNF</button>
                                    <?php } ?>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>

                
            </form>


        </div>
    </div> <!-- content -->

</div>

<!-- ============================================================== -->
<!-- End Page content -->
<!-- ============================================================== -->

<?php
include "pin/footer.php";
?>

<script>
    let net_payable = 0;
    let all_salaries = [];
    // 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);
    }
    function populateField(container_id, type, month_year, data = null) {

        let extra_field = "";
        if(data.title=='Allowed Leaves'){
            extra_field = `onchange="calculateDataAgain('${month_year}');"`;
        }

        let amount = data.value ?? data.working_amount ?? data.monthly_amount;
        if(amount%1 != 0){
            amount = amount.toFixed(2);
        }

        let readOnly = (extra_field == "" && data.title != 'Excess Leaves Utilized') ? 'readonly' : '';

        $(`#${container_id} .${type}`).append(`<div class="col-md-6">
                                            <div class="d-flex gap-1 mb-2">
                                                <input type="text" name="${type}_title[${month_year}][]" required class="form-control" value="${data.title}" readonly>
                                                <input type="text" name="${type}_value[${month_year}][]" required placeholder="${data.title} ${month_year}" class="form-control ${type}_field" value="${amount}" ${extra_field} ${readOnly}>
                                            </div>
                                        </div>`);
    }

    function addFnfField(container_id, type, month_year, data = null) {
        $(`#${container_id} .${type}`).append(`<div class="col-md-6">
                                <div class="d-flex gap-1 mb-2">
                                    <input type="text" name="${type}_title[${month_year}][]" required class="form-control" value="${data?.title ?? ''}" placeholder="Enter Title">
                                    <input type="text" name="${type}_value[${month_year}][]" required class="form-control ${type}_calculating_field" value="${data?.value ?? ''}" placeholder="Enter Value">
                                    <button type="button" class="btn btn-danger remove_${type}">Remove</button>
                                </div>
                            </div>`);
    }

    function iterateFields(fnf_details) {
        for (const [month_year, details] of Object.entries(fnf_details)) {
            let id = month_year.replace(" ", "_");
            
            // ########################################################## fixed data
            if($(`#${id}`).length === 0){
                $('#calculated_data').append(`<div id="${id}">
                    <div class="row fixed">
                        <div class="col-12">
                            <hr>
                            <h4 class="mt-3 mb-2">${month_year}</h4>
                        </div>
                    </div>
                </div>`);
            }
            let last_item = [];
            let fixed = details.fixed;
            fixed.forEach(item => {
                populateField(id, 'fixed', month_year, item);
                last_item = item;
            });
            // ########################################################## fixed data


            // ########################################################## add on data
            $(`#${id}`).append(`<div class="row add_on">
                            <div class="col-md-12">
                                <hr>
                                <div class="d-flex justify-content-end mb-2">
                                    <button type="button" class="btn btn-secondary mb-2" onclick="addFnfField('${id}', 'add_on', '${month_year}');">Add On</button>
                                </div>
                            </div>
                        </div>`);
            let add_on = (all_salaries.hasOwnProperty(month_year)) ? all_salaries[month_year].salary_components.add_on || [] : details.add_on;
            add_on.forEach(item => {
                populateField(id, 'add_on', month_year, item);
            });
            // ########################################################## add on data


            // ########################################################## deduction data
            $(`#${id}`).append(`<div class="row deduction">
                            <div class="col-md-12">
                                <hr>
                                <div class="d-flex justify-content-end mb-2">
                                    <button type="button" class="btn btn-secondary mb-2" onclick="addFnfField('${id}', 'deduction', '${month_year}');">Deduction</button>
                                </div>
                            </div>
                        </div>`);
            let deduction = (all_salaries.hasOwnProperty(month_year)) ? all_salaries[month_year].salary_components.deduction || [] : details.add_on;
            deduction.forEach(item => {
                populateField(id, 'deduction', month_year, item);
            });
            // ########################################################## deduction data
            
            
            // ########################################################## net payable
            let monthly_payable = details.monthly_payable || [];
            $(`#${id}`).append(`<div class="row">
                            <div class="col-md-12">
                                <hr>
                            </div>
                            <div class="col-md-6">
                                <div class="d-flex gap-1 mb-2">
                                    <input type="text" name="monthly_payable_title[${month_year}][]" required class="form-control" value="Monthly Payable" placeholder="Enter Title" readonly>
                                    <input type="text" name="monthly_payable_value[${month_year}][]" required class="form-control monthly_payable" value="" placeholder="Enter Value" readonly>
                                </div>
                            </div>
                        </div>`);
            // ########################################################## net payable

            // console.log($(`#${id}`));
            calculate_monthly_payable($(`#${id}`))
        }
    }

    $('#calculate_data').on('click', function() {
        let fnf_months = $('#fnf_months').val();
        let employee_id = $('#employee_id').val();
        // console.log(fnf_months, employee_id);
        if (fnf_months === '') {
            failedMessage('Please, Select FNF Months.', '<?php echo $_SESSION['user_name']; ?>');
            return false;
        }

        $.ajax({
            url: 'fun/fnf_calculation_backend',
            type: 'POST',
            data: {
                calculate_fnf: fnf_months,
                employee_id: employee_id
            },
            dataType: 'json',
            success: function(res) {
                console.log(res);
                if (res.status === 200) {
                    $('#calculated_data').html('');

                    all_salaries = res.data.all_salaries;
                    fnf_details = res.data.fnf_details;
                    console.log(all_salaries);
                    console.log(fnf_details);
                    iterateFields(fnf_details);
                } else {
                    // console.log(res);
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            },
            error: function(xhr, status, error) {
                console.log(`Error: ${JSON.stringify(error)}`);
            }
        });
    });

    function calculateDataAgain(month_year) {
        let container_id = month_year.replace(" ", "_");

        let total_working_days = $(`#${container_id} input[value="Total Working Days"]`).next().val();
        let allowed_leaves= $(`#${container_id} input[value="Allowed Leaves"]`).next().val();
        // let net_paid_days = $(`#${container_id} input[value="Net Paid Days"]`).next().val();


        // find the month data from all_salaries
        let month_data = all_salaries[month_year];
        // console.log(month_data);
        if (month_data) {
            let leaves = month_data.leaves;
            let net_paid_days = leaves['Total Working Days'];
            let final_paid_days = parseInt(net_paid_days) + parseInt(allowed_leaves);


            let fixed_pay = month_data.salary_components.fixed_pay;
            let add_on = month_data.salary_components.add_on;
            let deduction = month_data.salary_components.deduction;
            
            let working_fixed_ctc = 0;
            for (let key in fixed_pay) {
                // let value = (fixed_pay[key]['yearly_amount']/12)/leaves['Current Range Days'];
                // fixed_pay[key]['per_day_amount'] = value;
                fixed_pay[key]['working_amount'] = fixed_pay[key]['per_day_amount']*final_paid_days;
                working_fixed_ctc += fixed_pay[key]['working_amount'];
            }
            // console.log(fixed_pay);

            // let add_on_sum = 0;
            // for(let key in add_on){
            //     let value = add_on[key]['monthly_amount'];
            //     if(add_on[key]['title']=='ESIC Employer Share @ 3.25% of (A)'){
            //         add_on[key]['working_amount'] = add_on[key]['per_day_amount']*final_paid_days;
            //         value = add_on[key]['working_amount'];
            //         // console.log(value);
            //         $(`#${container_id} input[value="ESIC Employer Share @ 3.25% of (A)"]`).next().val(value.toFixed(2));
            //     }
            //     add_on_sum += value;
            // }


            // let deduction_sum = 0;
            // for (let key in deduction) {
            //     let value = deduction[key]['monthly_amount'];
            //     if(deduction[key]['title']=='ESIC Employee Share @ 0.75% of (A)'){
            //         deduction[key]['working_amount'] = deduction[key]['per_day_amount']*final_paid_days;
            //         value = deduction[key]['working_amount'];
            //         $(`#${container_id} input[value="ESIC Employee Share @ 0.75% of (A)"]`).next().val(value.toFixed(2));
            //     }
            //     deduction_sum += value;
            // }

            // console.log(working_fixed_ctc, deduction_sum, add_on_sum);
            $(`#${container_id} input[value="Net Paid Days"]`).next().val(final_paid_days);
            $(`#${container_id} input[value="Payable Salary"]`).next().val(working_fixed_ctc.toFixed(2))
            
        }
        // console.log(container_id)
        // console.log($(`#${container_id}`))
        calculate_monthly_payable($(`#${container_id}`));
    }
   

    function calculate_monthly_payable(container) {
        // console.log(container);
        let monthly_payable_input = $(container).find('.monthly_payable');
        // console.log(monthly_payable_input);

        let total = 0
        total += parseFloat($(container).find('input[value="Payable Salary"]').next().val());
        $(container).find('.add_on_calculating_field').each(function() {
            let val = $(this).val();
            if ($.isNumeric(val)) {
                total += parseFloat(val);
            }
        });
        $(container).find('.deduction_field').each(function() {
            let val = $(this).val();
            if ($.isNumeric(val)) {
                total -= parseFloat(val);
            }
        });
        $(container).find('.deduction_calculating_field').each(function() {
            let val = $(this).val();
            if ($.isNumeric(val)) {
                total -= parseFloat(val);
            }
        });

        // console.log(total);
        $(monthly_payable_input).val(total.toFixed(2));
        triggerNativeInput(monthly_payable_input, 'input');
    }

    $(document).on('click', '.remove_add_on, .remove_deduction', function(e) {
        let container = $(e.target).closest('.row').parent();
        $(this).closest('.col-md-6').remove();
        calculate_monthly_payable(container);
    });

   $(document).on('input', '.add_on_calculating_field, .deduction_calculating_field', function(e) {
        let container = $(e.target).closest('.row').parent();
        calculate_monthly_payable(container);
    });

    $(document).on('input', '.monthly_payable', function(e) {
        let total = 0;
        $('.monthly_payable').each(function() {
            total += parseFloat($(this).val()) || 0;
        });
        $('#net_payable').val(total.toFixed(2));
    });

    $(document).on('keyup', '.fixed_field', function () {
        if ($(this).is($('.fixed_field').last())) {
            let excessive_leaves = $(this).val();
            let net_paid_days = $(this).closest('.row').find('input[value="Net Paid Days"]').next().val();

            // let calculate_fnf_months = $('#fnf_months').val();
            // console.log(calculate_fnf_months);

            if ($.isNumeric(excessive_leaves)) {
                $.ajax({
                    url: 'fun/fnf_calculation_backend',
                    type: 'POST',
                    data: {
                        manage_execessive_leaves: 1,
                        calculate_fnf_months: $('#fnf_months').val(),
                        employee_id: $('#employee_id').val(),
                        excessive_leaves: excessive_leaves,
                        net_paid_days: net_paid_days
                    },
                    success: function(res) {
                        let resp = JSON.parse(res);
                        let excessive_leave_amount = resp.excessive_leave_amount;
                        console.log(resp);

                        $(`input[name="monthly_payable_value[${resp.formatted_month_year}][]"]`).val(resp.monthly_payable_amount.toFixed(2));
                        $(`input[value="Payable Salary"]`).last().next().val(resp.monthly_payable_salary);
                        

                        // // update net paid days
                        $(`input[value="Net Paid Days"]`).last().next().val(resp.net_paid_days);

                        let total = 0;
                        $('.monthly_payable').each(function() {
                            total += parseFloat($(this).val()) || 0;
                        });
                        $('#net_payable').val(total.toFixed(2));
                    },
                    error: function(xhr, status, error) {
                        console.log(`Error: ${JSON.stringify(error)}`);
                    }
                });
            }
        }
    });
</script>

<script>
    <?php if(!empty($fnf_details)): ?>
    let fnf_details = <?php echo !empty($fnf_details) ? $fnf_details : 'null'; ?>;
    // console.log(fnf_details);
    iterateFields(fnf_details);
    <?php endif; ?>
</script>

<script>

   $('#employee_id').change(function() {
        let emp_id = $(this).val();
        if (emp_id) {
            $.ajax({
                url: 'fun/letters_backend',
                type: 'POST',
                data: { fetch_employee: emp_id },
                dataType: 'json',
                success: function(res) {
                    // console.log(res);
                    if (res.status === 200) {
                        if(res.user_data){
                            $('#name').val(res.user_data.name);
                            $('#joiningDate').val(res.user_data.joining_date);
                            $('#last_working_date').val(res.user_data.working_status_date);
                            $('#designation').val(res.user_data.designation).trigger('change');
                        }
                    } else {
                        failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                        // clear employee_id
                        $('#employee_id').val('').trigger('change');
                    }
                },
                error: function(xhr, status, error) {
                    console.log(`Error: ${JSON.stringify(error)}`);
                }
            });
        }
    });
</script>

<script>
    function hasEmptyFields(form) {
        // Get all input elements within the form
        const inputs = form.querySelectorAll('input, select, textarea');

        // Check if any input is empty or null
        return Array.from(inputs).some(input => {
            // console.log(input.required, input.value.trim(), input.id);
            return input.required && input.value.trim() === ''
        });
    }

    $(document).on('submit', '#form_submit', function(e) {
        e.preventDefault()
        let form = document.getElementById('form_submit');

        if (!form.checkValidity()) {
            form.classList.add('was-validated');
            failedMessage("Fill All the Fields", "<?php echo $_SESSION['user_name']; ?>");
            return false;
        }

        // let form_data = new FormData(form);
        let form_data = $('#form_submit').serialize();
        console.log(form_data);

        // return;

        if (hasEmptyFields(form)) {
            failedMessage('Please, Fill all the Fields.', '<?php echo $_SESSION['user_name']; ?>');
            return false;
        }

        $.ajax({
            url: 'fun/fnf_calculation_backend',
            type: 'POST',
            data: form_data,
            dataType: 'json',
            success: function(res) {
                console.log(res);
                if (res.status === 200) {
                    successMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                    setTimeout(() => {
                        location.href = 'all_fnf';
                    }, 2000);
                } else {
                    // console.log(res);
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            },
            error: function(xhr, status, error) {
                console.log(`Error: ${JSON.stringify(error)}`);
            }
        });
    });
</script>