@model DiscountModel

@using Nop.Core.Domain.Discounts;
@using Telerik.Web.Mvc.UI;

@Html.ValidationSummary(false)
@Html.HiddenFor(model => model.Id)
@Html.Telerik().TabStrip().Name("discount-edit").Items(x =>
{
    x.Add().Text(T("Admin.Promotions.Discounts.Info").Text).Content(TabInfo().ToHtmlString()).Selected(true);
    x.Add().Text(T("Admin.Promotions.Discounts.Requirements").Text).Content(TabRequirements().ToHtmlString());
    if (Model.Id > 0)
    {
        x.Add().Text(T("Admin.Promotions.Discounts.History").Text).Content(TabHistory().ToHtmlString());
    }
})
@helper TabInfo()
    {
        
        
    <script type="text/javascript">
            $(document).ready(function () {
                $("#@Html.FieldIdFor(model => model.UsePercentage)").click(toggleUsePercentage);
                $("#@Html.FieldIdFor(model => model.RequiresCouponCode)").click(toggleRequiresCouponCode);
                $("#@Html.FieldIdFor(model => model.DiscountLimitationId)").change(toggleLimitation);

                toggleLimitation();
                toggleUsePercentage();
                toggleRequiresCouponCode();
            });


            function toggleLimitation() {
                var selectedDiscountLimitation = document.getElementById('@Html.FieldIdFor(model => model.DiscountLimitationId)');
                var selectedDiscountLimitationId = selectedDiscountLimitation.options[selectedDiscountLimitation.selectedIndex].value;
                if (selectedDiscountLimitationId == @(((int)DiscountLimitationType.NTimesOnly).ToString()) || selectedDiscountLimitationId == @(((int)DiscountLimitationType.NTimesPerCustomer).ToString())) {
                    //'N Times Only' or 'N Times Per Customer'
                    $('#pnlLimitationTimes').show();
                }
                else {
                    $('#pnlLimitationTimes').hide();

                }
            }

            function toggleUsePercentage() {
                if (getE('@Html.FieldIdFor(model => model.UsePercentage)').checked) {
                    $('#pnlDiscountPercentage').show();
                    $('#pnlDiscountAmount').hide();
                }
                else {
                    $('#pnlDiscountPercentage').hide();
                    $('#pnlDiscountAmount').show();
                }
            }

            function toggleRequiresCouponCode() {
                if (getE('@Html.FieldIdFor(model => model.RequiresCouponCode)').checked) {
                    $('#pnlCouponCode').show();
                }
                else {
                    $('#pnlCouponCode').hide();
                }
            }
            
    </script>
    
        
    <table class="adminContent">
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.Name):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.DiscountTypeId):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.DiscountTypeId, ((DiscountType)Model.DiscountTypeId).ToSelectList())
                @Html.ValidationMessageFor(model => model.DiscountTypeId)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.UsePercentage):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.UsePercentage)
                @Html.ValidationMessageFor(model => model.UsePercentage)
            </td>
        </tr>
        <tr id="pnlDiscountAmount">
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.DiscountAmount):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.DiscountAmount) [@Model.PrimaryStoreCurrencyCode]
                @Html.ValidationMessageFor(model => model.DiscountAmount)
            </td>
        </tr>
        <tr id="pnlDiscountPercentage">
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.DiscountPercentage):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.DiscountPercentage)
                @Html.ValidationMessageFor(model => model.DiscountPercentage)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StartDateUtc):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.StartDateUtc)
                @Html.ValidationMessageFor(model => model.StartDateUtc)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.EndDateUtc):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.EndDateUtc)
                @Html.ValidationMessageFor(model => model.EndDateUtc)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.RequiresCouponCode):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.RequiresCouponCode)
                @Html.ValidationMessageFor(model => model.RequiresCouponCode)
            </td>
        </tr>
        <tr id="pnlCouponCode">
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.CouponCode):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.CouponCode)
                @Html.ValidationMessageFor(model => model.CouponCode)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.DiscountLimitationId):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.DiscountLimitationId, ((DiscountLimitationType)Model.DiscountLimitationId).ToSelectList())
                @Html.ValidationMessageFor(model => model.DiscountLimitationId)
            </td>
        </tr>
        <tr id="pnlLimitationTimes">
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.LimitationTimes):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.LimitationTimes)
                @Html.ValidationMessageFor(model => model.LimitationTimes) @T("Admin.Promotions.Discounts.Fields.LimitationTimes.Times")
            </td>
        </tr>
    </table>
}
@helper TabRequirements()
    {
        if (Model.Id > 0)
        {
        
    <script type="text/javascript">
            
            $(document).ready(function () {
            
                $("#@Html.FieldIdFor(model => model.AddDiscountRequirement)").change(loadNewRequirementBox);

                //load add requirement box
                loadNewRequirementBox();

                //load existing requirements
                loadExistingRequirements();
                           
               //adding requirement event
               $("#discountRequirementContainer").bind('nopnewdiscountruleadded', function(event, newRequirementId) {
  
                    var discountId = @Model.Id;
                    $.ajax({
                        cache:false,
                        type: "POST",
                        url: "@(Url.Action("GetDiscountRequirementMetaInfo", "Discount"))",
                        data: "discountRequirementId=" + newRequirementId + "&discountId=" + discountId ,
                        success: function (result) {                            
                            discountRequirements.push({ discountRequirementId: newRequirementId, ruleName : result.ruleName, url : result.url });
                            loadExistingRequirements();
                        },
                        error:function (xhr, ajaxOptions, thrownError) {
                            alert('Failed to load new discount requirement info. Please refresh the page');
                        }
                    });

               });
            });

                
            //load requirement HTML
            function loadRequirement(configureRuleUrl, placeholderName) {
                $.ajax({
                    cache:false,
                    url: configureRuleUrl,
                    dataType: "html",
                    success: function (result) {
                        $(placeholderName).html(result);
                    },
                    error:function (xhr, ajaxOptions, thrownError) {
                        $(placeholderName).html('Failed to load requirement content.');
                    }
                });
            }

            //load HTML for adding requirement
            function loadNewRequirementBox() {
                //load URL
                var ruleSystemName = $(this).val();
                var discountId = @Model.Id;
                if (ruleSystemName != '') {
                    $.ajax({
                        cache:false,
                        url: "@(Url.Action("GetDiscountRequirementConfigurationUrl", "Discount"))",
                        data: "systemName=" + ruleSystemName + "&discountId=" + discountId,
                        success: function (result) {
                                var configureRuleUrl = result.url;
                                //now load the content
                                loadRequirement(configureRuleUrl, '#addrequirementplaceholder');
                        },
                        error:function (xhr, ajaxOptions, thrownError){
                            $('#addrequirementplaceholder').html('Failed to load requirement URL');
                        }  
                    });
                }
                else {
                    $('#addrequirementplaceholder').html('');
                }
            }

           //array of exisiting discount requirements
           var discountRequirements = [
                    @for (int i = 0; i < Model.DiscountRequirementMetaInfos.Count; i++)
                    {
                        var drmi = Model.DiscountRequirementMetaInfos[i];
                        <text>{ discountRequirementId: @(drmi.DiscountRequirementId), ruleName: "@(drmi.RuleName)", url:  "@(Html.Raw(drmi.ConfigurationUrl))" } </text> if (i != Model.DiscountRequirementMetaInfos.Count - 1)
                                                                                                                                                                         {<text>, </text>}

                    }
               ];
           
           //load HTML for exisiting requirements
           function loadExistingRequirements() {
               $("#discountRequirementContainer").html('');
               $("#discountRequirementTemplate").tmpl(discountRequirements).appendTo("#discountRequirementContainer");

               var discountRequirementsLen = discountRequirements.length;
               for (var i=0; i<discountRequirementsLen; i++) {
                   var url = discountRequirements[i].url;
                   var discountRequirementId = discountRequirements[i].discountRequirementId;
                   var placeholderName = '#editrequirementplaceholder' + discountRequirementId;
                   $(placeholderName).html('loading...');
                   loadRequirement(url, placeholderName);
               }
           }

           //delete requirement rule
           function deleteRequirement(discountRequirementId) {           
                var discountId = @Model.Id;                
                $.ajax({
                    cache:false,
                    type: "POST",
                    url: "@(Url.Action("DeleteDiscountRequirement", "Discount"))",
                    data: "discountId=" + discountId +"&discountRequirementId=" + discountRequirementId,
                    success: function (data) {
                        removeByElement(discountRequirements, discountRequirementId)
                        loadExistingRequirements();
                    },
                    error:function (xhr, ajaxOptions, thrownError){
                        alert('Failed to delete requirement.')
                    }  
                });

                
            function removeByElement(arrayName,discountRequirementId) {
                for(var i=0; i<arrayName.length; i++) {
                    if(arrayName[i].discountRequirementId==discountRequirementId) {
                        arrayName.splice(i,1);
                    }
                }
             }

        }

    </script>
    <!-- Template container -->
    <div id="discountRequirementContainer">
    </div>
    <!-- Discount requirement template -->
    <script id="discountRequirementTemplate" type="text/html">
            <div id="editrequirement{{= discountRequirementId }}">
                <div>Discount requirement type: <b>{{= ruleName }}</b></div>
                <div id="editrequirementplaceholder{{= discountRequirementId }}" style="float:left;"></div>
                <div style="float:right;">
                    <button type="button" name="deleterequirement{{= discountRequirementId }}" id="deleterequirement{{= discountRequirementId }}" onclick="deleteRequirement({{= discountRequirementId }})" class="t-button">Remove requirement</button>
                </div>
                <table class="adminContent">
                    <tr class="adminSeparator">
                        <td colspan="2">
                            <hr />
                        </td>
                    </tr>
                </table>
            </div>
    </script>
            
    <table class="adminContent">
        <tr>
            <td colspan="2">
                <b>@T("Admin.Promotions.Discounts.Requirements.AddNew")</b>
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.AddDiscountRequirement):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.AddDiscountRequirement, Model.AvailableDiscountRequirementRules)
                @Html.ValidationMessageFor(model => model.AddDiscountRequirement)
            </td>
        </tr>
    </table>
    <table class="adminContent">
        <tr>
            <td colspan="2">
                <div id="addrequirementplaceholder">
                </div>
            </td>
        </tr>
    </table>
        }
        else
        {
    @T("Admin.Promotions.Discounts.Requirements.SaveBeforeEdit")
        }
}
@helper TabHistory()
    { 
    
        var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;
    @(Html.Telerik().Grid<DiscountModel.DiscountUsageHistoryModel>()
                    .Name("usagehistory-grid")
                    .DataKeys(x =>
                    {
                        x.Add(y => y.Id).RouteKey("Id");
                        x.Add(y => y.DiscountId).RouteKey("discountId");
                    })
                    .Columns(columns =>
                    {
                        columns.Bound(x => x.OrderId)
                            .Width(100)
                            .Template(x => Html.ActionLink(T("Admin.Common.View").Text, "Edit", "Order", new { id = x.OrderId }, new { }))
                            .ClientTemplate("<a href=\"" + @Url.Content("~/Admin/Order/Edit/") + "<#= OrderId #>\">" + T("Admin.Common.View").Text + "</a>");
                        columns.Bound(x => x.CreatedOn).Width(200);
                        columns.Command(commands =>
                        {
                            commands.Delete();
                        }).Width(100).Title(T("Admin.Common.Delete").Text);

                    })
                    .Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
                    .DataBinding(dataBinding =>
                    {
                        dataBinding.Ajax().Select("UsageHistoryList", "Discount", new { discountId = Model.Id })
                            .Delete("UsageHistoryDelete", "Discount");
                    })
                    .EnableCustomBinding(true))
        
}