
<style>
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
</style>
<div class="modal fade " data-backdrop="static" id="addAccrued" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-14"></i></button>
                <h5><?php print CommonLanguage::getMessage('add_accrued_expenses'); ?></h5>
            </div>
            <div class="modal-body">
                <div id="AccruedUpdateValidationAlert" ></div>
                <div class="container-sm-height">
                    <div class="row-sm-height">
                        <div class="col-md-9 col-sm-height sm-no-padding">
                            <div>
                                <div class="input-group  col-md-4 center-margin pull-left" >
                                    <h2 class="font-montserrat all-caps hint-text"><?php print CommonLanguage::getMessage('accrued'); ?></h2>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div>
                                <div class="input-group  col-md-4 center-margin pull-left" >
                                    <span class="input-group-addon  complete">
                                        <i class="fa fa-search"></i>
                                    </span>
                                    <input type="text" id="Accrued_search_Supplier" class="form-control" placeholder="<?php print CommonLanguage::getMessage('enter_supplier_company'); ?>">
                                </div>
                                <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/ViewVendorList?is_pop=1" style="color:#4c0870;cursor:pointer"></span>

                                <div class="clearfix"></div>
                            </div>
                            <br>
                            <div id="addAccruedSupplierInfo">
                                <input type="hidden" name="Supplier_ID" required id="addAccruedSupplier_ID" value="0"/>
                                <div id="addAccruedSupplierInfoContent">
                                </div>
                            </div>
                        </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('start_date'); ?></label>
                                <input id="AccruedStartDate" name="AccruedStartDate" class="form-control" value="<?php echo ($today); ?>" />
                                <span class="input-group-addon complete"><i class="fa fa-calendar"></i></span>
                            </div>
                            <div  class="form-group form-group-default input-group">
                                <label><?php print CommonLanguage::getMessage('end_date'); ?></label>
                                <input id="AccruedEndDate" name="AccruedEndDate" class="form-control" value="<?php echo ($today); ?>" />
                                <span class="input-group-addon complete"><i class="fa fa-calendar"></i></span>
                            </div>
                            <?php echo Forms::CurrencyDropDown(1, 'complete'); ?>
                            <div style="display:flex;">
                                <div  style="width:48%;margin-right:2%">   
                                    <div class=" form-group" >   
                                        <label><?php print CommonLanguage::getMessage('branch'); ?></label>

                                        <input class=" full-width" id="branch_id" name="branch_id" type="hidden"  value="<?= (empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_id'] : smc_session()['user_accounts']['branch_id']) ?>" data-select-name='<?= json_encode((empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_name'] : smc_session()['user_accounts']['branch_name'])) ?>'/>


                                    </div>
                                </div>
                                <div style="width: 50%;" >
                                    <div  class="form-group " >
                                        <label><?php print CommonLanguage::getMessage('exchange_rate'); ?></label>
                                        <input type="number" step="any" min="0" id="current_rate" name="current_rate" class="form-control full-width current_rate" <?php echo ($DefaultCurrencyID == smc_session()['local_currency']) ? 'disabled' : '' ?>  value="<?php echo $IsEdit ? $edit_data['payments'][0]['current_rate'] : '' ?>" />
                                    </div>
                                </div>
                            </div>
                            <div   class="form-group " style="display: flex;">
                                <div   class="form-group <?php echo smc_session()['default_setting']['activate_accounting_job'] == 1 ? '' : 'hidden' ?>" style="width: 48%;margin-right:2%;" >
                                    <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                    <input type="hidden" class="full-width" id="job_id" />
                                </div>
                                <div class="<?php echo smc_session()['default_setting']['activate_project'] == 1 ? '' : 'hidden' ?>" style="width: 50%;" >
                                    <label><?php echo CommonLanguage::getMessage('project') ?></label>
                                    <input type="hidden" class="full-width" id="project_id" />
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="clearfix"></div>
                </div>
                <div class="table-responsive">
                    <table class="table m-t-50" id='AccruedTable'>
                        <thead>
                            <tr>
                                <th class="text-center" style="width:20%"><?php print CommonLanguage::getMessage('account_expense'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#4c0870;cursor:pointer"></span></th>
                                <th class="text-center" style="width:20%"><?php print CommonLanguage::getMessage('accrued_expense'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#4c0870;cursor:pointer"></span></th>
                                <th class="text-center" style="width:8%"><?php print CommonLanguage::getMessage('expected_amount'); ?></th>
                                <!--                                        <th class="text-center">Upload</th>-->
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="TableItem">
                                <td>
                                    <div class="form-group BootstrapDropDown">
                                        <input class=" full-width Expense_Account" id="Expense_Account"  type="hidden"  />

                                        <!--                                        <select class="full-width AccountCode" data-init-plugin="select2" id="Expense_Account">
                                        <?php foreach ($exp_acc as $account): ?>
                    <option value="<?php echo $account['Account_Code']; ?>"><?php echo $account['Account_Name'] . " - " . $account['Account_Code']; ?></option>
                                        <?php endforeach; ?>
</select>-->
                                    </div>
                                </td>
                                <td>
                                    <div class="form-group BootstrapDropDown">
                                        <input class=" full-width Expense_Accrued" id="Expense_Accrued"  type="hidden"  />
                                        <!--                                        <select class="full-width AccountCode" data-init-plugin="select2" id="Expense_Accrued">
                                        <?php foreach ($Accrued_expense_codes as $acc_exp): ?>
                    <option value="<?php echo $acc_exp['Account_Code']; ?>"><?php echo $acc_exp['Account_Name'] . " - " . $acc_exp['Account_Code']; ?></option>
                                        <?php endforeach; ?>
</select>-->
                                    </div>
                                </td>
                                <td><input type="text" class="form-control Amount isnumber" id="Expected_Amount"></td>
                                <!--                                        <td class="ImageTD"><button class="Remove btn btn-danger" onclick="RemoveCurrentTdFile(this);return false">Remove</button><button class="Add btn btn-complete"><input type="file" accept="image/*" class="form-control image_file" onchange="$(this).parents('td').addClass('Added')" />Add</button></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="Accrued_Desc" name="Accrued_Desc" class="form-control NoteTextArea" placeholder="<?php print CommonLanguage::getMessage('enter_description'); ?>"></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"><?php print CommonLanguage::getMessage('total'); ?></h5>
                            <h1 class="no-margin text-white AccuredTotal"><span class="CurrencyIndicator"><?php echo $DefaultCurrencySymbol ?></span>&nbsp;<span id="AccruedTotalDetails">0</span></h1>
                        </div>
                    </div>
                </div>
                <div class="container-sm-height" >
                    <button class=" btn btn-complete btn-cons m-b-10 pull-right " disabled  id="AccruedSubmitButton" 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>
            </div>
        </div>
    </div>

</div>
<script>
    var Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            CompanyLang = <?php echo json_encode(CommonLanguage::getMessage('company')); ?>,
            EmailLang = <?php echo json_encode(CommonLanguage::getMessage('Email')); ?>,
            PhoneLang = <?php echo json_encode(CommonLanguage::getMessage('Phone')); ?>,
            AddressLang = <?php echo json_encode(CommonLanguage::getMessage('address')); ?>,
            CountryLang = <?php echo json_encode(CommonLanguage::getMessage('country')); ?>,
            FinancialNbLang = <?php echo json_encode(CommonLanguage::getMessage('financial_nb')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            is_actual = <?php echo json_encode($Is_Actual); ?>;
    //var IsEditMode = < ?php echo $IsEdit ? "true" : "false"; ?>;
    $(function () {
        build_select2($('#Expense_Account'), "xhr/accIDSearch?type=Expense")
        build_select2($('#Expense_Accrued'), "xhr/accIDSearch?type=AccruedExpense")
        build_select2($("#branch_id"), "xhr/CommonSearch?col_id=branch_id&col_name=branch_name&table=tbl_organization_branches")
        build_select2($("#job_id"), "ACCAjax/JobSearch")
        build_select2($("#project_id"), "ACCAjax/projectSearch")
//        $("body").addClass("NoSearch")
//        $("body .search-link[data-toggle='search']").html("<i class='pg-search'></i>Click here to <span class='bold'>search</span>")
        $("#branch_id").on("change", function () {
            UpdatePrepaidSubmitButtonStatus()
        })
        $("#CurrencyDropDown li").on("click", function () {

            CurrencySymbol = $(this).attr("mysymbol")
            $(".CurrencyIndicator").html($(this).attr("mysymbol"))
            if ($(this).attr("value") == local_currency) {
                $("#current_rate").val(1).attr("disabled", "disabled")
            } else
                $("#current_rate").val("").removeAttr("disabled")
        })
        $("#AccruedStartDate,#AccruedEndDate").datepicker({autoclose: true}).on("changeDate", function () {
            $(this).keyup();
        })

        $("#Expected_Amount,#Accrued_search_Supplier").on("keyup", function () {

            UpdatePrepaidSubmitButtonStatus();

        })

        $("#AccruedSubmitButton").on("click", function () {
            //            alert(ToEditID)
            var DataForm = new FormData();
            var Data = {
                Expense_Code: $("#Expense_Account").val(),
                AccruedlExpense_Code: $("#Expense_Accrued").val(),
                Expected_Amount: $("#Expected_Amount").val(),
                Supplier_ID: $("#addAccruedSupplier_ID").val(),
                Currency_ID: $("#CurrencyDropDown button  input").val(),
                End_Date: $("#AccruedEndDate").val(),
                Start_Date: $("#AccruedStartDate").val(),
                Description: $("#Accrued_Desc").val(),
                branch_id: $("#branch_id").val(),
                job_id: $("#job_id").val(),
                project_id: $("#project_id").val(),
                current_rate: $("#current_rate").val(),
                is_actual: is_actual,
                ifEdit: ToEditID ? 1 : 0
            };
            if (ToEditID) {
                Data.Accrued_Expense_ID = ToEditID;

            }
            $.each(Data, function (key, value) {
                DataForm.append(key, value);
            })
            //            $("#AccruedUpdateValidationAlert").remove();
            //            var AlertBox = $('<div id="AccruedUpdateValidationAlert" class="WizardValidationAlert alert"></div>');
            //            AlertBox.insertAfter($("#addAccrued").find(".modal-dialog .modal-header").find("h5"))
            $("#AccruedIsBusy").remove()
            $("#addAccrued").append('<div id="AccruedIsBusy" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:9999;opacity:0"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>');

            $.ajax({
                url: "ACCAjax/addAccruedExpenseAjax",
                method: "POST",
                data: DataForm,
                processData: false,
                contentType: false,
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseText == "OK") {
                            ChangeTable();
                            $("#AccruedUpdateValidationAlert").attr("class", "alert alert-success").empty().html(Submitted_Successfully);
                            setTimeout(function () {

                                $("#addAccrued").modal('hide')
                                $("#AccruedUpdateValidationAlert").addClass("hidden")
                            }, 1500)
                        } else {
                            $("#AccruedUpdateValidationAlert").attr("class", "alert alert-danger").empty().html(v1.responseText);

                        }
                    } else {
                        $("#AccruedUpdateValidationAlert").attr("class", "alert alert-danger").empty().html(Failed_Submit);
                    }
                    $("#AccruedIsBusy").remove();
                }
            })
        });
    })



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

        $(".CurrencyIndicator").html($(this).attr("mysymbol"))
    })

    function UpdatePrepaidSubmitButtonStatus() {

        var amount = $("#Expected_Amount").val(),
                SupplierID = $("#addAccruedSupplier_ID").val();
        $(".AccuredTotal span").eq(1).html(amount) 
        if (amount == "" || SupplierID == 0 || (($("#Expected_Amount").val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)) {

            $("#AccruedSubmitButton").attr("disabled", "disabled")
        } else {

            $("#AccruedSubmitButton").removeAttr("disabled")
        }

    }
    function AccruedSupplierSearch() {
        $("#Accrued_search_Supplier").autocomplete({
            source: 'xhr/ajaxVendor?' + (ToEditID == 0 ? 'Status_ID=1' : ('is_edited=' + $("#addAccruedSupplier_ID").val())),
            minLength: 2,
            select: function (event, ui) {
                var Content = "";
                Content += "<strong><span class='Name'>" + ui.item.Supplier_Name + "</span></strong>";
                Content += "<div><strong>" + CompanyLang + ": </strong><span class='Company'>" + ui.item.Supplier_Company + "</span></div>";
                Content += "<div><strong>" + EmailLang + ": </strong><span class='Address'>" + ui.item.Supplier_Email + "</span></div>";
                Content += "<div><strong>" + PhoneLang + ": </strong><span class='Phone'>" + ui.item.Supplier_Phone + "</span></div>";
                Content += "<div><strong>" + AddressLang + ": </strong><span class='Discount'>" + ui.item.Supplier_Address + "</span></div>";
                Content += "<div><strong>" + CountryLang + ": </strong>" + ui.item.Country_Name + "</div>";
                Content += "<div><strong>" + FinancialNbLang + ": </strong>" + ui.item.Account_Code + "</div>";
                $("#addAccruedSupplierInfoContent").html(Content)
                $("#Supplier_ID-error").remove()
                $("#addAccruedSupplier_ID").removeClass("error").val(ui.item.Supplier_ID);
                UpdatePrepaidSubmitButtonStatus();

            }
        })
                .autocomplete("instance")._renderItem = function (ul, item) {
            return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='Column1'><i class='fa fa-file-o'></i></td><td><strong>" + item.Supplier_Name + "</strong></td></tr></table>").appendTo(ul)
        }
        $("#Accrued_search_Supplier").autocomplete("instance")._resizeMenu = function (ul, items) {
            this.menu.element.outerWidth($("#Accrued_search_Supplier").width() + parseFloat($("#Accrued_search_Supplier").css("padding-left")) + parseFloat($("#Accrued_search_Supplier").css("padding-right")) + 2);
        }
    }


</script>
