@model PantheonRA.BackOffice.Models.SynchronizationSettingsViewModel
@{
    ViewBag.Title = Loc.SyncSettings;
}

<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-lg-10">
        <a class="navbar-minimalize btn btn-primary " href="#"><i class="fa fa-bars"></i> </a>
        <h2>@ViewBag.Title</h2>
        <span class="breadcrumb-divider">&bull;</span>
        <ol class="breadcrumb">
            <li><a href="@Url.Action("Index", "SynchronizationSettings")">Home</a></li>
            <li>@Loc.AdministrationPanel</li>
            <li class="active"><strong>@ViewBag.Title</strong></li>
        </ol>
    </div>
    <div class="col-lg-2">
    </div>
</div>
<div class="wrapper wrapper-content animated fadeIn fiscal-certificate-wrapper">
    <div class="row">

        <div class="col-xs-12">

            <div class="tabs-container tabs-normal">
                <ul class="nav nav-tabs">
                    <li class="active"><a data-toggle="tab" href="#tab-1">@Loc.Settings</a></li>
                    @if (Model.SynchronizationStatus.IsSynchronizationEnabled)
                    {
                        <li class=""><a data-toggle="tab" href="#tab-2">@Loc.Errors</a></li>
                        <li class=""><a data-toggle="tab" href="#tab-3">Fine Tuning</a></li>
                    }
                </ul>
                <div class="tab-content">
                    <div id="tab-1" class="tab-pane active">
                        <div class="panel-body">
                            @if (Model.SynchronizationStatus.IsSynchronizationEnabled)
                            {
                                <div class="col-md-12 col-lg-12">
                                    <div class="alert alert-success alert-fiscal-certificate">
                                        <div class=""><i class="fa fa-check fa-5x"></i></div>
                                        <div>
                                            <p><b>@Loc.SynchronizationIsEnabled</b></p>
                                            @if (Model.SynchronizationStatus.DidSynchronizationStart)
                                            {
                                                <p>@Loc.SynchronizationSuccessfulyStarted</p>
                                            }
                                            else
                                            {
                                                <p>@Loc.SynchronizationDidntStartYet</p>
                                            }
                                        </div>
                                    </div>

                                    <h2>@Loc.SynchronizationStatus</h2>
                                    @if (Model.SynchronizationStatus.DidSynchronizationStart)
                                    {
                                        <div>
                                            <small>@Loc.LastSynchronized.ToUpper() @@</small>
                                            @Model.SynchronizationStatus.LastSynchronizationCycle.Ended
                                        </div>
                                        if (Model.SynchronizationStatus.HasLastError)
                                        {
                                            <div>
                                                <small>@Loc.LastSynchronizationError.ToUpper() @@</small> @Model.SynchronizationStatus.LastError.Created, <b>@Model.SynchronizationStatus.LastError.Message</b>
                                            </div>
                                        }
                                    }
                                    else
                                    {
                                        <div><small>@Loc.SynchronizationDidntStartYet</small></div>
                                    }

                                    <div class="col-md-6 col-sm-12">
                                        <div class="ibox">
                                            <div class="ibox-title">
                                                <h5>Sync Info</h5>
                                            </div>
                                            <div class="ibox-content">
                                                <div class="row m-b-sm m-t-sm">
                                                    <div class="col-md-9 col-sm-12">
                                                        <dl class="dl-horizontal">
                                                            <dt>Data Source</dt>
                                                            <dd>@Model.SynchronizationStatus.Datalink.DataSource</dd>

                                                            <dt>Database</dt>
                                                            <dd>@Model.SynchronizationStatus.Datalink.InitialCatalog</dd>

                                                            <dt>User</dt>
                                                            <dd>@Model.SynchronizationStatus.Datalink.DbUserId</dd>

                                                            <dt>Starting Date</dt>
                                                            @if (Model.SynchronizationStatus.Datalink.StartingDateTime != null)
                                                            {
                                                                <dd id="SyncInfoStartingDate">@Model.SynchronizationStatus.Datalink.StartingDateTime.Value.ToString("dd.MM.yyyy.")</dd>
                                                            }
                                                        </dl>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-xs-12">
                                        <div class="form-group m-t-sm">
                                            @Html.CheckBoxFor(model => model.SynchronizationStatus.Datalink.IsEnabled, new { @id = "IsActive", @class = "form-control js-switch" })
                                            @Html.LabelFor(model => model.SynchronizationStatus.Datalink.IsEnabled, "Is syncronization enabled")
                                        </div>
                                    </div>

                                </div>
                                @*<div class="col-md-12 col-lg-4">
                                        <h2>@Loc.SynchronizationDetails</h2>
                                        <table class="table">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>@Loc.Name</th>
                                                    <th>@Loc.Synced</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @for (int i = 1; i <= Model.SynchronizationStatus.ConceptStatuses.Count(); i++)
                                                {
                                                    var status = Model.SynchronizationStatus.ConceptStatuses.ElementAt(i - 1);
                                                    <tr>
                                                        <td>@i</td>
                                                        <td>@status.Concept</td>
                                                        <td>@status.LastSuccessfulSynchronizationTime</td>
                                                    </tr>
                                                }
                                            </tbody>
                                        </table>
                                    </div>*@
                            }
                            else
                            {
                                <div class="col-xs-12">
                                    <div class="alert alert-warning alert-fiscal-certificate">
                                        <div class=""><i class="fa fa-exclamation fa-5x"></i></div>
                                        <div>
                                            <p class="alert-link">@Loc.SynchronizationIsNotSetup!</p>
                                            <p>@Loc.IfYouWantToSynchronizeYourDataYouMustSetupTheSynchronization</p>
                                        </div>
                                    </div>

                                    <div><a href="@Url.Action("Create", "SynchronizationSettings")" class="btn btn-primary pull-right">@Loc.ClickHereToSetupTheSnychronization</a></div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="col-xs-12">
                                </div>
                            }
                        </div>
                    </div>
                    <div id="tab-2" class="tab-pane">
                        <div class="panel-body">
                            <div class="col-xs-12">
                                <h2>@Loc.Errors</h2>
                                @*<div class="row m-b-sm m-t-sm">
                                    <div class="col-md-12">*@
                                <div class="row">
                                    <div class="col-md-5">
                                        <div class="form-group">
                                            @Html.TextBoxFor(model => model.ErrorDataFilter.From, "{0:dd.MM.yyyy.}", new { @id = "From", @class = "form-control datepicker", @placeholder = Loc.From + "..." })
                                        </div>
                                    </div>
                                    <div class="col-md-5">
                                        <div class="form-group">
                                            @Html.TextBoxFor(model => model.ErrorDataFilter.To, "{0:dd.MM.yyyy.}", new { @id = "To", @class = "form-control datepicker", @placeholder = Loc.To + "..." })
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <button type="button" id="searchMainGrid" class="btn btn-block btn-outline btn-primary">@Loc.Search</button>
                                        </div>
                                    </div>
                                    @*</div>

                                        </div>*@
                                </div>

                                <div class="project-list">
                                    <table id="mainGrid" class="list-table">
                                        <thead>
                                            <tr>
                                                <th data-column-id="Id" data-type="numeric" data-visible="false" data-identifier="true">Id</th>
                                                <th data-column-id="Type">@Loc.Type</th>
                                                <th data-column-id="Message">@Loc.ErrorMessage</th>
                                                <th data-column-id="Data" data-header-css-class="wordwrap-header-css">@Loc.Data</th>
                                                <th data-column-id="CreatedDisplayValue" data-order="desc">@Loc.Date</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="tab-3" class="tab-pane">
                        <div class="panel-body">
                            <div class="col-xs-12">
                                <h2>Tax Settings</h2>
                                <div class="row buttons-ribbon">
                                    <div class="col-xs-12">
                                        <a href="javascript:void(0);" id="autoMergeTaxes" class="btn btn-sm btn-primary pull-right"><i class="fa fa-download"></i>&nbsp;&nbsp;<span class="bold">Merge PA Taxes</span></a>
                                        <div class="pull-right button-divider"></div>
                                        <a href="@Url.Action("CreateTax", "SynchronizationSettings")" id="newTaxItem" class="btn btn-sm btn-success pull-right"><i class="fa fa-plus"></i>&nbsp;&nbsp;<span class="bold">New Tax Link</span></a>
                                    </div>
                                </div>
                                <div class="project-list">
                                    <table id="taxGrid" class="list-table">
                                        <thead>
                                            <tr>
                                                <th data-column-id="Id" data-type="numeric" data-visible="false" data-identifier="true">Id</th>
                                                <th data-column-id="taxGroupTax" data-formatter="taxGroupTax">Tax Group - Tax</th>
                                                <th data-column-id="PACode">PA code</th>
                                                <th data-column-id="PaToRc" data-formatter="checkbox">PA to Rc</th>
                                                <th data-column-id="RcToPa" data-formatter="checkbox">Rc to PA</th>
                                                <th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <h2>Time Settings</h2>
                                <div class="col-xs-12 col-md-3">
                                    <div class="form-group">
                                        @Html.LabelFor(model => model.SynchronizationStatus.StartingDateTime, "Starting Date of Next Invoice Synchronization")
                                        @Html.TextBoxFor(m => m.SynchronizationStatus.StartingDateTime, "{0:dd.MM.yyyy.}", new { @id = "SyncStartingDate", @class = "form-control datepicker" })
                                    </div>
                                </div>
                                <div class="col-xs-12 col-md-offset-9 col-md-3">
                                    <div class="form-group">
                                        <button type="button" id="submitStartDate" class="btn btn-block btn-outline btn-primary">Submit Dates</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@section pageCss{
    <link href="~/Content/jquery.bootgrid.css" rel="stylesheet" />
    <link href="~/Content/plugins/datapicker/datepicker3.css" rel="stylesheet" />
    <link href="~/Content/plugins/switchery/switchery.css" rel="stylesheet" />
<style>
    .wordwrap-header-css {
        word-wrap: break-word;
    }
    .bootgrid-table td {
        white-space: normal;
    }
</style>
}

