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

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


// $firstDayLast =  '';
// $lastDayLast = '';
if (isset($_GET['which_month'])) {
    $firstDayLast = date('Y-m-01', strtotime(trim($_GET['which_month'])));
    $lastDayLast = date('Y-m-t', strtotime(trim($_GET['which_month'])));
} else {
    $firstDayLast =  date('Y-m-d', strtotime('first day of last month'));
    $lastDayLast =  date('Y-m-d', strtotime('last day of last month'));
}

?>


<div class="content-page">
    <div class="content">
        <div class="container-fluid">
            <div class="my-3"></div>

            
            <div class="row my-3 align-items-center">
                <div class="col-sm-12">
                    <div class="form-inline float-sm-right mt-3 mt-sm-0">
                        <div class="form-group mb-sm-0 mr-2">
                            <input type="month" class="form-control" onchange="setDateMonth(this);" value="<?php echo date('Y-m', strtotime($firstDayLast)); ?>">
                            <!-- <input type="text" class="form-control" id="dash-daterange" onchange="setDateRange(this);" style="min-width: 210px;" /> -->
                        </div>
                        <?php if ($user_role == 0) { ?>
                        <div class="btn-group">
                            <button type="button" class="btn btn-primary" onclick="exportMonthDataIds('<?php echo $firstDayLast; ?>','<?php echo $lastDayLast; ?>');">
                                <i class='uil uil-file-alt mr-1'></i>Download Monthly Excel<i class="uil uil-down-arrow ml-1"></i>
                            </button>
                        </div>
                        <?php } ?>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body p-4">
                            <h4 class="header-title mt-0 mb-1 mb-4">
                                Salary
                            </h4>

                            <table id="basic-datatable" class="table dt-responsive nowrap">
                                <thead>
                                    <tr>
                                        <th><input id="checkAll" type="checkbox"></th>
                                        <th>ID</th>
                                        <th>Employee Id</th>
                                        <th>Name</th>
                                        <th>Department</th>
                                        <th>Monthly Salary Details</th>
                                        <th>Total Leave Details</th>
                                        <th>Working Days Salary Details</th>
                                        <th>Monthly Deduction Details</th>
                                        <th>Payable Salary</th>
                                        <th>Salary Slip</th>
                                    </tr>
                                </thead>


                              
                            </table>

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

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

<!-- Modal -->
<div class="modal fade" id="monthSalaryDetails" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="monthSalaryDetailsLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header pb-2">
                <h5 class="modal-title" id="monthSalaryDetailsLabel"><span id="name_salary"></span> Monthly Salary Details</h5>
                <button type="button" class="btn text-dark" onclick="modalHide('monthSalaryDetails');"><i data-feather="x"></i></button>
            </div>
            <div class="modal-body px-4"></div>
            <!-- <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Understood</button>
            </div> -->
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="workingSalaryDetails" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="workingSalaryDetailsLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header pb-2">
                <h5 class="modal-title" id="workingSalaryDetailsLabel"><span id="working_name_salary"></span> Working Days Salary Details</h5>
                <button type="button" class="btn text-dark" onclick="modalHide('workingSalaryDetails');"><i data-feather="x"></i></button>
            </div>
            <div class="modal-body px-4"></div>
            <!-- <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Understood</button>
            </div> -->
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="totalLeave" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="totalLeaveLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header pb-2">
                <h5 class="modal-title" id="totalLeaveLabel"><span id="name_leave"></span> Leave Details</h5>
                <button type="button" class="btn text-dark" onclick="modalHide('totalLeave');"><i data-feather="x"></i></button>
            </div>
            <div class="modal-body px-4"></div>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="monthDeduction" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="monthDeductionLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header pb-2">
                <h5 class="modal-title" id="monthDeductionLabel"><span id="name_deduction"></span> Monthly Deduction Details</h5>
                <button type="button" class="btn text-dark" onclick="modalHide('monthDeduction');"><i data-feather="x"></i></button>
            </div>
            <div class="modal-body px-4"></div>
        </div>
    </div>
</div>


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

