<?php 
if ($IsEdit && $check_lock != '') { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong><?php echo $check_lock ?>
    </div>
    <?php
    return;
}
if ($IsEdit && empty($edit_data)) { ?>
<div class="alert alert-danger" role="alert">
    <button class="close" data-dismiss="alert"></button>
    <strong>Danger: </strong>you can not edit this <?php echo $is_deduction ? 'deduction' : 'overtime' ;?>! 
    <br>
    This <?php echo $is_deduction ? 'deduction' : 'overtime' ;?> is not available.
</div>
<?php die(); } ?>
<style type="text/css">
    #OverTimeTable thead tr th {
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #OverTimeTable tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
    }
    #OverTimeTable tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #OverTimeTable tbody tr:first-child td{
        padding-top:10px;
    }
    #InvoiceDiscountInput{
        display: inline-block;
        width: 40px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;
    }
    #OverTimeTable .Hint{
        position: absolute;
        font-size: 10px;
        font-weight: bold;
        height: 20px;
        line-height: 20px;
        bottom: 2px;
        right: 4px;
        color: rgb(153, 153, 153);   
    }
    #OverTimeTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    #OverTimeTable .Disc{
        width:50px;
    }
    #OverTimeTable input.wrong{
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
    }
    .DropDownForForms > .dropdown-menu{
        width:100%;
        height:200px;
        max-height:200px;
        overflow-y:scroll;
    }
    .DropDownForForms > .dropdown-menu{
        height:auto;
        cursor: pointer;
        overflow-y:auto;
    }
    .DropDownForForms > button{
        position:relative;
        z-index:999;
    }
    .DropDownForForms > button > input{
        position: absolute;
        left:5;
        top: 0;
        width:90%;
        cursor: pointer;
        -webkit-user-select:none;
        -moz-user-select:none;
        user-select:none;
        padding: 0;
        border: 0;
        background: transparent;
    }
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
    #AdvanceValue{
        width: 102px;
        display: inline-block;
    }
    .datepicker thead tr .dow {
        color:#4c0870!important;
    }
    .datepicker table tr td.day:hover {
        background: #4c0870!important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #4c0870!important;
    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870 !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870!important;
    }
    .datepicker table tr td span:hover {
        background-color: #4c0870!important;
        color:#fff;
    }
    datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .input-group-addon 
    {
        background-color:#4c0870 !important;
        color:#fff;
    }
