

<!-- This modal is used to add prepaid prepaid income
prepaid accounts are for 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 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="modal fade" data-backdrop="static" id="addPrepaidIncome" 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_prepaid'); ?></h5>
            </div>
            <div class="modal-body">
                <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 CommonLanguage::getMessage('prepaid_income'); ?></h4>
                                </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="Income_Search_Supplier" class="form-control" placeholder="<?php print CommonLanguage::getMessage('customer_name'); ?>">
                                </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="addPrepaidIncomeSupplierInfo">
                                <input type="hidden" name="Supplier_ID" required id="addPrepaidIncomeSupplier_ID" value="0"/>
                                <div id="addPrepaidIncomeSupplierInfoContent">
                                </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="Income_Start_Date" name="Income_Start_Date" 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="Income_End_Date" name="Income_End_Date" 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="inc_branch_id" name="inc_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="inc_current_rate" name="inc_current_rate" class="form-control full-width inc_current_rate" <?php echo ($DefaultCurrencyID == smc_session()['local_currency']) ? 'disabled' : '' ?>   />
                                    </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="inc_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="inc_project_id" />
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="clearfix"></div>
                </div>
                <div class="table-responsive">
                    <table class="table m-t-50" id='IncomeTable'>
                        <thead>
                            <tr>
                                <th class="text-center" style="width:20%"><?php print CommonLanguage::getMessage('account'); ?><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="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'); ?></th>
                                <th class="text-center" style="width:8%"><?php print CommonLanguage::getMessage('amount_month'); ?></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>
                                <!--                                        <th class="text-center">Upload</th>-->
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="TableItem">
                                <td>
                                    <div class="form-group BootstrapDropDown">
                                        <input class=" full-width Income_Account_Code" id="Income_Account_Code"  type="hidden"  />
                                    </div>
                                </td>
                                <td>
                                    <div class="form-group BootstrapDropDown">
                                        <input class=" full-width Prepaid_Income" id="Prepaid_Income"  type="hidden"  />
                                    </div>
                                </td>
                                <td><input type="text" class="form-control Amount isnumber" id="Income_Total_Amount"></td>
                                <td><input type="text" class="form-control Amount isnumber" id="Permonth_Income"></td>
                                <td><input type="text" class="form-control Amount isnumber" id="Income_Paid_Amount"></td>
                                <td>
                                    <div class="form-group BootstrapDropDown">
                                        <select class="full-width AccountCode" data-init-plugin="select2" id="Income_Payment_ID">
                                            <?php foreach ($payment_types as $payment): ?>
                                                <option value="<?php echo $payment['Account_ID']; ?>"><?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="Income_Desc" name="Income_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 Income_Amount"><span class="CurrencyIndicator"></span>&nbsp;<span id="PrepaidTotalDetails">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="IncomeSubmitButton" 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')); ?>,
            is_actual = <?php echo json_encode($Is_Actual); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>;
    $(function () {
        build_select2($(".Income_Account_Code"), "xhr/accIDSearch?type=Income", false, 'diff_class');
        build_select2($(".Prepaid_Income"), "xhr/accIDSearch?type=PrepaidIncome", false, 'diff_class');
        build_select2($("#inc_job_id"), "ACCAjax/JobSearch")
        build_select2($("#inc_project_id"), "ACCAjax/projectSearch")
        build_select2($("#inc_branch_id"), "xhr/CommonSearch?col_id=branch_id&col_name=branch_name&table=tbl_organization_branches")
        $("#inc_branch_id").on("change", function () {
            UpdatePrepaidIncomeSubmitButtonStatus()
        })
        $("#CurrencyDropDown li").on("click", function () {

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

            var amount = $(this).val()
            $(".Income_Amount span").eq(1).html(amount)

        })
        $("#Income_Total_Amount,#Permonth_Income,#Income_Paid_Amount,#Income_Search_Supplier").on("keyup", function () {
            UpdatePrepaidIncomeSubmitButtonStatus()


        })
        $("#IncomeSubmitButton").on("click", function () {
            var DataForm = new FormData();
            var Data = {
                Account_Code: $("#Income_Account_Code").val(),
                Prepaid_Account: $("#Prepaid_Income").val(),
                Payment_ID: $("#Income_Payment_ID").val(),
                Supplier_ID: $("#addPrepaidIncomeSupplier_ID").val(),
                Total_Amount: $("#Income_Total_Amount").val(),
                Currency_ID: $("#addPrepaidIncome #CurrencyDropDown button input").val(),
                Amount_PerMonth: $("#Permonth_Income").val(),
                Start_Date: $("#Income_Start_Date").val(),
                End_Date: $("#Income_End_Date").val(),
                Description: $("#Income_Desc").val(),
                Old_Description: $("#Income_Desc").attr('old-desc'),
                Paid_Amount: $("#Income_Paid_Amount").val(),
                branch_id: $("#inc_branch_id").val(),
                job_id: $("#inc_job_id").val(),
                project_id: $("#inc_project_id").val(),
                current_rate: $("#inc_current_rate").val(),
                Prepaid_ID: ToEditID ? ToEditID : 0,
                is_actual: is_actual,
                is_expense: Income ? 0 : 1
            };

            $.each(Data, function (key, value) {
                DataForm.append(key, value);
            })
            $("#IncomeValidateAlert").remove();
            var AlertBox = $('<div id="IncomeValidateAlert" class="WizardValidationAlert alert"></div>');
            AlertBox.insertAfter($("#addPrepaidIncome").find(".modal-dialog .modal-header").find("h5"))
            $("#IncomeIsBusy").remove()
            $("#addPrepaidIncome").append('<div id="IncomeIsBusy" 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') {
                            $("#IncomeValidateAlert").attr("class", "alert alert-success").empty().html(Submitted_Successfully);
                            ChangeTable()
                            setTimeout(function () {
                                $("#addPrepaidIncome").modal('hide')
                                $("#IncomeValidateAlert").addClass("hidden")
                                clear_input()
                            }, 1500)
                        } else {
                            $("#IncomeValidateAlert").attr("class", "alert alert-danger").empty().html(v1.responseText);

                        }
                    } else {
                        $("#IncomeValidateAlert").attr("class", "alert alert-danger").empty().html(Failed_Submit);
                    }
                    $("#IncomeIsBusy").remove();
                }
            })
        });
    })
    function UpdatePrepaidIncomeSubmitButtonStatus() {
        var IncometotalAmount = $("#Income_Total_Amount").val(),
                IncomeAmountPerMonth = $("#Permonth_Income").val(),
                IncomePaidAmount = $("#Income_Paid_Amount").val(),
                SupplierID = $("#addPrepaidIncomeSupplier_ID").val();
        if (IncometotalAmount == "" && IncomeAmountPerMonth == "" && IncomePaidAmount == "" || SupplierID == 0 || ((IncometotalAmount).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null) || ((IncomeAmountPerMonth).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null) || ((IncomePaidAmount).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null))
            $("#IncomeSubmitButton").addClass("Disabled")
        else
            $("#IncomeSubmitButton").removeClass("Disabled")

    }
    function enableSupplierPrepaidIncomeAutoComplete() {
        $("#Income_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>";
                $("#addPrepaidIncomeSupplierInfoContent").html(Content)
                $("#Supplier_ID-error").remove()
                $("#addPrepaidIncomeSupplier_ID").removeClass("error").val(ui.item.Supplier_ID);
                UpdatePrepaidIncomeSubmitButtonStatus()
            }
        })
                .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)
        }
        $("#Income_Search_Supplier").autocomplete("instance")._resizeMenu = function (ul, items) {
            this.menu.element.outerWidth($("#Income_Search_Supplier").width() + parseFloat($("#Income_Search_Supplier").css("padding-left")) + parseFloat($("#Income_Search_Supplier").css("padding-right")) + 2);
        }
    }
</script>
