<?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 `employee_salary` WHERE `id`='$_GET[edit]' "));
$fixed = $edit['fixed'];
$add_on = $edit['add_on'];
$deduction = $edit['deduction'];
$salary_data = $edit;

?>

<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="parsley-examples">

                <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">
                                    Add Employee Salary
                                </h4>
                                <!-- <p class="text-danger" style="font-size:0.7rem;">First Field for Month And Second Field for Year.</p> -->

                                <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="salary_condition">Employee Condition<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="salary_condition" class="form-control custom-select-picker" data-placeholder="Select Employee" id="salary_condition" required>
                                                <option></option>
                                                <option selected value="Employee">Employee</option>
                                                <option value="Considered As Intern">Considered As Intern</option>
                                                <option value="Intern">Intern</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>

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


                                <div id="employee_salary">
                                    <div class="d-flex justify-content-between">
                                        <h4 class="header-title mt-1 mb-2">Fixed Pay</h4>
                                        <div>
                                            <button type="button" class="btn btn-success mb-1 add-fixed" style="height:fit-content;"><i class="uil-plus"></i></button>
                                        </div>
                                    </div>
                                    <div id="employee_salary_fixed"></div>


                                    <hr class="mb-2 mt-4">
                                    <div class="d-flex justify-content-between">
                                        <h4 class="header-title mt-1 mb-2">Add On</h4>
                                        <div>
                                            <button type="button" class="btn btn-success mb-1 add-addOn" style="height:fit-content;"><i class="uil-plus"></i></button>
                                        </div>
                                    </div>
                                    <div id="employee_salary_addOn"></div>


                                    <hr class="mb-2 mt-4">
                                    <div class="d-flex justify-content-between">
                                        <h4 class="header-title mt-1 mb-2">Deduction</h4>
                                        <div>
                                            <button type="button" class="btn btn-success mb-1 add-deduction" style="height:fit-content;"><i class="uil-plus"></i></button>
                                        </div>
                                    </div>
                                    <div id="employee_salary_deduction"></div>

                                    <hr>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="ctcYearly">CTC<span class="text-danger">*</span></label>
                                                <div class="d-flex gap-1">
                                                    <input type="text" name="ctcMonthly" required placeholder="CTC Monthly" class="form-control monthlyValue indianCurrencyFormat" id="ctcMonthly" value="">
                                                    <input type="text" name="ctcYearly" required placeholder="CTC Yearly" class="form-control yearlyValue indianCurrencyFormat" id="ctcYearly" value="<?php echo $edit['ctc']; ?>">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="netPayableYearly">Net Payable<span class="text-danger">*</span></label>
                                                <div class="d-flex gap-1">
                                                    <input type="text" name="netPayableMonthly" required placeholder="Net Payable Monthly" class="form-control monthlyValue indianCurrencyFormat" id="netPayableMonthly" value="">
                                                    <input type="text" name="netPayableYearly" required placeholder="Net Payable Yearly" class="form-control yearlyValue indianCurrencyFormat" id="netPayableYearly" value="<?php echo $edit['net_payable']; ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                </div>

                                <div id="intern_salary" style="display: none;">
                                    <div class="d-flex justify-content-between">
                                        <h4 class="header-title mt-1 mb-2">Intern Salary</h4>
                                        <div>
                                            <button type="button" class="btn btn-success mb-1" id="addSalaryField" style="height:fit-content;"><i class="uil-plus"></i></button>
                                        </div>
                                    </div>
                                </div>

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

                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body p-4">
                                <div class="row">

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="" class="d-block">Revision Salary Date</label>
                                            <div class="form-check d-inline-block" style="cursor:pointer;">
                                                <input class="form-check-input" type="radio" name="revisionDateCheck" value="Yes" id="revisionDateYes" <?php echo isset($_GET['ReviseSalary']) ? 'checked' : ((!empty($edit['revision_start_date'])) ? 'checked' : ''); ?>>
                                                <label class="form-check-label" for="revisionDateYes">Yes</label>
                                            </div>
                                            <div class="form-check d-inline-block ml-3" style="cursor:pointer;">
                                                <input class="form-check-input" type="radio" name="revisionDateCheck" value="No" id="revisionDateNo" <?php echo !isset($_GET['ReviseSalary']) ? (isset($edit['revision_start_date']) ? ((empty($edit['revision_start_date'])) ? 'checked' : '') : 'checked') : ''; ?>>
                                                <label class="form-check-label" for="revisionDateNo">No</label>
                                            </div>
                                            <input type="date" name="revisionDate" class="form-control mt-1" id="revisionDate" style="display:<?php echo isset($_GET['ReviseSalary']) ? 'block' : ((!empty($edit['revision_start_date'])) ? 'block' : 'none'); ?>;" value="<?php echo isset($_GET['ReviseSalary']) ? $_GET['revision_date'] : $edit['revision_start_date']; ?>">

                                        </div>
                                    </div>

                                </div>

                                <?php if (isset($_GET['ReviseSalary'])) { ?>
                                    <input type="hidden" name="ex_employee_id" value="<?php echo $edit['employee_id']; ?>">
                                    <input type="hidden" name="edit_id" value="<?php echo $edit['id']; ?>">
                                    <input class="btn btn-primary mr-1" name="ReviseSalary" type="hidden">
                                <?php } else if (isset($edit['id'])) { ?>
                                    <input type="hidden" name="ex_employee_id" value="<?php echo $edit['employee_id']; ?>">
                                    <input type="hidden" name="edit_id" value="<?php echo $edit['id']; ?>">
                                    <input type="hidden" name="revisionOldDate" value="<?php echo $edit['revision_start_date']; ?>">
                                    <input class="btn btn-primary mr-1" name="updateSalary" type="hidden">
                                <?php } else { ?>
                                    <input class="btn btn-primary mr-1" name="addSalary" type="hidden">
                                <?php } ?>


                                <div class="form-group text-right mb-0 mt-4">
                                    <input type="hidden" name="salary_joining_date" id="salary_joining_date" value="">
                                    <?php if (isset($_GET['ReviseSalary'])) { ?>
                                        <button class="btn btn-primary mr-1" name="ReviseSalary" type="submit">Revise Salary</button>
                                    <?php } else if (isset($edit['id'])) { ?>
                                        <button class="btn btn-primary mr-1" name="updateSalary" type="submit">Update Salary</button>
                                    <?php } else { ?>
                                        <button class="btn btn-primary mr-1" name="addSalary" type="submit">Add Salary</button>
                                    <?php } ?>
                                </div>

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

                </div>
                <!-- end row -->
            </form>


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

