<?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_id = mysqli_real_escape_string($db, base64_decode($_GET['edit']));
$edit = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM `appraisal_letter` WHERE `id`='$edit_id' "));
$edit_salary_id = $edit["salary_id"];

// $user_data = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM `users` WHERE `employee_id`='$edit[employee_id]' "));
// $salary_data = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM `employee_salary` WHERE id='$edit[salary_id]'"));
// $fixed = !empty($salary_data['fixed']) ? $salary_data['fixed'] : '[]';
// $add_on = !empty($salary_data['add_on']) ? $salary_data['add_on'] : '[]';
// $deduction = !empty($salary_data['deduction']) ? $salary_data['deduction'] : '[]';

?>
<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>

            <div class="row">
                <div class="col-lg-12">
                    <form id="form_submit" class="parsley-examples">
                        <h3 class="mt-1 mb-4">Appraisal Letter</h3>

                        <div class="card">
                            <div class="card-body p-4">
                                <h4 class="header-title mt-1 mb-4">Employee Details</h4>

                                <div class="row">

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label" for="employee_id">Employee Id</label>
                                            <select required id="employee_id" name="employee_id" data-plugin="customselect" 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 user">
                                                <option></option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="name">User Name<span class="text-danger">*</span></label>
                                            <input type="text" name="name" required placeholder="Enter User name" class="form-control" id="name" value="">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="email">Email</label>
                                            <input type="text" name="email" placeholder="Enter user email" class="form-control" id="email" value="">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="phone">Phone</label>
                                            <input type="text" name="phone" placeholder="Enter user phone" class="form-control" id="phone" value="">
                                        </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="">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="probationDate">Probation Date</label>
                                            <input type="date" name="probationDate" class="form-control" id="probationDate" value="">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="noticePeriod">Notice Period (In Days)<span class="text-danger">*</span></label>
                                            <input type="text" name="noticePeriod" pattern="[0-9]+" data-parsley-type="number" required placeholder="Enter Notice Period" class="form-control" id="noticePeriod" value="">
                                        </div>
                                    </div>


                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="department">Department<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="department" class="form-control custom-select-picker-ajax" data-search="departments" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Department" id="department" required>
                                                <option></option>
                                            </select>
                                        </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'=>'', '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>Role<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" id="user_role" name="user_role" class="form-control custom-select-picker" data-placeholder="Select Role" required>
                                                <option></option>
                                                <?php if ($user_role == 0) { ?>
                                                    <option value="0">Boss</option>
                                                    <option value="1">Manager</option>
                                                <?php } ?>
                                                <option value="2">Employee</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Leader<span class="text-danger">*</span></label>
                                            <select data-plugin="customselect" name="leader" id="leader" class="form-control custom-select-picker-ajax" data-search="managers" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Leader" required>
                                                <option></option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="level">Level<span class="text-danger">*</span></label>
                                            <input type="text" name="level" required placeholder="Enter Level" class="form-control" id="level" value="<?php echo $edit['level']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="issueDate">Issue Date<span class="text-danger">*</span></label>
                                            <input type="date" name="issueDate" class="form-control" id="issueDate" required value="<?php echo (isset($edit['issue_date']) ? ((!empty($edit['issue_date'])) ? date("Y-m-d", strtotime($edit['issue_date'])) : '') : ''); ?>">
                                        </div>
                                    </div>

                                </div>

                            </div>
                        </div>

                        <div class="card">
                            <div class="card-body p-4">
                                <h4 class="header-title mt-1 mb-4">Salary Details</h4>

                                <div class="show_old_salaries" style="display:none;"></div>

                                <hr class="mb-2 mt-4">
                                <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="">
                                            </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="">
                                            </div>
                                        </div>
                                    </div>
                                </div>


                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="revisionDate">Revision Date<span class="text-danger">*</span></label>
                                            <input type="date" name="revisionDate" required class="form-control" id="revisionDate" value="">
                                        </div>
                                    </div>
                                </div>


                                <hr>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="incentiveTerm">Performance Incentive</label>
                                            <textarea name="incentiveTerm" id="incentiveTerm"><?php echo $edit['incentive_term']; ?></textarea>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>

                        <input type="hidden" name="editSalaryId" id="editSalaryId" value="">
                        <input type="hidden" name="revisionEndDate" id="revisionEndDate" value="">
                        <div class="card">
                            <div class="card-body p-4">
                                <?php if (isset($edit['id'])) { ?>
                                    <input type="hidden" name="editAppraisalId" id="editAppraisalId" value="<?php echo $edit['id']; ?>">
                                    <input type="hidden" name="revisionOldDate" id="revisionOldDate" value="">
                                    <input class="btn btn-primary mr-1" name="UpdateAppraisal" id="UpdateAppraisal" type="hidden">
                                <?php } else { ?>
                                    <input class="btn btn-primary mr-1" name="addAppraisal" id="addAppraisal" 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="UpdateAppraisal" id="UpdateAppraisal" type="submit">Update Letter</button>
                                    <?php } else { ?>
                                        <button class="btn btn-primary mr-1" name="addAppraisal" id="addAppraisal" type="submit">Add Letter</button>
                                    <?php } ?>
                                </div>
                            </div>
                        </div>

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

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

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

</div>

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


<?php
include "pin/footer.php";
require_once 'salaryComponentsSupport.php';
?>
<script src="https://cdn.ckeditor.com/4.21.0/standard/ckeditor.js"></script>
<script>
    CKEDITOR.replace('incentiveTerm');
</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, letter_name: 'appraisal_letter' },
                dataType: 'json',
                success: function(res) {
                    // console.log(res);
                    if (res.status === 200) {
                        if(res.user_data){
                            $('#name').val(res.user_data.name);
                            $('#email').val(res.user_data.email);
                            $('#phone').val(res.user_data.phone);
                            $('#joiningDate').val(res.user_data.joining_date);
                            $('#probationDate').val(res.user_data.probation_date);
                            $('#noticePeriod').val(res.user_data.notice_period);
                            $('#department').val(res.user_data.department).trigger('change');
                            $('#designation').val(res.user_data.designation).trigger('change');
                            $('#user_role').val(res.user_data.role).trigger('change');
                            $('#leader').val(res.user_data.leader).trigger('change');
                        }

                        show_old_salaries(res);

                    } 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)}`);
                }
            });
        }
    });


    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();
        var incentiveTerm = CKEDITOR.instances['incentiveTerm'].getData();
        form_data = form_data.replace(/(^|&)(incentiveTerm=[^&]*)/g, '&incentiveTerm=' + encodeURIComponent(incentiveTerm));
        console.log(form_data);

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