</style>
<?php echo Forms::ModalLoader('OverTimeDisabler') ?>
<form method="POST" action="" onsubmit="return false" id="OverTimeForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <div id="OverTimeSuccess" class="hidden"></div>
                <div class="invoice padding-50 sm-padding-10">
                    <div class="container-sm-height">
                        <div class="row-sm-height">
                            <div class="col-md-9 col-sm-height sm-no-padding">
                                <h2 class="font-montserrat all-caps hint-text"><?php print CommonLanguage::getMessage($IsEdit ? ($is_deduction ? 'edit_deduction' : 'edit_overtime') : ($is_deduction ? 'add_deduction' : 'add_overtime')); ?></h2>
                                <br>
                            </div>
                            <div class="col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">
                                <div  class="form-group form-group-default input-group">
                                    <label><?php print CommonLanguage::getMessage('Date'); ?><span class="red-star">*</span></label>
                                    <input id="OverTime_Date" name="OverTime_Date" class="form-control" value="<?php echo ($IsEdit ? $edit_data['OverTime_Date'] : $date); ?>" />
                                    <span class="input-group-addon "><i class="fa fa-calendar"></i></span>
                                </div>
                                <div class="row" style="padding:0 5px;margin-bottom: 10px;">
                                    <div class="col-md-6">
                                        <?php print CommonLanguage::getMessage('from_time'); ?>
                                        <input type="text" value="<?php echo $IsEdit ? $edit_data['Overtime_Start_Time'] : '' ?>" id="Overtime_Start_Time" data-format="hh:mm:ss" name="Overtime_Start_Time" placeholder="From Time" class="form-control ignore">
                                    </div>
                                    <div class="col-md-6">
                                        <?php print CommonLanguage::getMessage('to_time'); ?>
                                        <input type="text"  value="<?php echo $IsEdit ? $edit_data['Overtime_End_Time'] : '' ?>" id="Overtime_End_Time" data-format="hh:mm:ss" name="Overtime_End_Time" placeholder="From Time" class="form-control ignore">
                                    </div>
                                </div>
                                <div class="row" style="padding:0 5px;margin-bottom: 15px;">
                                    <div class="col-md-6">
                                        <?php print CommonLanguage::getMessage('duration'); ?><span class="red-star">*</span>
                                        <input style="color:#000" type="text" value="<?php echo $IsEdit ? $edit_data['duraton_time'] : '00:00' ?>"  data-duration="<?php echo $IsEdit ? $edit_data['Overtime_Duration'] : '' ?>" id="Overtime_Duration" data-format="hh:mm:ss" name="Overtime_Duration" placeholder="From Time" class="form-control " required>
                                    </div>
                                    <div class="col-md-6">
                                        <?php print CommonLanguage::getMessage('type'); ?><span class="red-star">*</span>
                                        <select id="type" class="full-width" data-init-plugin="select2" required>
                                            <option value=""><?php echo CommonLanguage::getMessage('Select')?></option>
                                            <option value="0" <?php echo ($IsEdit && $edit_data['type']==0)  ? 'selected' : ''?>><?php echo CommonLanguage::getMessage('payroll')?></option>
                                            <option value="1" <?php echo ($IsEdit && $edit_data['type']==1)  ? 'selected' : ''?>><?php echo CommonLanguage::getMessage('cumulative')?></option>
                                            <option value="2" <?php echo ($IsEdit && $edit_data['type']==2)  ? 'selected' : ''?>><?php echo CommonLanguage::getMessage('cumulative_payroll')?></option>
                                        </select>
                                    </div>
                                </div>
                                <div class="row" style="padding:0 5px;margin-bottom: 15px;">

                                    <label><?php print CommonLanguage::getMessage('currency'); ?></label>
                                    <div id="CurrencyIDContainer" class=" " >
                                        <div class="form-group form-material floating ">
                                            <div class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown" data-symbol="<?php echo $IsEdit ? $edit_data['Currency_Symbol'] : smc_session()['local_currency_symbol']; ?>">
                                                <button type="button" class="btn btn-success btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                    <span><strong id="curency-label"><?php echo ($IsEdit ? $edit_data['Currency_Name'] : smc_session()['local_currency_name']) . ' - ' . ($IsEdit ? $edit_data['Currency_Symbol'] : smc_session()['local_currency_symbol']) ?></strong></span>
                                                    <input type="hidden"  value="<?php echo $IsEdit ? $edit_data['Currency_ID'] : smc_session()['local_currency'] ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" id="basic_salary_currency"/>
                                                </button>
                                                <!--                                                <ul class="dropdown-menu">
                                                <?php echo $CurList ?>
                                                                                                    <li class="divider"></li>
                                                                                                    <li><a class="LoadMore">More..</a></li>
                                                                                                </ul>-->
                                            </div>

                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table m-t-50" id='OverTimeTable'>
                            <thead>
                                <tr>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('employee_name'); ?><span class="red-star">*</span></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('amount_per_hr'); ?></th>
                                    <!--<th class="text-center hidden"><?php print CommonLanguage::getMessage('shift_duration'); ?></th>-->
                                    <!--                                    <th style="width:10%" class="text-center"><?php print CommonLanguage::getMessage('is_holiday'); ?></th>-->
                                    <!--<th style="width:10%" class="text-center "><?php print CommonLanguage::getMessage('is_paid'); ?></th>-->
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><input type="text" style="text-align:center" class="form-control AutoComplete Employee_Name ignore" id="Employee_ID" value="<?php echo $IsEdit ? $edit_data['Employee_Name'] : '' ?>" data-id="<?php echo $IsEdit ? $edit_data['Employee_ID'] : '' ?>"></td>
                                    <td><input type="text"style="text-align:center;color: #000;" value="<?php echo $IsEdit ? $edit_data['hr_unit_amount'] : '' ?>" class="form-control   Basic_Salary" <?php echo $permissions->hasPermission($is_deduction ? 'change_deduction_unit_amount' : 'change_overtime_unit_amount') ? '' : 'disabled' ?> id="Basic_Salary"></td>
                                    <!--<td><input type="text" style="text-align:center;color: #000;" disabled class="form-control Shift_Duration isnumber hidden" id="Shift_Duration" value="<?php echo smc_session()['default_hours'] ?>"></td>-->
                                    <!--                                    <td class="text-center"><input type="checkbox" data-init-plugin="switchery" id="Is_Holiday"/></td>-->
                                    <!--<td class="text-center"><input type="checkbox" data-init-plugin="switchery" id="Is_Paid"/></td>-->
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height" >
                        <div class="row row-sm-height b-a b-grey">
                            <div class="col-sm-8 col-sm-height col-middle clearfix sm-p-b-15">
                                <textarea id="note" name="note" class="form-control NoteTextArea"  placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?>"><?php echo $IsEdit ? $edit_data['note'] : '' ?></textarea>

                            </div>
                            <div class="col-sm-4 text-right bg-menu col-sm-height padding-15">
                                <!--                                                <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold">Total</h5>-->
                                <h1 class="no-margin text-white Quantity isnumber"><span class="CurrencyIndicator"></span>&nbsp;<span id="Overtime_Amount">0</span></h1>
                            </div>
                        </div>
                    </div>
                    <div class="container-sm-height" >
                        <button class=" btn btn-success btn-cons m-b-10 pull-right" id="OverTimeButton" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('Save'); ?></span></button>
                    </div>
                    <hr>
                </div>
            </div>
        </div>
    </div>