</div>

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

<?php
include "pin/footer.php";
require_once 'salaryComponentsSupport.php';
?>

<script>
    $(document).on('change', "input[name=revisionDateCheck]", function() {
        if ($("input[name=revisionDateCheck]:checked").val() == 'Yes') {
            $("#revisionDate").slideDown();
            $("#revisionDate").val('');
            $("#revisionDate").prop('required', true);
        } else {
            $("#revisionDate").slideUp();
            $("#revisionDate").val('');
            $("#revisionDate").prop('required', false);
        }
    });


    $(document).on('change', "#employee_id", function() {
        let eid = $(this).val();
        $.ajax({
            url: "fun/function",
            type: "POST",
            data: {
                fromAddUserEmployeeId: eid
            },
            success: function(response) {
                let res = JSON.parse(response);
                // console.log(res);

                $(`input[name=epfStatus][value="${(res.epf_applicable_status) ?res.epf_applicable_status: 'No'}"]`).prop('checked', true).trigger("click");
                $('select[name="salary_condition"]').val(res.consider_as ? res.consider_as : 'Employee').change();
                $('#salary_joining_date').val(res.joining_date);
            }
        });
    });
</script>

<script>
    // ############################################################################## internship salary
    let intern_salary = $('#intern_salary').children().clone();
    let employee_salary = $('#employee_salary').children().clone();
    $('#intern_salary').children().html('');

    $(document).on('change', '#salary_condition', function(e) {
        let val = $(this).val();
        if (val == 'Intern') {
            $('#employee_salary').hide();
            $('#employee_salary').html('');

            $('#intern_salary').show();
            $('#addSalaryField').show();
            $('#intern_salary').html(intern_salary);
        } else {
            $('#employee_salary').show();
            $('#employee_salary').html(employee_salary);

            $('#intern_salary').hide();
            $('#addSalaryField').hide();
            $('#intern_salary').html('');
        }
    });

    $(document).on('click', '#addSalaryField', function(e) {
        $('#intern_salary').append(`<div class="d-flex gap-1 mb-2">
                                        <input type="text" name="basicSalaryTitle[]" placeholder="Enter Title" class="form-control" value="Basic Salary" readonly>
                                        <input type="text" name="basicSalaryMonthly[]" required placeholder="Basic Salary Monthly" class="form-control monthlyValue indianCurrencyFormat" value="">
                                        <input type="text" name="basicSalaryYearly[]" required placeholder="Basic Salary Yearly" class="form-control yearlyValue indianCurrencyFormat" value="">
                                        <div class="">
                                            <button type="button" class="btn btn-danger removeSalaryField"><i class="uil-minus"></i></button>
                                        </div>
                                    </div>`);
    });

    $(document).on('click', '.removeSalaryField', function(e) {
        $(this).parent().parent().remove();
    });
    // ############################################################################## internship salary
</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');
        // 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/salary_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_salary';
                    }, 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>