<?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;
}
?>
<!-- This modal is used to add prepaid expense or prepaid income ex. insurance
prepaid accounts are for expenses or incomes that are prepaid and need to be devided into period of time 
we include them in this type since they must be added as expense or income for each month of the defined period
but at same time we enter them just once in the system upon the entire period
-->
<style>
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
    
</style>
<div class="container-fluid container-fixed-lg">
    <div class="panel panel-default">
        <div class="panel-body">
            <?php echo Forms::ModalLoader('PrepaidIsBusy') ?>
            <div id="UpdateValidationAlert" ></div>

            <div class="invoice">
                <div class="container-sm-height">
                    <form id="prepaid-form" action="javascript:void(0);">
                        <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" >
                                            <h4 class="font-montserrat all-caps hint-text"><?php print $title; ?></h4>
                                        </div>
                                        <div class="clearfix"></div>
                                    </div>
                                    <div>
                                        <div class="input-group  col-md-4 center-margin pull-left " >
                                            <label><?php print CommonLanguage::getMessage($Income ? 'choose_customer' : 'choose_supplier'); ?></label><span class="red-star">*</span><span class="fa fa-plus-circle m-l-5 openFrame" data-src="<?php echo $IsSales ? "Inventory/CustomerList?is_pop=1" : "Inventory/ViewVendorList?is_pop=1" ?>" style="color:#4c0870;cursor:pointer"></span>
                                            <input class="search_supplier full-width" id="search_supplier" name="search_supplier" type="hidden" value="<?= ($IsEdit) ? $edit_arr['Supplier_ID'] : ''; ?>" data-select-name='<?= json_encode(($IsEdit) ? $edit_arr['Supplier_Name'] : ""); ?>' />
                                        </div>
                                    </div>
                                    <br>