</form>
<script>
    var Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            auto_ded_desc = <?php echo json_encode(CommonLanguage::getMessage('auto_ded_desc')); ?>,
            auto_overtime_desc = <?php echo json_encode(CommonLanguage::getMessage('auto_overtime_desc')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>;
    var current_Employee, TotalAmountWithHoliday,
            overtime_day = <?php echo smc_session()['default_overtime'] ?>,
            is_actual = <?php echo json_encode($is_actual); ?>,
            is_deduction = <?php echo json_encode($is_deduction); ?>,
            emp_id = <?php echo json_encode($emp_id); ?>,
            emp_name = <?php echo json_encode($emp_name); ?>,
            duration = <?php echo json_encode($duration); ?>,
            hr_amount = <?php echo json_encode($hr_amount); ?>,
            duration_amt = <?php echo json_encode($duration_amt); ?>,
            rate = <?php echo json_encode($rate); ?>,
            IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>,
            ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : '',
            overtime_rate = 0;

    $(function () {
        $('#Overtime_Start_Time,#Overtime_End_Time').timepicker().val("")
//        $('#Overtime_Duration').timepicker({
//            showMeridian: false,
//            maxHours: 120
//        }).val(duration)
        $('#Overtime_Duration').val(duration)
//        current_Employee = emp_id;
        if (!IsEditMode)
            $("input.Employee_Name").val(emp_name)

        $("#Basic_Salary").on("keyup", function () {
//            console.log($("#Basic_Salary").val())
//            console.log($("#Basic_Salary").attr("data-duration"))
//            alert()
            CalculateTimeFromTo()
            CalculateAmount()
        })
        if (hr_amount != 0 || IsEditMode || emp_id != 0) {
            overtime_rate = rate;
            CalculateAmount()
        }
        if (hr_amount != 0 && !IsEditMode) {
//            console.log(hr_amount)
            $("input.Employee_Name").attr("data-id", emp_id)
            $("#Basic_Salary").val(parseFloat(hr_amount).toFixed(2))
//            $(".Basic_Salary").val(3000)
            $("#Overtime_Duration").attr("data-duration", duration_amt)

            CalculateAmount()
            $("#note").val((is_deduction ? auto_ded_desc : auto_overtime_desc) + ' ' + $("input.Employee_Name").val())
        }
        $('#Overtime_Start_Time,#Overtime_End_Time,#Overtime_Duration').on("input", function () {
            CalculateTimeFromTo()
            CalculateAmount()
        })
        //        $('#Is_Holiday').on("change", function () {
        //            CalculateAmount();
        //        })

        $('#Employee_ID').on("change", function () {
            CalculateTimeFromTo();
            CalculateAmount();
        })

        EnableAutoComplete($("#OverTimeTable .AutoComplete.Employee_Name"));
        $("#OverTime_Date").datepicker({autoclose: true}).on("changeDate", function (e) {
            $(this).keyup();
        })


        $("#OverTimeForm").validate({
            ignore: ".ignore",
        })
        $("#OverTimeButton").on("click", ApplyPostMethod);

    })

    function EnableAutoComplete(who) {
        if (!who.hasClass("AutoAdded")) {
            who.autocomplete({
                source: is_actual ? 'xhr/ajaxAddEmployeeOverTime?hidden=true&month=' + $("#OverTime_Date").val() : 'xhr/ajaxAddEmployeeOverTime?month=' + $("#OverTime_Date").val(),
                minLength: 0,
                select: function (event, ui) {
                    var TR = $(this).parents("tr");
                    TR.find("input.Employee_Name").val(ui.item.Employee_Name),
                            TR.find("input.Basic_Salary").val(parseFloat(ui.item.unit_hr).toFixed(2)).trigger("keyup"),
                            $("#basic_salary_currency").val(ui.item.Currency_ID)
                    $("#curency-label").html(ui.item.Currency_Name + ' - ' + ui.item.Currency_Symbol)
                    $(".CurrencyIndicator").html(ui.item.Currency_Symbol)
                    overtime_rate = is_deduction ? ui.item.deduction_rate : ui.item.overtime_rate;
                    //                            TR.find("input.Shift_Duration").val(ui.item.Shift_Duration),
                    TR.find("input.Employee_Name").attr("data-id", ui.item.Employee_ID);

//                    current_Name = ui.item.Employee_Name;
//                    current_currency = ui.item.Currency_ID;
                    return false;
                }
            }).focus(function () {
                $(this).autocomplete("search", $(this).val());
            }).autocomplete("instance")._resizeMenu = function (ul, items) {
                this.menu.element.outerWidth((who.width()) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
            }
            who.autocomplete("instance")._renderItem = function (ul, item) {
                var MyType = item.Employee_Name;
                return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
            }
            who.addClass("AutoAdded")
        }

    }
    function ApplyPostMethod() {
        if ($("#Employee_ID").val() == '' || $("#OverTime_Date").val() == '' || $('#Overtime_Duration').val() == '0:00' || $('#Overtime_Duration').val() == '' || $("#type").val()=='') {
            $("#OverTimeSuccess").attr("class", "alert alert-danger").html(Required_Fields)
            $(document.body).animate({scrollTop: 0}, 800)
            return;
        }
        var Data = {
            Employee_ID: $("input.Employee_Name").attr("data-id"),
            Employee_Name: $("input.Employee_Name").val(),
            Overtime_Amount: $("#Overtime_Amount").attr('data-value'),
            Overtime_Currency: $("#basic_salary_currency").val(),
            Overtime_Start_Time: $("#Overtime_Start_Time").val(),
            Overtime_End_Time: $("#Overtime_End_Time").val(),
            Overtime_Duration: $("#Overtime_Duration").attr('data-duration'),
            OverTime_Date: $("#OverTime_Date").val(),
            hr_unit_amount: $("#Basic_Salary").val(),
            type: $("#type").val(),
            hr_rate: overtime_rate,
            Is_Holiday: $("#Is_Holiday").is(":checked") ? 1 : 0,
//            Is_Paid: $("#Is_Paid").is(":checked") ? 1 : 0,
            is_actual: is_actual,
            is_deduction: is_deduction,
            note: $("#note").val()

        };
        if (IsEditMode) {
            Data.Overtime_ID = ID_Edit;
        }

        $("#OverTimeDisabler").show();
        $.ajax({
            url: IsEditMode ? "HRMAjax/editOverTimeRequest" : "HRMAjax/addOverTimeRequest",
            method: "POST",
            data: Data,
            complete: function (v1, v2) {
                if (v2 == "success" && v1.responseText == 'Ok') {
                    $("#OverTimeSuccess").attr("class", "alert alert-success").html(Submitted_Successfully)
                } else {
                    $("#OverTimeSuccess").attr("class", "alert alert-danger").html(v1.responseText)
                }
                $(document.body).animate({scrollTop: 0}, 800)
                $("#OverTimeDisabler").hide();
            }
        })

    }
    function CalculateTimeFromTo() {
        if ($("#Overtime_End_Time").val() != '' && $("#Overtime_Start_Time").val() != '') {
            var date1 = Date.parse("1/1/2010 " + $("#Overtime_End_Time").val()),
                    date2 = Date.parse("1/1/2010 " + $("#Overtime_Start_Time").val());
            var diff = Math.abs(date1 - date2) / 36e5;
            var X = new Date(date1 - date2)
            $("#Overtime_Duration").val(X.getUTCHours() + ":" + X.getUTCMinutes()).attr('data-duration', diff)
        } else {
            var data = $('#Overtime_Duration').val().split(':');
            var Hours = data[0] || 0;
            var Minutes = data[1] || 0;
            var OverTime = parseInt(Hours) + parseFloat(Minutes / 60);
            $("#Overtime_Duration").attr('data-duration', OverTime)

        }
    }
    function CalculateAmount() {
        var data = $('#Overtime_Duration').val().split(':');
        var Hours = data[0] || 0;
        var Minutes = data[1] || 0;
        var OverTime = parseInt(Hours) + parseFloat(Minutes / 60);
//        var Shift = $('#Shift_Duration').val().split(':');
//        var ShiftHours = Shift[0];
//        var ShiftMinutes = Shift[1];
//        var ShiftDuration = parseInt(ShiftHours) + parseFloat(ShiftMinutes / 60);
        var BasicSalary = $("#Basic_Salary").val();
//        var Currency = Salary[0];
//        var BasicSalary = Salary[1];

        //               console.log(BasicSalary)
        //               console.log(overtime_day)
        //               console.log(ShiftDuration)
        //               console.log(OverTime)
        //        
        //        if ($("#Is_Holiday").is(":checked")) {
        //            //overtime With Holiday        
        //            //(((basic salary/30 )/shifthrs)*2)*overtime
        //            var AmountWithHoliday = (((BasicSalary / overtime_day) / ShiftDuration) * 2) * OverTime;
        //            var TotalAmountWithHoliday = AddCommas(parseFloat(AmountWithHoliday + "").toFixed(2))
        //            $("#Overtime_Amount").empty().html(Currency + ' ' + TotalAmountWithHoliday);
        //            $("#Overtime_Amount").attr('data-value', AmountWithHoliday);
        //        } else {
        //overtime Without Holiday
        //(((basic salary/30 )/shifthrs)*1.5)*overtime
        var AmountWithoutHoliday = (BasicSalary * overtime_rate) * OverTime;
        console.log(BasicSalary + '==' + overtime_rate)

        var TotalAmountWithoutHoliday = AddCommas(parseFloat(AmountWithoutHoliday + "").toFixed(2))
        $("#Overtime_Amount").empty().html(TotalAmountWithoutHoliday || 0);
        $("#Overtime_Amount").attr('data-value', AmountWithoutHoliday);
        //        }
    }
</script>
