@model PantheonRA.BackOffice.Models.SubjectCreateViewModel

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Hidden("UrlSave", Url.Action("SaveApproval", "Subjects"))
        @Html.Hidden("UrlDelete", Url.Action("DeleteApproval", "Subjects"))
        @Html.Hidden("TxtConfirm", Loc.Confirm)
        @Html.Hidden("TxtDeleteQuestion", Loc.DeleteQuestionRecord)
        @Html.Hidden("TxtCancel", Loc.Cancel)
        @Html.Hidden("TxtConfirmation", Loc.Confirmation)
        @Html.Hidden("TxtDelNotPossible", Loc.DeleteEntryTypeNotPossible)
        @Html.Hidden("TxtInputFields", Loc.FieldIsRequired)
        @Html.Hidden("TxtAlreadyExists", Loc.AlreadyExists)
        @Html.Hidden("PrimaryKeyExists", Loc.PrimaryKeyExists)
        @Html.Hidden("GetSetApprovalUrl", Url.Action("GetSetApproval", "Subjects"))
        @Html.Hidden("PageUrl", Url.Action("Edit", "Subjects"))

        <div class="tab-content set-wh-content">
            <div class="row document-head">
                <!-- Keywords -->
                <div class="col-md-4 col-xs-12">
                    <div class="form-group">
                        <label class="control-label">@Loc.SearchFilter</label>
                        @Html.TextBoxFor(model => model.Keywords, new { @id = "Keywords", @class = "form-control search-input", @placeholder = Loc.Search, autocomplete = "off" })
                    </div>
                </div>
                <!-- FromDate -->
                <div class="col-md-2 col-xs-12">
                    <div class="form-group">
                        <label class="control-label">@Loc.DateFrom</label>
                        <div class="input-group">
                            <span class="input-group-addon border-bottom-none"><i class="far fa-calendar alt"></i></span>
                            <input autocomplete="off" class="form-control datepicker border-bottom-none" id="DateFrom" onchange="onFilterDateChange('DateFrom')" type="text">
                        </div>
                    </div>
                </div>
                <!-- ToDate -->
                <div class="col-md-2 col-xs-12">
                    <div class="form-group">
                        <label class="control-label">@Loc.DateTo</label>
                        <div class="input-group">
                            <span class="input-group-addon border-bottom-none"><i class="far fa-calendar alt"></i></span>
                            <input autocomplete="off" class="form-control datepicker border-bottom-none" id="DateTo" onchange="onFilterDateChange('DateTo')" type="text">
                        </div>
                    </div>
                </div>
                <div class="col-md-2 hidden-sm hidden-xs"></div>
            </div>
            <div class="row setwh-100-h">
                <div class="col-md-12 containerSetCalEntryTypes p-r-0">
                    <table id="tblSettingsApprovals"
                           class="table table-bordered setwh-table"
                           style="margin-bottom: 0;" role="grid">
                        <thead>
                            <tr>
                                <th data-column-id="SetApprovalId">@Loc.SetSubjApprovalType</th>
                                <th data-column-id="Note">@Loc.Note</th>
                                <th data-column-id="ValidFrom">@Loc.ValidFrom</th>
                                <th data-column-id="ValidTo">@Loc.ValidTo</th>
                                <th style="width: 34px"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr id="tr-0" class="sortable-row">
                                <!-- Set Approval Id -->
                                <td class="p-top-none padding-bottom-none" label="@Loc.SetSubjApprovalType">
                                    <div class="ddw-full-width select2HideColumns">
                                        <select id="input-set-approval"
                                                data-placeholder="@Loc.SetSubjApprovalType"
                                                class="form-control select2withAPI"
                                                data-column-names="@Loc.Code,@Loc.Value"
                                                data-bootstrap-columns="col-md-3,col-md-9"
                                                data-search-width="350"
                                                data-mobile-width="200"
                                                onchange="changeApprovalId(0)"
                                                data-url=@Url.Action("GetSubjectSetApprovals", "Subjects")>
                                        </select>
                                    </div>
                                </td>
                                <!-- Note -->
                                <td class="p-top-none padding-bottom-none" label="@Loc.Note">
                                    <input id="input-note"
                                           maxlength="4000"
                                           type="text"
                                           class="form-control border-bottom-none"
                                           autocomplete="off"
                                           placeholder="@Loc.Note" />
                                </td>
                                <!-- ValidFrom -->
                                <td class="p-top-none padding-bottom-none" label="@Loc.ValidFrom">
                                    <div class="input-group">
                                        <span class="input-group-addon border-bottom-none"><i class="far fa-calendar alt"></i></span>
                                        <input class="form-control datepicker border-bottom-none" id="input-date-from" type="text">
                                    </div>
                                </td>
                                <!-- ValidTo -->
                                <td class="p-top-none padding-bottom-none" label="@Loc.ValidTo">
                                    <div class="input-group">
                                        <span class="input-group-addon border-bottom-none"><i class="far fa-calendar alt"></i></span>
                                        <input class="form-control datepicker border-bottom-none" id="input-date-to" type="text">
                                    </div>
                                </td>
                                <!-- Action -->
                                <td class="td-action">
                                    <p class="btn btn-success" onclick="saveApproval(0)">
                                        <span class="far fa-plus cursor-pointer" aria-hidden="true"></span>
                                    </p>
                                </td>
                            </tr>
                            @foreach (var item in Model.SubjectApprovals)
                            {
                                <tr id="tr-@item.AnQid" class="sortable-row" data-id="@item.AnQid">
                                    <!-- Set Approval Id -->
                                    <td class="p-top-none padding-bottom-none" label="@Loc.SetSubjApprovalType">
                                        <div class="ddw-full-width select2HideColumns">
                                            <select id="input-set-approval-@item.AnQid"
                                                    data-placeholder="@Loc.SetSubjApprovalType"
                                                    class="form-control select2withAPI"
                                                    data-column-names="@Loc.Code,@Loc.Value"
                                                    data-bootstrap-columns="col-md-3,col-md-9"
                                                    data-search-width="350"
                                                    data-mobile-width="200"
                                                    data-url=@Url.Action("GetSubjectSetApprovals", "Subjects")
                                                    onchange="saveApproval(@item.AnQid)">
                                                <option selected="selected" value="@item.SetApprovalId">@item.SetApprovalText</option>
                                            </select>
                                        </div>
                                    </td>
                                    <!-- Note -->
                                    <td class="p-top-none padding-bottom-none" label="@Loc.Note">
                                        <input id="input-note-@item.AnQid"
                                               value="@item.Note"
                                               maxlength="4000"
                                               type="text"
                                               class="form-control border-bottom-none"
                                               autocomplete="off"
                                               placeholder="@Loc.Note"
                                               onchange="saveApproval(@item.AnQid)" />
                                    </td>
                                    <!-- ValidFrom -->
                                    <td class="p-top-none padding-bottom-none" label="@Loc.ValidFrom">
                                        <div class="input-group">
                                            <span class="input-group-addon border-bottom-none"><i class="far fa-calendar alt"></i></span>
                                            <input class="form-control datepicker border-bottom-none"
                                                   id="input-date-from-@item.AnQid" type="text"
                                                   onchange="saveApproval(@item.AnQid)"
                                                   value="@(item.DateFrom == null ? string.Empty : item.DateFrom.Value.ToString(Loc.DateFormat))">
                                        </div>
                                    </td>
                                    <!-- ValidTo -->
                                    <td class="p-top-none padding-bottom-none" label="@Loc.ValidTo">
                                        <div class="input-group">
                                            <span class="input-group-addon border-bottom-none"><i class="far fa-calendar alt"></i></span>
                                            <input class="form-control datepicker border-bottom-none"
                                                   id="input-date-to-@item.AnQid" type="text"
                                                   onchange="saveApproval(@item.AnQid)"
                                                   value="@(item.DateTo == null ? string.Empty : item.DateTo.Value.ToString(Loc.DateFormat))">
                                        </div>
                                    </td>
                                    <!-- Action -->
                                    <td class="p-top-none padding-bottom-none" class="td-action">
                                        <p class="text-center" title="@Loc.Delete">
                                            <span onclick="deleteApproval(@item.AnQid)" style="margin-top: 12px" class="far fa-trash-alt cursor-pointer" aria-hidden="true"></span>
                                        </p>
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

@section pageScripts{
    @* TODO: remove after refactor *@
    @Scripts.Render("~/bundles/validation")
    <script src="~/Scripts/global-script.js"></script>
}

<!-- This will be moved into js on the task finish -->
<script>
    $(document).ready(function () {
        $(this).find('input[type="checkbox"]').customCheckbox();

        $("#Keywords").on("keyup", function () {
            var filter = $(this).val().toLowerCase();

            $('#tblSettingsApprovals tr').each(function (i, row) {
                if (i <= 1
                    || row.innerHTML.toLowerCase().indexOf('value="' + filter) > -1
                    || row.innerHTML.toLowerCase().includes(filter)
                    || row.innerHTML.toLowerCase().indexOf('>' + filter) > -1) {
                    row.style.display = "";
                }
                else {
                    row.style.display = "none";
                }
            });

        });

        $("#DateFrom").on("change", function () {
            var filter = $(this).val().toLowerCase();
            console.log(filter);

        });
    });

    $(document).ajaxError(function () {
        location.reload();
    });

    function onFilterDateChange(fieldName) {
        let dateValue = $("#" + fieldName).val();

        let pageUrl = $("#PageUrl").val() + "?type=approvals&id=" + $("#SubjectId").val() + "&" + fieldName + "=" + dateValue;

        window.location = pageUrl;
    }

    function changeApprovalId(anQid) {
        let sufix = anQid != 0 ? "-" + anQid : "";
        let setApprovalId = $("#input-set-approval" + sufix).val();

        var setApprovalTxt = $('#select2-input-set-approval-container').text();

        setApprovalTxt = setApprovalTxt.split(", ")[1];
        $('#select2-input-set-approval-container').text(setApprovalTxt);

        $.ajax({
            url: $("#GetSetApprovalUrl").val(),
            data: { setApprovalId: setApprovalId },
            type: 'GET',
            success: function (data) {
                $("#input-note" + sufix).val(data.Note);
                $("#input-date-from" + sufix).datepicker("setDate", data.AdValidFrom);
                $("#input-date-to" + sufix).datepicker("setDate", data.AdValidTo);
            }
        });
    }

    function deleteApproval(anQid) {
        var deleteText = $("#TxtDeleteQuestion").val();
        var deleteTitle = $("#TxtConfirmation").val();
        var confirmText = $("#TxtConfirm").val();
        var cancelText = $("#TxtCancel").val();

        $().customModal({
            destroyOnClose: true,
            title: deleteTitle,
            showCloseButton: true,
            help: function () {

            },
            id: "modalDeleteEntryType",
            type: "question",
            text: deleteText,
            buttons: [{
                icon: 'fa fa-times',
                text: cancelText,
                action: function () {

                },
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: confirmText,
                closeOnAction: true,
                action: async function () {
                    await new Promise((resolve, reject) => setTimeout(function () {
                        removeApproval(anQid);
                        resolve();
                    }, 1500));
                },
                closeOnAction: true,
                type: 'primary'
            }]
        });
    }

    function removeApproval(anQid) {
        $.ajax({
            url: $("#UrlDelete").val() + '?anQId=' + anQid,
            type: 'GET',
            success: function (data) {
                if (data && data.Status) {
                    $("#tr-" + anQid).remove();
                }
                else {
                    $(document).ready(function () {
                        $().customModal({
                            destroyOnClose: true,
                            title: '',
                            showCloseButton: true,
                            help: function () {

                            },
                            id: "modalDeleteEntryTypeNotPossible",
                            type: "alert",
                            text: $("#TxtDelNotPossible").val(),
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: $("#TxtConfirm").val(),
                                    closeOnAction: true,
                                    type: 'primary'
                                }]
                        });
                    });
                }
            }
        });
    }

    function saveApproval(anQid) {
        let sufix = anQid != 0 ? "-" + anQid : "";

        let data = {
            AnQid: anQid ? anQid : 0,
            SubjectId: $("#SubjectId").val(),
            SetApprovalId: $("#input-set-approval" + sufix).val(),
            Note: $("#input-note" + sufix).val(),
            DateFrom: $("#input-date-from" + sufix).val(),
            DateTo: $("#input-date-to" + sufix).val(),
        };

        postApproval(data);
    }

    function postApproval(data) {
        $.ajax({
            url: $("#UrlSave").val(),
            type: 'POST',
            data: data,
            success: function (data) {
                location.reload();
            }
        });
    }
</script>