<!--                                    <div id="AddPrepaidSupplierInfo">
                                        <input type="hidden" name="Supplier_ID" required id="addPrepaidIncomeSupplier_ID" value="0" required/>
                                        <div id="AddPrepaidSupplierInfoContent">
                                        </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="StartDate" name="StartDate" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['Start_Date']: $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="EndDate" name="EndDate" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['End_Date']: $today); ?>" />
                                        <span class="input-group-addon complete"><i class="fa fa-calendar"></i></span>
                                    </div> 
                                    <div class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown" data-symbol="<?php echo ($IsEdit ) ? $edit_arr['Currency_Symbol'] : $DefaultCurrencySymbol; ?>">
                                            <button type="button" class="btn btn-complete btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                <span><strong><?php echo ($IsEdit) ? ($edit_arr['Currency_Name'] . ' - ' . $edit_arr['Currency_Symbol']) : CommonLanguage::getMessage('select') ?></strong></span>
                                                <input type="hidden"  value="<?php echo ($IsEdit ) ? $edit_arr['Currency_ID'] : $DefaultCurrencyID ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" name="Currency_ID"/>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <?php echo $CurList ?>
                                                <li class="divider"></li>
                                                <li><a class="LoadMore">More..</a></li>
                                            </ul>
                                        </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="<?= ($IsEdit ? $edit_arr['branch_id']: (empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_id'] : smc_session()['user_accounts']['branch_id'])) ?>" data-select-name='<?= json_encode($IsEdit ? $edit_arr['branch_name'] : (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 ($IsEdit && $edit_arr['Currency_ID'] ==smc_session()['local_currency']) || (!$IsEdit && $DefaultCurrencyID == smc_session()['local_currency']) ? 'disabled' : '' ?>  value="<?php echo $IsEdit ? $edit_arr['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" value="<?php echo $IsEdit && !empty($edit_arr['job_id']) ? $edit_arr['job_id'] : ''?>" data-select-name='<?= json_encode($IsEdit && !empty($edit_arr['job_name'])  ? $edit_arr['job_name'] : '')?>' />
                                        </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" value="<?php echo $IsEdit && !empty($edit_arr['project_id'])  ? $edit_arr['project_id'] : ''?>" data-select-name='<?= json_encode($IsEdit && !empty($edit_arr['project_name']) ? $edit_arr['project_name'] : '')?>'/>
                                        </div>

                                    </div>
                                </div>
                            </div>
                        </div>
                        <div>
                            <div class="clearfix"></div>
                        </div>
                        <div class="table-responsive">
                            <table class="table m-t-50" id='PrepaidTable'>
                                <thead>
                                    <tr>
                                        <th class="text-center" style="width:20%"><?php print CommonLanguage::getMessage('account'); ?><span class="red-star">*</span><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('prepaid_account'); ?><span class="red-star">*</span><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('amount'); ?><span class="red-star">*</span></th>
                                        <th class="text-center" style="width:8%"><?php print CommonLanguage::getMessage('amount_month'); ?><span class="red-star">*</span></th>
                                        <th class="text-center" style="width:8%"><?php print CommonLanguage::getMessage('paid_amount'); ?></th>
                                        <th class="text-center" style="width:8%"><?php print CommonLanguage::getMessage('payment_type'); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="TableItem">
                                        <td>
                                            <div class="form-group BootstrapDropDown">
                                                <input class=" full-width Account_Code" id="Account_Code" name="Account_Code"  type="hidden" required  value="<?php echo $IsEdit ? $edit_arr['Account_ID'] : ''?>" data-select-name='<?= json_encode($IsEdit ? $edit_arr['Main_Account'] : '')?>'/>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="form-group BootstrapDropDown">
                                                <input class=" full-width Prepaid_Account" id="Prepaid_Account" name="Prepaid_Account" type="hidden" required value="<?php echo $IsEdit ? $edit_arr['Prepaid_Account_ID'] : ''?>" data-select-name='<?= json_encode($IsEdit ? $edit_arr['Prepaid_Account_Name'] : '')?>'/>
                                            </div>
                                        </td>
                                        <td><input type="text" class="form-control Amount  isnumber" min="0" name="Total_Amount" id="Total_Amount" required value="<?php echo $IsEdit ? $edit_arr['Total_Amount'] : ''?>"></td>
                                        <td><input type="text" class="form-control Amount isnumber" min="0" name="Amount_PerMonth" id="Amount_PerMonth" required  value="<?php echo $IsEdit ? $edit_arr['Amount_PerMonth'] : ''?>"></td>
                                        <td><input type="text" class="form-control Amount isnumber" min="0" name="Paid_Amount" id="Paid_Amount" value="<?php echo $IsEdit ? $edit_arr['Paid_Amount'] : ''?>"></td>
                                        <td>
                                            <div class="form-group BootstrapDropDown">
                                                <select class="full-width AccountCode" data-init-plugin="select2" id="Payment_ID">
                                                    <?php foreach ($payment_types as $payment): ?>
                                                        <option value="<?php echo $payment['Account_ID']; ?>" <?php echo $IsEdit && $payment['Account_ID'] == $edit_arr['Payment_ID'] ? 'selected' : ''?>><?php echo $payment['Account_Code'] . ' - ' . $payment['Account_Name']; ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </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="Prepaid_Desc" name="Prepaid_Desc" class="form-control NoteTextArea" placeholder="<?php print CommonLanguage::getMessage('enter_description'); ?>" ><?php echo $IsEdit ? $edit_arr['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 prepaidmodalTotal"><span class="CurrencyIndicator"><?php echo $IsEdit ? $edit_arr['Currency_Symbol'] : $DefaultCurrencySymbol ?></span>&nbsp;<span id="PrepaidTotalDetails"><?php echo $IsEdit ? $edit_arr['Total_Amount'] : 0?></span></h1>
                                </div>
                            </div>
                        </div>
                        <div class="container-sm-height" >
                            <button class=" btn btn-complete btn-cons m-b-10 pull-right "  id="PrepaidSubmitButton" 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>
                    </form>
                </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')); ?>,
            is_actual = <?php echo json_encode($Is_Actual); ?>,
            local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
            Income = <?php echo $Income ? "true" : "false" ?>,
            IsEdit = <?php echo json_encode($IsEdit)?>,
            ToEditID = IsEdit ? <?php echo json_encode($id); ?> : '',
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>;
    $(function () {

        build_select2($(".Account_Code"), "xhr/accIDSearch?type=Expense")
        build_select2($(".Prepaid_Account"), "xhr/accIDSearch?type=PrepaidExpense")
        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")
        build_select2($("#search_supplier"), (Income ? ("xhr/customerSearch") : "xhr/supplierSearch"))

        $("#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")
        })
        $("#StartDate,#EndDate").datepicker({autoclose: true}).on("changeDate", function () {
            $(this).keyup();
        })
        $("#Total_Amount").on("keyup", function () {
            var amount = $(this).val()
            $(".prepaidmodalTotal span").eq(1).html(public_round_number(amount))
        })
        $("#Total_Amount,#Paid_Amount").on("change", function () {
            $("#Total_Amount").val( public_round_number($("#Total_Amount").val()))
            $("#Paid_Amount").val( public_round_number($("#Paid_Amount").val()))

        })

//        $("#Total_Amount,#Amount_PerMonth,#Paid_Amount,#Prepaid_search_Supplier").on("keyup", function () {
//            UpdatePrepaidSubmitButtonStatus();
//        });

        $("#PrepaidSubmitButton").on("click", function () {
            if (!$("#prepaid-form").valid()) {
                return;
            }
            var DataForm = new FormData();
            var Data = {
                Account_Code: $("#Account_Code").val(),
                Prepaid_Account: $("#Prepaid_Account").val(),
                Payment_ID: $("#Payment_ID").val(),
                Supplier_ID: $("#search_supplier").val(),
                Total_Amount: $("#Total_Amount").val(),
                Currency_ID: $("#CurrencyDropDown button input").val(),
                Amount_PerMonth: $("#Amount_PerMonth").val(),
                Start_Date: $("#StartDate").val(),
                End_Date: $("#EndDate").val(),
                Description: $("#Prepaid_Desc").val(),
                Old_Description: $("#Prepaid_Desc").attr('old-desc'),
                Paid_Amount: $("#Paid_Amount").val(),
                branch_id: $("#branch_id").val(),
                job_id: $("#job_id").val(),
                project_id: $("#project_id").val(),
                current_rate: $("#current_rate").val(),
                Prepaid_ID: ToEditID ? ToEditID : 0,
                is_actual: is_actual,
                is_expense: Income ? 0 : 1
            };
            //            if(IsEditMode){
            //                Data.Prepaid_ID = ToEditID;
            //
            //            }
            $.each(Data, function (key, value) {
                DataForm.append(key, value);
            })
            //            $("#UpdateValidationAlert").remove();
            //            var AlertBox = $('<div id="UpdateValidationAlert" class="WizardValidationAlert alert"></div>');
            //            AlertBox.insertAfter($("#addPrepaid").find(".modal-dialog .modal-header").find("h5"))
            $("#PrepaidIsBusy").removeClass('hidden')
//            $("#addPrepaid").append('<div id="PrepaidIsBusy" 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/addPrepaidAjax",
                method: "POST",
                data: DataForm,
                processData: false,
                contentType: false,
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseText == 'OK') {
                            $("#UpdateValidationAlert").attr("class", "alert alert-success").empty().html(Submitted_Successfully);
//                            ChangeTable()
                            setTimeout(function () {
                                $("#addPrepaid").modal('hide')
                                $("#UpdateValidationAlert").addClass('hidden')
//                                clear_input()
                            }, 1500)
                            $(document.body).animate({scrollTop: 0}, 800)
                        } else {
                            $("#UpdateValidationAlert").attr("class", "alert alert-danger").empty().html(v1.responseText);
                        }
                    } else {
                        $("#UpdateValidationAlert").attr("class", "alert alert-danger").empty().html(Failed_Submit);
                    }
                    $("#PrepaidIsBusy").addClass('hidden');
                }
            })
        });
        $("#CurrencyDropDown li").on("click", function () {
            $(".CurrencyIndicator").html($(this).attr("mysymbol"))
        })
    })