<script>

    function modalHide(id) {
        $("#" + id).modal("hide");
    }

    function monthSalaryDetails(name, res) {
        res = JSON.parse(res);
        console.log(res);
        $("#name_salary").text(name);
        let txt = '';
        let total = 0;
        for (const [key, value] of Object.entries(res)) {
            txt += `<p class="mb-2"><strong>${key}:&nbsp;&nbsp;&#8377;&nbsp;</strong><span>${Math.round(value)}</span></p>`;
            total += value;
        }
        txt += `<p class="mb-2 text-center fs-5 text-primary"><strong>Total Salary:&nbsp;&nbsp;&#8377;&nbsp;</strong><span>${Math.round(total)}</span></p>`;

        $("#monthSalaryDetails .modal-body").html(txt);
        $("#monthSalaryDetails").modal("show");
    }

    function workingSalaryDetails(name, res) {

        res = JSON.parse(res);
        console.log(res);

        $("#working_name_salary").text(name);
        let txt = '';
        let total = 0;
        for (const [key, value] of Object.entries(res)) {
            txt += `<p class="mb-2"><strong>${key}:&nbsp;&nbsp;&#8377;&nbsp;</strong><span>${Math.round(value)}</span></p>`;
            total += value;
        }
        txt += `<p class="mb-2 text-center fs-5 text-primary"><strong>Total Salary:&nbsp;&nbsp;&#8377;&nbsp;</strong><span>${Math.round(total)}</span></p>`;

        $("#workingSalaryDetails .modal-body").html(txt);
        $("#workingSalaryDetails").modal("show");

    }

    function totalLeave(name, res) {
        res = JSON.parse(res);
        console.log(res);

        $("#name_leave").text(name);
        let txt = '';
        txt += `<p class="mb-2"><strong>Absent: </strong><span>${res['Absent']}</span>&nbsp;Days</p>`
        txt += `<p class="mb-2"><strong>Half Day: </strong><span>${res['Half Day']}</span>&nbsp;Days</p>`
        txt += `<p class="mb-2"><strong>Total Leaves: </strong><span>${res['Total Leaves']}</span>&nbsp;Days</p>`
        txt += `<p class="mb-2"><strong>Total Working Days: </strong><span>${res['Total Working Days']}</span>&nbsp;Days</p>`

        $("#totalLeave .modal-body").html(txt);
        $("#totalLeave").modal("show");
    }

    function monthDeduction(name, res) {
        res = JSON.parse(res);
        console.log(res);

        $("#name_deduction").text(name);
        let txt = '';
        let total = 0;
        for (const [key, value] of Object.entries(res)) {
            txt += `<p class="mb-2"><strong>${key}:&nbsp;&nbsp;&#8377;&nbsp;</strong><span>${Math.round(value)}</span></p>`;
            total += value;
        }
        txt += `<p class="mb-2 text-center fs-5 text-primary"><strong>Total Deduction:&nbsp;&nbsp;&#8377;&nbsp;</strong><span>${Math.round(total)}</span></p>`;

        $("#monthDeduction .modal-body").html(txt);
        $("#monthDeduction").modal("show");
    }


    function setDateMonth(element) {

        let val = $(element).val();
        // console.log(val);
        location.href = "?which_month=" + val;
    }

    function exportMonthDataIds(from, to) {

        if (all_checkboxes_val.length!=0) {

            // console.log(users, from, to);
            if (confirm("Exports users to Excel....?")) {
                $.ajax({
                    url:'fun/exportSalary',
                    type:"GET",
                    data:{
                        users:all_checkboxes_val,
                        from:from,
                        to:to
                    },
                    dataType: "json",
                    success:function(res){
                        // console.log(res);
                        if (res.status=200) {
                            successMessage(res.message, '<?php echo $_SESSION['user_name'] ?>');
                        } else {
                            failedMessage(res.message, '<?php echo $_SESSION['user_name'] ?>');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.log(`Error: ${JSON.stringify(error)}`);
                    }
                });
            } else {
                return false;
            }

        } else {
            alert("Please Select Employees...");
        }
    }

    function requestSalarySlip(id, from, to) {

        if (confirm("Do You want to download the slip?")) {
            $.ajax({
                url: "fun/function",
                type: "POST",
                data: {
                    requestSalarySlip: id,
                    requestFrom: from,
                    requestTo: to
                },
                success: function(res) {
                    console.log(res);
                    res = JSON.parse(res);
                    if (res.status == 200) {
                        successMessage(res.message, '<?php echo $user_name; ?>');
                        window.open(res.link, '_blank');
                    } else {
                        failedMessage(res.message, '<?php echo $user_name; ?>');
                    }

                }
            });
        }
    }



    $(document).on('click', '.showPayableSalary', function() {
        if($(this).hasClass('uil-eye-slash')){
            let salary = $(this).parent().data('salary');
            $(this).parent().find('span').html(`&#8377;${salary}`);
            $(this).removeClass('uil-eye-slash').addClass('uil-eye');
        }else{
            $(this).parent().find('span').html(`&#8377;XXXX`);
            $(this).removeClass('uil-eye').addClass('uil-eye-slash');
        }
    });


    $(document).ready(function() {
        
        let columns = [];
        // ############################### columns
        let columns_visible = [
            {data: 'id'},
            {data: 'row_num'}, 
            {data: 'employee_id'}, 
            {data: 'name'}, 
            {data: 'department_name'},
            {data: 'firstDayLast'},
            {data: 'lastDayLast'},

            {data: 'email'},
            {data: 'phone'},
            {data: 'gender'},
            {data: 'working_status_date'},
            {data: 'joining_date', visible:false},
        ];

        let columns_hide = [];

        columns = [...columns_visible, ...columns_hide]
        // ############################### columns
        function show_hierarchy_data() {

            // ############################### setArray
            
            // ############################### setArray

            let extra_where = {
                firstDayLast: '<?php echo $firstDayLast ?>',
                lastDayLast: '<?php echo $lastDayLast ?>',
            };
            // console.log(extra_where);

            $("#filter_options").html('');
            form_fields.each(function() {
                search_filter(this);
            });
            loadTable('#basic-datatable', 'get_from_server/all_salary_get', columns, [1, 'asc'], setArray, JSON.stringify(extra_where));
            
            // console.log(setArray);
            setArray = [];
            // console.log(setArray);
        }

        show_hierarchy_data();
        $("#search_filter").click(show_hierarchy_data);
    });


    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() === ''
            }
        );
    }

    $('#form_submit').submit(function (e) {
        e.preventDefault();
        let form = document.getElementById('form_submit');
        // let form_data = new FormData(form);
        let form_data = $('#form_submit').serialize();
        // console.log(form_data);

        if(hasEmptyFields(form)){
            failedMessage('Please, Fill all the Fields.','<?php echo $_SESSION['user_name']; ?>');
            return false;
        }
        $.ajax({
            url: 'fun/function',
            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.reload();
                    // }, 2000);
                } else {
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            },
            error: function(xhr, status, error) {
                console.log(`Error: ${JSON.stringify(error)}`);
            }
        });
    });

</script>