@section pageScripts{
    <script type="text/javascript" src="~/Scripts/jquery.bootgrid.js"></script>
    <script type="text/javascript" src="~/Scripts/plugins/datapicker/bootstrap-datepicker.js"></script>
    <script type="text/javascript" src="~/Scripts/plugins/datapicker/bootstrap-datepicker.js"></script>
    <script src="~/Scripts/plugins/switchery/switchery.js"></script>

    <script>
        $(function () {
            var language = '@PantheonRA.BackOffice.CurrentUser.Localization';

            var grid = $("#mainGrid").bootgrid({
                ajax: true,
                url: "@Url.Action("_ErrorDataList", "SynchronizationSettings")",
                templates: {
                    search: "",
                    header: ""
                },
                labels: {
                    noResults: "@Loc.NoResultFound",
                    infos: "@Loc.Showing {{ctx.start}} @Loc.To.ToLower() {{ctx.end}} ({{ctx.total}})",
                    loading: "@Loc.Loading..."
                },
                post: function () {
                    return {
                        From: reformatDate($("#From").val()),
                        To: reformatDate($("#To").val())
                    };
                },
                column: {
                    "data": {
                        cssClass: "width: 30px; word-wrap: break-word; text-align: right"
                    }
                }
            });

            $('.datepicker').datepicker()
                .on('click', function (e) {
                    $(this).select();
                });

            $("#searchMainGrid").on("click", function () {
                $('#mainGrid').bootgrid('reload');
            });

            // Switchery
            var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));

            elems.forEach(function (html) {
                var switchery = new Switchery(html);
            });

            $('#IsActive').change(function () {
                $.ajax(
                        {
                            url: '@Url.Action("SetSyncEnabled", "SynchronizationSettings")',
                            type: 'POST',
                            data: { isEnabled: this.checked },
                            success: function (result) {
                                if (result.status == "OK")
                                    alert("Sync Status Changed!");
                                else
                                    alert("Error Changing Sync Status!");
                            }
                        });
            });
        });

        // dd.MM.yyyy. -> yyyy-MM-dd
        function reformatDate(dateString) {
            var dateElements = dateString.split('.');
            return dateElements[2] + '-' + dateElements[1] + '-' + dateElements[0]
        }

        $(function () {
            var language = '@PantheonRA.BackOffice.CurrentUser.Localization';

            var grid = $("#taxGrid").bootgrid(
                {
                    ajax: true,
                    url: "@Url.Action("TaxList", "SynchronizationSettings")",
                    sorting: false,
                    templates:
                        {
                            search: "",
                            header: "",
                        },
                    labels: {
                        noResults: "@Loc.NoResultFound",
                        infos: "@Loc.Showing {{ctx.start}} @Loc.To.ToLower() {{ctx.end}} ({{ctx.total}})",
                        loading: "@Loc.Loading..."
                    },
                    formatters: {
                        "checkbox": function (column, row) {
                            if (row[column.id])
                                return "<span class=\"glyphicon glyphicon-ok\" aria-hidden=\"true\"></span>";
                            else
                                return "<span class=\"glyphicon glyphicon-remove\" aria-hidden=\"true\"></span>";
                        },
                        "commands": function (column, row) {
                            return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.Id + "\"><span class=\"fa fa-pencil\"></span></button> " +
                                "<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.Id + "\"><span class=\"fa fa-trash-o\"></span></button>";
                        },
                        "taxGroupTax": function (column, row) {
                            return row.TaxGroup + " - " + row.Tax;
                        },
                    }
                }).on("loaded.rs.jquery.bootgrid", function () {
                    /* Executes after data is loaded and rendered */
                    grid.find(".command-edit").on("click", function (e) {
                        var url = '@Url.Action("EditTax", "SynchronizationSettings")';
                        window.location.href = url + "?id=" + $(this).data("row-id");
                    }).end().find(".command-delete").on("click", function (e) {
                        $.ajax(
                           {
                               url: '@Url.Action("DeleteTax", "SynchronizationSettings")',
                               type: 'GET',
                               data: { id: $(this).data("row-id") },
                               success: function (result) {
                                   $('#taxGrid').bootgrid('reload');
                               }
                           });
                    });
                });


            $("#submitStartDate").on("click", function () {
                $.ajax(
                   {
                       url: '@Url.Action("SetSyncStartDate", "SynchronizationSettings")',
                       type: 'POST',
                       data: { date: reformatDate($("#SyncStartingDate").val()) },
                       success: function (result) {
                           if (result.status == "OK") {
                               alert("Dates Saved!");
                               $('#SyncInfoStartingDate').text($("#SyncStartingDate").val())
                           }
                           else
                               alert("Error Saving Dates!");
                       }
                   });
            });

            $("#autoMergeTaxes").on("click", function () {
                $.ajax(
                   {
                       url: '@Url.Action("AutoMergePantheonTaxes", "SynchronizationSettings")',
                       type: 'POST',
                       success: function (result) {
                           if (result.status == "OK")
                               alert("Taxes Merged!");
                           else
                               alert("Error Merging Taxes!");
                           $('#taxGrid').bootgrid('reload');
                       }
                   });
            });
        });
    </script>
}