//    function UpdatePrepaidSubmitButtonStatus() {
//        var totalAmount = $("#Total_Amount").val(),
//                AmountPerMonth = $("#Amount_PerMonth").val(),
//                PaidAmount = $("#Paid_Amount").val(),
//                SupplierID = $("#search_supplier").val();
//        if ((totalAmount == "" && AmountPerMonth == "" && PaidAmount == "") || SupplierID == 0 || ((totalAmount).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null) || ((AmountPerMonth).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null) || ((PaidAmount).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null))
//            $("#PrepaidSubmitButton").addClass("Disabled")
//        else
//            $("#PrepaidSubmitButton").removeClass("Disabled")
//    }
//    function enableSupplierPrepaidAutoComplete() {
//        $("#Prepaid_search_Supplier").autocomplete({
//            source: 'xhr/ajaxVendor?' + (ToEditID == 0 ? 'Status_ID=1' : ('is_edited=' + $("#addPrepaidIncomeSupplier_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>";
//                $("#AddPrepaidSupplierInfoContent").html(Content)
//                $("#Supplier_ID-error").remove()
//                $("#addPrepaidIncomeSupplier_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)
//        }
//        $("#Prepaid_search_Supplier").autocomplete("instance")._resizeMenu = function (ul, items) {
//            this.menu.element.outerWidth($("#Prepaid_search_Supplier").width() + parseFloat($("#Prepaid_search_Supplier").css("padding-left")) + parseFloat($("#Prepaid_search_Supplier").css("padding-right")) + 2);
//        }
//    }
</script>
