@extends('layouts.app')

@section('content')
<!-- Exclude Modal content  -->
<div class="modal" id="modal_exclude" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Excluding <span class="modal_zone"></span></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        Exclude <strong><span class="modal_zone"></span></strong> from <strong><span class="modal_server"></span></strong>?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-warning" id="btnModalExclude">Exclude</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!-- /Modal content   -->
<!-- Remove Exclude Modal content -->
<div class="modal" id="modal_remove_exclude" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Removing exclude of <span class="modal_remove_zone"></span></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        Remove exclude of <strong><span class="modal_remove_zone"></span></strong> from <strong><span class="modal_remove_server"></span></strong>?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="btnModalRemoveExclude">Remove exclude</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!-- /Modal content -->
<div class="container-fluid">
  <div class="content-header text-center">
    <h1><i class="fas fa-globe mr-1"></i> Zones</h1>
  </div>
  <div class="card card-primary card-outline">
    <div class="card-body">
      <div class="row">
        <div class="col-md-6">
          <div class="shadow card card-secondary">
            <div class="card-header">
              All zones (<i data-toggle="tooltip" title="If the number of zones is big and loading is slow, you can disable zones complete load in 'Settings'. A search box will appear instead." class="fas fa-info-circle"></i>)
            </div>
            <div class="card-body">
              @if ($zones === 0)
                {{ __('No zones found.') }}
              @else
                <div id="msg" class="mb-3">
                @if( !$disable_zones_complete_load )
                    <div class="d-flex justify-content-center"><div class="spinner-border centered" role="status"></div></div>
				@endif
                </div>
                @if( $disable_zones_complete_load )
				<div class="input-group mb-3">
				  <input type="text" class="form-control" id="search_zones" placeholder="Search zones by name">
				  <div class="input-group-append">
					<button class="btn btn-outline-secondary" id="btn_search_zones" type="button"><i class="fas fa-search"></i> Search</button>
				  </div>
				</div>
                <hr>
                @else
                @endif
                <table id="table_zones" class="table table-sm table-striped">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Server</th>
                            <th>Insert date</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
              @endif
            </div>
          </div>
        </div>
        <div class="col-md-6">
          <div class="shadow card card-warning">
            <div class="card-header">
              Excluded zones
                <span class="float-right"><button id="btn_reload_excluded" class="btn btn-xs btn-default"><i class="fas fa-sync"></i></button></span>
            </div>
            <div class="card-body">
                <div id="msg_remove">
                    <div class="d-flex justify-content-center"><div class="spinner-border centered" role="status"></div></div>
                </div>
                <table id="table_excludes" class="table table-sm table-striped">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Server</th>
                            <th></th>
                        </tr>
                    </thead>
                </table>
            </div>
          </div>
          
          <div class="shadow card card-danger">
            <div class="card-header">
              Duplicate zones
                <span class="float-right"><button id="btn_reload_duplicates" class="btn btn-xs btn-default"><i class="fas fa-sync"></i></button></span>
            </div>
            <div class="card-body">
                <div id="msg_dup">
                    <div class="d-flex justify-content-center"><div class="spinner-border centered" role="status"></div></div>
                </div>
                <small>*NE/TD = <strong>N</strong>ot <strong>E</strong>xcluded server count / <strong>T</strong>otal <strong>D</strong>uplicate server count.</small>
                <hr />
                <table id="table_duplicates" class="table table-sm table-striped">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Servers</th>
                            <th>NE/TD*</th>
                        </tr>
                    </thead>
                </table>
            </div>
          </div>

          <div class="shadow card card-warning">
            <div class="card-header">
              Mass exclude zones
            </div>
            <div class="card-body">
                <div id="msg_mass_exclude">
                    <div class="d-flex justify-content-center"><div class="spinner-border centered" role="status"></div></div>
                </div>
								<div class="row">
                  <div class="col-md-8">
                    <div class="form-group">
                      <select class="form-control" id="mass_exclude_option">
                      </select>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="form-group">
                      <button id="btn_load_mass_exclude_zones" class="btn btn-outline-primary">Load zones</button>
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col">
                    <div class="form-group">
                      <div class="form-check">
                        <input type="checkbox" name="show_excluded" id="show_excluded" class="form-check-input"> <label for="show_excluded" class="form-check-label">Show excluded</label>
                      </div>
                    </div>
                  </div>
								</div>
								<div id="mass_exclude_table_wrapper" style="display:none">
									<div class="form-group">
										<div class="btn-group">
											<button class="btn btn-outline-primary" id="btn_mass_exclude">Exclude selected</button> <button class="btn btn-outline-primary" id="btn_mass_remove_exclude">Remove exclude from selected</button>
										</div>
									</div>
									<div class="form-group">
										<div class="btn-group">
											<button id="btn_mass_exclude_select_all" class="btn btn-sm btn-outline-secondary">Select all</button> <button class="btn btn-sm btn-outline-secondary" id="btn_mass_exclude_unselect_all">Un-select all</button> <button class="btn btn-sm btn-outline-secondary" id="btn_mass_exclude_select_duplicates">Select duplicates</button>
										</div>
									</div>
									<table id="table_mass_exclude" class="table table-sm table-striped">
											<thead>
													<tr>
															<th>Zone</th>
															<th>Duplicate?</th>
													</tr>
											</thead>
									</table>
								</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div> 
