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

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


if (isset($_GET['delete'])) {
    $q = mysqli_query($db, "DELETE FROM employee_bonusIncentive WHERE id='$_GET[delete]' ");

    if ($q) {
        echo "<script>alert('Tax Slab Deleted Successfully !');</script>";
        echo "<script>location.href='tax-slab';</script>";
    }
}

// $edit = mysqli_fetch_assoc(mysqli_query($db, "SELECT * from employee_bonusIncentive where id='$_GET[edit]' "));

?>


<!-- ============================================================== -->
<!-- Start Page Content here -->
<!-- ============================================================== -->

<div class="content-page">
    <div class="content">
        <div class="container-fluid">
            <div class="mt-5"></div>

            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body p-4">
                            <h4 class="header-title mt-1 mb-4">
                                Add Bonus/Incentive
                            </h4>

                            <form id="form_submit">
                                <div class="row">
                                    <div class="col-sm-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>
                                                <option></option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="bonus">Bonus<span class="text-danger">*</span></label>
                                            <input type="text" name="bonus" required class="form-control indianCurrencyFormat" id="bonus" value="" placeholder="Enter Bonus">
                                        </div>
                                    </div>

                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="incentive">Incentive<span class="text-danger">*</span></label>
                                            <input type="text" name="incentive" class="form-control indianCurrencyFormat" id="incentive" required placeholder="Enter Incentive" value="">
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="bonusIncentive_date">Month<span class="text-danger">*</span></label>
                                            <input type="month" id="bonusIncentive_date" name="bonusIncentive_date" class="form-control" required value="">
                                        </div>
                                    </div>
                                </div>

                                <input class="btn btn-primary mr-1" name="bonusIncentiveSubmit" id="bonusIncentiveSubmit" type="hidden">

                                <div class="form-group text-right mb-0 mt-4">
                                    <button class="btn btn-primary mr-1" name="bonusIncentiveSubmit" id="bonusIncentiveSubmit" type="submit">Save Bonus/Incentive</button>
                                </div>

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


                    <div class="card">
                        <div class="card-body p-4">
                            <h4 class="header-title mt-1 mb-4">
                                Bulk Bonus/Incentive
                            </h4>

                            <form id="form_submit_file">
                                <div class="row">

                                    <div class="col-12 mb-3">
                                        <a href="<?php echo $url; ?>files_download/bonus-incentive-sample.csv" class="btn btn-primary">Download Sample CSV</a>
                                    </div>


                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="bonus_incentive_sample">Bonus_incentive_sample<span class="text-danger">*</span></label>
                                            <input type="file" name="bonus_incentive_sample" required class="form-control" id="bonus_incentive_sample" value="" placeholder="Enter Bonus Incentive Sample">
                                        </div>
                                    </div>

                                </div>

                                <input class="btn btn-primary mr-1" name="bonusIncentive_file" id="bonusIncentive_file" type="hidden">

                                <div class="form-group text-right mb-0 mt-4">
                                    <button class="btn btn-primary mr-1" name="bonusIncentive_file" id="bonusIncentive_file" type="submit">
                                        <span>Upload Bonus/Incentive</span>
                                        <span class="spinner-border" role="status" style="width:1rem; height:1rem; display:none;"></span>
                                    </button>
                                </div>

                            </form>
                        </div>
                    </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">
                                All Tax Slab
                            </h4>

                            <table id="basic-datatable" class="table dt-responsive nowrap">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Employee Id</th>
                                        <th>Name</th>
                                        <th>Bonus</th>
                                        <th>Incentive</th>
                                        <th>Date</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>

                            </table>
                            <!-- </div> -->

                        </div> <!-- end card body-->
                    </div> <!-- end card -->
                </div><!-- end col-->
            </div>
            <!-- end row-->

        </div>
    </div> 

</div>



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

<script>
    $(document).ready(function() {
            
        // ############################### columns
        let columns = [
            {data: 'id'}, 
            {data: 'employee_id'}, 
            {data: 'name'},
            {data: 'bonus'},
            {data: 'incentive'},
            {data: 'date'},
            {data: 'action_id'},
        ];

        // ############################### columns
        function show_hierarchy_data() {

            $("#filter_options").html('');
            form_fields.each(function() {
                search_filter(this);
            });
            if (setArray.length > 0) {
                loadTable('#basic-datatable', 'get_from_server/bonus_incentive_get', columns, [0, 'desc'], setArray);
            } else {
                loadTable('#basic-datatable', 'get_from_server/bonus_incentive_get', columns, [0, 'desc']);
            }
            // console.log(setArray);
            setArray = [];
            // console.log(setArray);
        }

        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.href='bonus-incentive';
                    }, 2000);
                } else {
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            },
            error: function(xhr, status, error) {
                console.log(`Error: ${JSON.stringify(error)}`);
            }
        });
    });

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

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

        $(form).find('button[type="submit"] span:last-child').show();
        $(form).find('button[type="submit"]').prop('disabled', true);
        await $.ajax({
            url: 'fun/importBonusIncentive',
            type: 'POST',
            data: form_data,
            processData: false,      // 🔥 don't process the data
            contentType: false,      // 🔥 don't set content type
            success: function(res) {
                console.log(res);
                res = JSON.parse(res);
                console.log(res);
                if (res.status === 200) {
                    successMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                    setTimeout(() => {
                        location.href='bonus-incentive';
                    }, 2000);
                } else {
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            }
        });
        $(form).find('button[type="submit"] span:last-child').hide();
        $(form).find('button[type="submit"]').prop('disabled', false);
    });
</script>