<?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($data)) { ?>
<div class="alert alert-danger" role="alert">
    <button class="close" data-dismiss="alert"></button>
    <strong>Danger: </strong>you can not edit this advance payment! 
    <br>
    This advance payment is not available.
</div>
<?php die(); } ?>
<style type="text/css">
    #AdvancePaymentTable thead tr th {
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #AdvancePaymentTable tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
    }
    #AdvancePaymentTable tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #AdvancePaymentTable 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;
    }
    #AdvancePaymentTable .Hint{
        position: absolute;
        font-size: 10px;
        font-weight: bold;
        height: 20px;
        line-height: 20px;
        bottom: 2px;
        right: 4px;
        color: rgb(153, 153, 153);   
    }
    #AdvancePaymentTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    #AdvancePaymentTable .Disc{
        width:50px;
    }
    #AdvancePaymentTable 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;
color:#ed9421 !important;    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870 !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker table tr td span:hover {
        background-color: #4c0870!important;
color:#ed9421 !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('AdvancePaymentDisabler') ?>
<form method="POST" action="" onsubmit="return false" id="AdvancePaymentForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <div id="AdvancePaymentSuccess" 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('add_advance_payment'); ?></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'); ?></label>
                                    <input id="Advance_Payment_Date" name="Advance_Payment_Date" class="form-control" value="<?php echo ($today); ?>" />
                                    <span class="input-group-addon "><i class="fa fa-calendar"></i></span>
                                </div>
                                <div class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown">
                                    <button type="button" class="btn btn-success btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                        <span><strong><?php print $IsEdit ? $data['Currency_Name'] . ' - ' . $data['Currency_Code'] : CommonLanguage::getMessage('Select_Currency'); ?></strong></span>
                                        <input id="currency_id" type="hidden" value="<?php echo $IsEdit ? $data['Currency_ID'] : $DefaultCurrencyID; ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" required/>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <?php echo($currency->GetLIListCurrency()); ?>
                                        <li class="divider"></li>
                                        <li><a class="LoadMore"><?php print CommonLanguage::getMessage('More'); ?>..</a></li>
                                    </ul>
                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table m-t-50" id='AdvancePaymentTable'>
                            <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('basic_salary'); ?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('description'); ?><span class="red-star">*</span></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('amount'); ?><span class="red-star">*</span></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('payment_type'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><input type="text" class="form-control AutoComplete Employee_Name" data-advance="<?php echo $IsEdit ? $data['Advance_Payment_ID'] : '' ?>" id="Employee_ID" value="<?php echo $IsEdit ? $data['Employee_Name'] : '' ?>" data-id="<?php echo $IsEdit ? $data['Employee_ID'] : '' ?>"></td>
                                    <td><input type="text" disabled class="form-control   Basic_Salary text-center" id="Basic_Salary" value="<?php echo $IsEdit ? $data['Basic_Salary'] : '' ?>"></td>
                                    <td><input type="text" class="form-control" id= "Advance_Payment_Description" value="<?php echo $IsEdit ? $data['Advance_Payment_Description'] : "" ?>"></td>
                                    <td><input type="number" class="form-control Quantity isnumber" id="Advance_Payment_Amount" value="<?php echo $IsEdit ? $data['Advance_Payment_Amount'] : "" ?>"></td>
                                    <td>
                                        <div class="form-group BootstrapDropDown">
                                            <select id="paymentType" class="full-width PaymentType" data-init-plugin="select2">
                                                <?php foreach ($payment_type as $type): ?>
                                                    <option data-code="<?php echo $type['Account_ID'] ?>" value="<?php echo $type['Account_ID']; ?>" <?php echo $IsEdit ? ($data['Payment_ID'] == $type['Account_ID'] ? 'selected' : '') : '' ?>   ><?php echo $type['Account_Code'] . ' - ' . $type['Account_Name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height" >
                        <button class=" btn btn-success btn-cons m-b-10 pull-right" id="AdvancePaymentSubmitButton" 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')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            advance_payment_percent = <?php echo json_encode(smc_session()['default_setting']['default_advance_payment_percent']); ?>,
            IsEdit = <?php echo json_encode($IsEdit); ?>,
            is_actual = <?php echo json_encode($is_actual); ?>;
    var current_Employee, current_Name, current_currency;
    var CurrencyRate = <?php echo json_encode($Extable); ?>;
    $(function () {
        EnableAutoComplete($("#AdvancePaymentTable .AutoComplete.Employee_Name"));
        $("#Advance_Payment_Date").datepicker({autoclose: true}).on("changeDate", function (e) {
            $(this).keyup();
        })

//        $("#Advance_Payment_Amount").on('change', function () {
//            var me = $(this).val(),
//                    FromC = $(".Basic_Salary").attr('data-curr'),
//                    ToC = $("#CurrencyDropDown input").val();
//            /* ConvertCurrency2(1500,84,144); From LBP(84) to USD(144) will return 1 */
//            var payment = (ConvertCurrency2(me, FromC, ToC));
////            $("#Advance_Payment_Amount").val(payment)
//        })

        $("#CurrencyDropDown li").on('click', function () {

            if (advance_payment_percent > 0) {
                var me = $('#Basic_Salary').attr('data-price') / 3;
                FromC = $(".Basic_Salary").attr('data-curr'),
                        ToC = $(this).val();
                /* ConvertCurrency2(1500,84,144); From LBP(84) to USD(144) will return 1 */
                var payment = (ConvertCurrency2(me, FromC, ToC));
                $("input.Quantity").attr('max', payment * advance_payment_percent / 100);
//            console.log(payment)
                $("#Advance_Payment_Amount").val('')

            }

        })



        $("#CurrencyDropDown li").click(function () {

            $(".CurrencyIndicator").html($(this).attr("MySymbol"))
            // setTimeout("UpdateSubmitButtonStatus()",100)
        })
        var Def = $("#CurrencyDropDown li").filter(function () {
            return $(this).attr("value") == $("#CurrencyDropDown input").val()
        })
        if (Def.length > 0) {
            $(".CurrencyIndicator").html(Def.attr("MySymbol"))
            $("> button > span", $("#CurrencyDropDown")).html(Def.text())
        }
        $("#AdvancePaymentForm").validate({
            ignore: ".ignore",
            rules: {
                Advance_Payment_Date: {required: true, date: true}
            }
        })
        $("#AdvancePaymentSubmitButton").on("click", ApplyPostMethod);
    })


    function EnableAutoComplete(who) {
        if (!who.hasClass("AutoAdded")) {
            who.autocomplete({
                source: is_actual ? 'xhr/ajaxAddEmployeeOverTime?hidden=true&month=' + $("#Advance_Payment_Date").val() : 'xhr/ajaxAddEmployeeOverTime&month=' + $("#Advance_Payment_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(ui.item.Currency_Symbol + ' ' + ui.item.Basic_Salary),
                            TR.find("input.Basic_Salary").attr('data-curr', ui.item.Currency_ID),
                            TR.find("input.Basic_Salary").attr('data-price', ui.item.Basic_Salary);

//                            TR.find("input.Quantity").val(ui.item.Basic_Salary / 3),
                    if (advance_payment_percent > 0) {
                        TR.find("input.Quantity").attr('max', ui.item.Basic_Salary * advance_payment_percent / 100);
                    }

                    //                            TR.find("input.Shift_Duration").val(ui.item.Shift_Duration),
                    current_Employee = ui.item.Employee_ID;
                    current_Name = ui.item.Employee_Name;
//                    current_currency = ui.item.Currency_ID;

                    $('#currency_id').val(ui.item.Currency_ID);
                    $('#CurrencyDropDown button span').html(ui.item.Currency_Name + ' - ' + ui.item.Currency_Code);
                    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 ($("#Advance_Payment_Amount").val() == '' || $("#Advance_Payment_Description").val() == '' || $("#Employee_ID").val() == '') {
            $("#AdvancePaymentSuccess").attr("class", "alert alert-danger").html(Required_Fields)
            $(document.body).animate({scrollTop: 0}, 800)
            return;
        }
        var Data = {
            Employee_ID: current_Employee ? current_Employee : $('#Employee_ID').attr('data-id'),
            Employee_Name: current_Name ? current_Name : $('#Employee_ID').val(),
            Advance_Payment_Date: $("#Advance_Payment_Date").val(),
            Currency_ID: $("#CurrencyDropDown input").val(),
            Advance_Payment_Amount: $("#Advance_Payment_Amount").val(),
            Advance_Payment_Description: $("#Advance_Payment_Description").val(),
            Payment_ID: $("#paymentType").val(),
            Payment_Account_Code: $("#paymentType").find("option:selected").attr('data-code'),
            is_actual: is_actual
        };
        if (IsEdit)
            Data.Advance_Payment_ID = $('#Employee_ID').attr('data-advance')
        $("#AdvancePaymentDisabler").removeClass('hidden');
        $.ajax({
            url: "HRMAjax/addAdvancePaymentRequest",
            method: "POST",
            data: Data,
            complete: function (v1, v2) {
                if (v2 == "success" & v1.responseText == 'OK') {
                    $("#AdvancePaymentSuccess").attr("class", "alert alert-success").html(Submitted_Successfully)
                } else {
                    $("#AdvancePaymentSuccess").attr("class", "alert alert-danger").html(v1.responseText)
                }
                $(document.body).animate({scrollTop: 0}, 800)
                $("#AdvancePaymentDisabler").addClass('hidden');
            }
        })

    }
</script>