<?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'];


$financial_year_start =  '';
$financial_year_end = '';
if (isset($_GET['financial_year'])) {
    $financial_year_start = explode(' to ', $_GET['financial_year'])[0];
    $financial_year_end = explode(' to ', $_GET['financial_year'])[1];
} else {
   $currentMonth = date('n');
    $currentYear = date('Y');
    if ($currentMonth >= 4) {
        $startYear = $currentYear;
        $endYear = $currentYear + 1;
    } else {
        $startYear = $currentYear - 1;
        $endYear = $currentYear;
    }
    $financial_year_start = "$startYear-04";
    $financial_year_end = "$endYear-03";
}

?>


<div class="content-page">
    <div class="content">
        <div class="container-fluid">
            <div class="my-3"></div>
            
            <?php if ($user_role == 0) { ?>
                 <div class="row mb-3 align-items-center">
                    <div class="col-sm-12">
                        <div class="form-inline float-sm-right mt-3 mt-sm-0">
                            <div class="mb-sm-0 mr-2">
                                <label for="financial_year">Select Financial Year</label>
                                <input type="text" name="financial_year" parsley-trigger="change" required class="form-control" id="financial_year">
                            </div>
                            <!-- <div class="btn-group">
                                <button type="button" class="btn btn-primary" onclick="exportYearDataIds();">
                                    <i class='uil uil-file-alt mr-1'></i>Download Yearly Excel<i class="uil uil-down-arrow ml-1"></i>
                                </button>
                            </div> -->
                        </div>
                    </div>
                </div>
                
                <div class="row mb-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">
                                <button type="button" class="btn btn-primary" onclick="storeForYear('<?php echo $financial_year_start; ?>','<?php echo $financial_year_end; ?>');">
                                    <i class='uil uil-file-alt mr-1'></i>
                                    <span>Store/Update Yearly Salary</span>
                                    <i class="uil uil-arrow-up-right ml-1"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php } ?>

            <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>Employee Id</th>
                                        <th>Leaves</th>
                                        <th>Net CTC</th>
                                        <th>Net Payable</th>
                                        <th>Deduction</th>
                                        <th>Final Salary</th>
                                        <th>Tax</th>
                                    </tr>
                                </thead>


                              
                            </table>

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

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

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

<script>
    flatpickr("#financial_year", {
        mode: "range",
        dateFormat: "Y-m",
        defaultDate: [
            "<?php echo $financial_year_start; ?>",
            "<?php echo $financial_year_end; ?>"
        ]
    });

    $('#financial_year').on('change', function(e){
        if(this.value.split(' to ').length == 2){
            location.href = "?financial_year=" + this.value;
        }
    });

    function storeForYear(from, to) {

        // console.log(users, from, to);
        if (confirm("You want to store all salary for selected period?")) {
            $.ajax({
                    url:'fun/storeSalaryForYear',
                    type:"GET",
                    data:{
                        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)}`);
                    }
                });
            alert('Come back later; your data will be updated soon.')
        } else {
            return false;
        }

    }

    $(document).ready(function() {
        
        let columns = [];
        // ############################### columns
        let columns_visible = [
            {data: 'employee_id'}, 
            {data: 'leaves_json'}, 
            {data: 'net_ctc_json'},
            {data: 'net_payable_json'},
            {data: 'deduction_json'},
            {data: 'final_salary_json'},
            {data: 'total_final_salary'},
        ];

        let columns_hide = [];

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

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

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

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

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


</script>