</div>

<link rel="stylesheet" type="text/css" href="{{ asset('css/adminlte-3.0.5/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css') }}">
<script type="text/javascript" src="{{ asset('/css/adminlte-3.0.5/plugins/datatables/jquery.dataTables.min.js') }}"></script>
<script type="text/javascript" src="{{ asset('css/adminlte-3.0.5/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js') }}"></script>

<script type="text/javascript">
  $(document).ready(function () {

			var mass_excludes_table = $('#table_mass_exclude').DataTable({
					"pageLength": 50,
					columns:
						[
							{
								data: 'zone',
								render: function(data, type, row, meta)
								{
									var duplicate_data = 0;
									var excluded_text = "";
									if(row.excluded == 1)
									{
										excluded_text = "<span class='badge badge-primary')>Excluded</span>";
									}
									if(row.duplicate_servers.length > 1)
									{
										duplicate_data = 1;
									}

									return '<input data-duplicate="' + duplicate_data + '"type="checkbox" class="mass_exclude_selection" id="mass_id_'+row.id+'" data-zone_id="' + row.id +'"> <label for="mass_id_'+row.id+'">' + data + '</label> '+excluded_text;
								},
							},
							{
								data: 'duplicate_servers',
								render: function(data, type, row, meta)
								{
									if(data.length > 1)
									{
										var server_names = [];
										$.each(data, function (index, value)
										{
											server_names.push(value.name);
										});
										return "<label class='text-danger' for='mass_id_"+row.id+"' title='"+server_names.join(",")+"'>yes</label>";
									}
									else
									{
										return "<label class='text-success' for='mass_id_"+row.id+"'>no</label>";
									}
								}
							},
						]
			});
      $('#menu-zones').addClass('active');
        var zones_table = $('#table_zones').DataTable({
            "pageLength": 100,
            "oLanguage": {
                "sSearch": "Filter: "
            },
            columns:
            [
                {data: 'zone'},
                {data: 'server_name'},
                {data: 'insert_date'},
                {
                    data: 'server_name',
                    render: function(data, type, row, meta)
                    {
                        return '<button class="btn btn-sm btn-warning btn_exclude" data-server_name="'+ data +'" data-zone="'+ row.zone +'" data-server="'+ row.server_id +'">Exclude</button>';
                    }
                },

            ]
        });
        var excludes_table = $('#table_excludes').DataTable(
        {
            "pageLength": 10,
            columns:
            [
                {data: 'zone'},
                {data: 'server_name'},
                {
                    data: 'server_name',
                    render: function(data, type, row, meta)
                    {
                        return '<button class="btn btn-sm btn-secondary btn_remove_exclude" data-server_name="'+ data +'" data-zone="'+ row.zone +'" data-server="'+ row.server_id +'">Remove exclusion</button>';
                    }
                },

            ]

        });
        var duplicates_table = $('#table_duplicates').DataTable(
        {
            "pageLength": 10,
            columns:
            [
                {data: 'zone'},
                {
                    data: 'duplicate_servers',
                    render: function(data, type, row, meta)
                    {
                        var ret = '<div class="btn-group">';
                        $.each(data, function(i, item)
                        {
                          if(row.excluded_in == 0)
                          {
                              ret += '<button class="btn btn-sm btn-warning btn_exclude" data-server_name="'+ item.name +'" data-zone="'+ row.zone +'" data-server="'+ item.id +'">'+ item.name +'</button>';
                          }
                          else
                          {
                            
                            var server_id = item.id;
                            var excluded = false;
                            $.each(row.excluded_in, function(j, excl)
                            {
                              if(excl.server_id == server_id)
                              {
                                excluded = true;
                              }
                            });
                            if(excluded)
                              ret += '<button class="btn btn-sm btn-warning disabled" data-toggle="tooltip" title="already excluded">'+ item.name +'</button>';
                            else
                              ret += '<button class="btn btn-sm btn-warning btn_exclude" data-server_name="'+ item.name +'" data-zone="'+ row.zone +'" data-server="'+ item.id +'">'+ item.name +'</button>';

                          }
                        });
                        ret += '</div>';
                        return ret;
                    }
                },
                {
                  data: 'not_excluded_server_count',
                  render: function(data, type, row, meta)
                  {
                    var ret = data + "/" + row.count;
                    return ret;
                  }
                },
            ]

        });

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        @if ($disable_zones_complete_load)
			$("#btn_search_zones").on("click", function()
			{
				$("#msg").html('<div class="d-flex justify-content-center"><div class="spinner-border centered" role="status"></div></div>');
				var query = $("#search_zones").val();
				$.ajax(
				{
					type: "POST",
					url: "/zones/search",
					data: {query:query},
					success: function(response)
					{
						zones_table.clear();
						zones_table.rows.add(response).draw();

						$("#msg").html('');
					}
				});
			});	

        @else
        function getMoreZones(after_id)
        {
            $.ajax(
            {
                type: "POST",
                url: "/zones/all",
                data: {id:after_id},
                success: function(response)
                {
                    zones_table.rows.add(response.zones).draw();
                    if(response.more)
                    {
                        getMoreZones(response.after);
                    }
                    else
                    {
                        $("#msg").html('');
                    }
                }
            });
        };

        $.ajax(
        {
            type: "GET",
            url: "/zones/all",
            success: function(response)
            {

                zones_table.clear();
                zones_table.rows.add(response.zones).draw();
                if(response.more)
                {
                    getMoreZones(response.after);
                }
                else
                {
                    $("#msg").html('');
                }
            }
        });
        @endif
        function load_excluded()
        {
          $.ajax(
          {
              type: "GET",
              url: "/zones/excluded",
              success: function(response)
              {
                  excludes_table.clear();
                  excludes_table.rows.add(response).draw();
                  $("#msg_remove").html('');
              }
          });
        }

        function load_duplicates()
        {
          var url = "/zones/duplicates";
          @if($hide_single_server_zones_in_dup_list) 
            url = "/zones/duplicates/no_singles";
          @endif
          $.ajax(
          {
              type: "GET",
              url: url,
              success: function(response)
              {
                  duplicates_table.clear();
                  if(response.length > 1)
                  {
                    duplicates_table.rows.add(response).draw();
                  }
                  else if(response.length == 1)
                  {
                    duplicates_table.row.add(response[Object.keys(response)[0]]).draw();
                  }
                  else
                  {
                    duplicates_table.draw();
                  }

                  $("#msg_dup").html('');
              }
          });
        }

        function load_mass_exclude_servers()
        {
          $.ajax(
          {
            type: "GET",
            url: "/zones/mass_exclude_servers",
            success: function(response)
            {
              $("#msg_mass_exclude").html('');
							$.each(response, function(i, server)
							{
								$("#mass_exclude_option").append(new Option(server.name, server.id));
							});
            }
					

					});
				};

        load_excluded();
        load_duplicates();
				load_mass_exclude_servers();

				$(document).on('click', '#btn_mass_exclude', function()
				{
					var btn = $(this);
					btn.prop('disabled', true);
					var exclude_zone_ids = [];
					$('.mass_exclude_selection:checked').each(function (idx)
					{
						exclude_zone_ids.push($(this).data('zone_id'));	
					});

					if(exclude_zone_ids.length>0)
					{
						$.ajax(
						{
							type: "POST",
							url: "/zones/mass_exclude",
							data: {zone_ids: exclude_zone_ids},
							success: function(response)
							{
									
								$(document).Toasts('create', {
									title: 'Mass exclude',
									class: 'bg-success',
									autohide: true,
									delay: 5000,
									body: 'Message: ' + response.message,
								});
								
								btn.prop('disabled', false);
							}
						});
					
					}
					else
					{
						$(document).Toasts('create', {
							title: 'Mass exclude',
							class: 'bg-danger',
							autohide: true,
							delay: 5000,
							body: 'Select some zones to exclude',
						});
						btn.prop('disabled', false);
					}
				});

				$(document).on('click', '#btn_mass_remove_exclude', function()
				{
					var btn = $(this);
					btn.prop('disabled', true);
					var remove_exclude_zone_ids = [];
					$('.mass_exclude_selection:checked').each(function (idx)
					{
						remove_exclude_zone_ids.push($(this).data('zone_id'));	
					});

					if(remove_exclude_zone_ids.length>0)
					{
						$.ajax(
						{
							type: "POST",
							url: "/zones/mass_remove_exclude",
							data: {zone_ids: remove_exclude_zone_ids},
							success: function(response)
							{
									
								$(document).Toasts('create', {
									title: 'Mass remove exclude',
									class: 'bg-success',
									autohide: true,
									delay: 5000,
									body: 'Message: ' + response.message,
								});
								
								btn.prop('disabled', false);
							}
						});
					
					}
					else
					{
						$(document).Toasts('create', {
							title: 'Mass remove exclude',
							class: 'bg-danger',
							autohide: true,
							delay: 5000,
							body: 'Select some zones to remove exclude',
						});
						btn.prop('disabled', false);
					}
				});
				
				$(document).on('click', '#btn_mass_exclude_select_duplicates', function()
				{
					mass_excludes_table.rows().every( function ( rowIdx,element )
					{
						var row = $(this.node());
						var cell = row.find('td input[data-duplicate="1"]').eq(0);
						cell.prop('checked', true);
						
					});


				});

				$(document).on('click', '#btn_mass_exclude_select_all', function()
				{
					mass_excludes_table.rows().every( function ( rowIdx,element )
					{
						var row = $(this.node());
						var cell = row.find('td input').eq(0);
						cell.prop('checked', true);
						
					});
				});

				$(document).on('click', '#btn_mass_exclude_unselect_all', function()
				{
					mass_excludes_table.rows().every( function ( rowIdx,element )
					{
						var row = $(this.node());
						var cell = row.find('td input').eq(0);
						cell.prop('checked', false);
						
					});
				});

				$(document).on('click', '#btn_load_mass_exclude_zones', function()
				{
          var show_excluded = false;
          if($('#show_excluded').prop('checked'))
          {
            show_excluded = true;
          }
					var server = $('#mass_exclude_option').val();
					$.ajax(
					{
						type: "POST",
						url: "/zones/mass_exclude_load_zones",
						data: {server_id: server, show_excluded: show_excluded},
						success: function (response)
						{
							$('#mass_exclude_table_wrapper').show();
							mass_excludes_table.clear();
							mass_excludes_table.rows.add(response).draw();
						}
					});
				});
        $(document).on('click', '#btn_reload_duplicates', function()
        {
          load_duplicates();
        });

        $(document).on('click', '#btn_reload_excluded', function()
        {
          load_excluded();
        });

        $(document).on('click', '.btn_exclude',  function () {
            var zone = $(this).data('zone');
            var server = $(this).data('server');
            var server_name = $(this).data('server_name')
            $('#btnModalExclude').data('zone',zone);
            $('#btnModalExclude').data('server',server);

            $('.modal_zone').text(zone);
            $('.modal_server').text(server_name);
            $('#modal_exclude').modal('show');
             
        });
        $(document).on('click', '#btnModalExclude', function()
            {
              var zone = $(this).data('zone');
              var server = $(this).data('server');
              $('#modal_exclude').modal('hide');
              $.ajax({
                type : 'POST',
                url : '/zones/exclude',
                data : {zone:zone, server:server},
                success : function(response)
                {
                  if (response.code == "ok")
                  {
										$(document).Toasts('create', {
										title: 'Excluding ' + zone,
										class: 'bg-success',
											autohide: true,
											delay: 2000,
											body: response.message
										});
                  }
                  else
                  {
										$(document).Toasts('create', {
											title: 'Excluding ' + zone,
											class: 'bg-warning',
											autohide: true,
											delay: 2000,
											body: response.message
										});
                  }
                }
              })
            });
        $(document).on('click', '.btn_remove_exclude', function ()
        {
            var zone = $(this).data('zone');
            var server = $(this).data('server');
            var server_name = $(this).data('server_name')
            $('#btnModalRemoveExclude').data('zone',zone);
            $('#btnModalRemoveExclude').data('server',server);
            $('.modal_remove_zone').text(zone);
            $('.modal_remove_server').text(server_name);
            $('#modal_remove_exclude').modal('show');

        });
        $(document).on('click', '#btnModalRemoveExclude', function()
        {
          var zone = $(this).data('zone');
          var server = $(this).data('server');

          $('#modal_remove_exclude').modal('hide');
          $.ajax({
              type : 'POST',
              url : '/zones/exclude/remove',
              data : {zone:zone, server:server},
              success : function(response)
              {
                  if (response.code == "ok")
                  {
										$(document).Toasts('create', {
										title: 'Removing exclude of ' + zone,
										class: 'bg-success',
											autohide: true,
											delay: 2000,
											body: response.message
										});
                  }
                  else
                  {
										if (response.code == "ok")
										{
											$(document).Toasts('create', {
											title: 'Removing exclude of ' + zone,
											class: 'bg-warning',
												autohide: true,
												delay: 2000,
												body: response.message
											});
										}
									}
              }
          });
        });
    });
</script>
@endsection
