@extends('layouts.app')
@section('title') Zones bulk operations @endsection
@section('content')

<div x-data="{ step_1: true, step_2: false,agent_name:'',loading: false, ex_open: false, selected_count: 0, agent_id: null, operation: ''}">

<div x-cloak
       @keydown.window.escape="ex_open = false"
       x-show="ex_open"
       class="relative z-10"
       aria-labelledby="modal-title"
       x-ref="dialog"
       aria-modal="true">
  
    <div x-show="ex_open"
         x-transition:enter="ease-out duration-300"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         x-transition:leave="ease-in duration-200"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0"
         x-description="Background backdrop, show/hide based on modal state."
         class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
         aria-hidden="true"></div>
  
  
    <div class="fixed inset-0 z-10 w-screen overflow-y-auto">
      <div class="flex min-h-full items-end justify-center p-4 text-center items-center sm:p-0">
        <div x-show="ex_open"
             x-transition:enter="ease-out duration-300"
             x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
             x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
             x-transition:leave="ease-in duration-200"
             x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
             x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
             x-description="Modal panel, show/hide based on modal state."
             class="relative transform overflow-hidden rounded-lg border-t-2 border-orange-600 bg-white dark:bg-slate-800 text-left shadow-xl transition-all my-8 w-full max-w-lg"
             @click.away="ex_open = false">
          <div class="bg-white dark:bg-slate-800 px-4 pb-4 pt-5 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:flex-col sm:items-start">
              <div class="sm:flex sm:flex-row items-center">
                <div class="mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-gray-100 sm:mx-0 sm:h-10 sm:w-10">
                <svg xmlns="http://www.w3.org/2000/svg"
                     viewBox="0 0 20 20"
                     fill="currentColor"
                     class="size-5 fill-orange-600">
                  <path fill-rule="evenodd"
                        d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495ZM10 5a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 10 5Zm0 9a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"
                        clip-rule="evenodd" />
                </svg>
                </div>
                <div class="mt-3 w-full text-center sm:ml-4 sm:mt-0 sm:text-left text-gray-900 dark:text-white">
                  <h3 class="text-lg font-semibold leading-6"
                      id="modal-title">
                      <span x-text="operation == 'exclude' ? 'Exclude' : 'Remove exclude'"></span> zones from <span x-text="agent_name" class="underline"></span>
                  </h3>
                  <hr class="border-slate-200 dark:border-slate-700 my-3">
                  <div class="text-base">
                    This action will <span x-text="operation == 'exclude' ? 'exclude' : 'remove the exclusion of'"></span> <span class="font-bold underline" x-text="selected_count"></span> zones from <span class="font-bold" x-text="agent_name"></span>.
                  </div>
                </div>
              </div>  
            </div>
          </div>
          <div class="px-4 py-3 text-center">
            <button type="button"
                    x-text="operation == 'exclude' ? 'Exclude' : 'Remove exclude'"
                    class="mt-3 inline-flex items-center px-4 py-2 text-sm font-medium text-gray-900 bg-white border border-orange-700 rounded-lg hover:bg-gray-100 focus:z-10 focus:ring-2 focus:ring-blue-700 focus:text-blue-700 dark:bg-gray-800 dark:border-orange-700 dark:text-white dark:hover:text-white dark:hover:bg-gray-700 dark:focus:ring-blue-500 dark:focus:text-white"
                    x-on:click="ex_open = false;(operation == 'exclude' ? exclude_zones(agent_id) : remove_exclude_zones(agent_id))"></button>
          </div>
        </div>
  
      </div>
    </div>
  </div>


 <div x-show="step_1" class="mt-4 flex p-4 border-l-2 border-indigo-400 flex-col bg-white dark:bg-slate-900 rounded-md drop-shadow-md animate-slide-up-fade-in">
  <div>
   Select an agent to load its zones:
  </div>
  <div class="text-center overflow-x-auto">
   <table class="border-collapse table-auto w-full">
    <thead>
     <tr>
      <th class="p-2">Name</th>
      <th class="p-2">Zones</th>
      <th class="p-2">Cluster</th>
     </tr>
    </thead>
    <tbody class="text-sm">
    @foreach($agents as $agent)
     <tr x-on:click="step_1=false;step_2=true;agent_name='{{$agent->name}}';loading=true;load_zones({{$agent->id}});agent_id={{$agent->id}}" class="border-y border-indigo-200 dark:border-indigo-800 hover:bg-slate-100 dark:hover:bg-slate-800 hover:cursor-pointer" >
      <td class="p-2">{{ $agent->name }}</td>
      <td class="p-2">{{ $agent->zones_count }}</td>
      <td class="p-2">{{ $agent->getCluster() }}</td>
     </tr>
    @endforeach
    </tbody>
   </table>
  </div>
 </div>

 <div x-cloak x-show="step_2" class="mt-4 flex-col p-4 border-l-2 border-indigo-400 flex-col bg-white dark:bg-slate-900 rounded-md drop-shadow-md animate-slide-up-fade-in">
  <button x-on:click="step_2=false;step_1=true;loading=false;"
    class="inline-flex items-center  px-4 py-2 text-sm font-medium text-gray-900 bg-white border border-gray-200 rounded-lg hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:text-white dark:hover:text-white dark:hover:bg-gray-700 w-fit">
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="size-5">
      <path fill-rule="evenodd" d="M18 10a.75.75 0 0 1-.75.75H4.66l2.1 1.95a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 1 1 1.02 1.1l-2.1 1.95h12.59A.75.75 0 0 1 18 10Z" clip-rule="evenodd" />
    </svg>
    Go back to agent list
  </button>
  <div class="p-4 mt-2 text-center">
   <span class="font-bold text-lg underline" x-text="agent_name"></span> zones
  </div>
  <div x-show="loading" class="text-center" x-on:loading-hide.window="loading=false">
   <svg aria-hidden="true" class="inline my-3 w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/>
    <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/>
   </svg>
  </div>
  <div class="text-center">
    <div class="inline-flex my-2 px-2">
      <button x-on:click="select_all_zones(1)" class="px-4 py-2 text-xs text-gray-900 border border-slate-200 dark:border-slate-600 bg-orange-400 dark:bg-orange-800 rounded-s-md  dark:text-white w-fit">Select excluded</button>
      <button x-on:click="select_all_zones(2)" class="px-4 py-2 text-xs text-gray-900 border border-slate-200 dark:border-slate-600 bg-green-400 dark:bg-green-800 dark:text-white w-fit ">Select not excluded</button>
      <button x-on:click="select_all_zones(4)" class="px-4 py-2 text-xs text-gray-900 border border-slate-200 dark:border-slate-600 bg-red-400 dark:bg-red-800 dark:text-white w-fit ">Select duplicates</button>      
      <button x-on:click="select_all_zones(0)" class="px-4 py-2 text-xs text-gray-900 border border-slate-200 dark:border-slate-600 dark:text-white w-fit ">Select all</button>
      <button x-on:click="select_all_zones(3)" class="px-4 py-2 text-xs text-gray-900 border border-slate-200 dark:border-slate-600 rounded-e-md dark:text-white w-fit ">De-select all</button>

    </div>
  </div>
  <div class="text-center overflow-x-auto">
   <table id="zones_table" class="border-collapse table-auto w-full">
    <thead>
     <tr>
      <th>Select</th>
      <th>Zone</th>
      <th>Owner</th>
      <th>Excluded?</th>
      <th>Duplicate?</th>
     </tr>
    </thead>
    <tbody>

    </tbody>
   </table>
  </div>
  <div class="text-center mt-2 p-4">
    <div class="inline-flex">
    <button x-on:click="if(count_selected_zones() > 0){operation='exclude',ex_open=true; selected_count=count_selected_zones()}"
      class="px-4 py-2 text-sm font-medium text-gray-900 bg-orange-400 border-s border-y border-slate-900 rounded-s-lg dark:bg-orange-800 dark:border-slate-200 dark:text-white w-fit">
      Exclude selected zones
    </button>
    <button x-on:click="if(count_selected_zones() > 0){operation='remove exclude',ex_open=true; selected_count=count_selected_zones()}"
      class="px-4 py-2 text-sm font-medium text-gray-900 bg-green-400 border border-slate-900 rounded-e-lg dark:bg-green-800 dark:border-slate-200 dark:text-white w-fit">
      Remove exclude from selected zones
    </button>
    </div>
  </div>
 </div>

</div>

<script>
 const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

 document.addEventListener('DOMContentLoaded', function () {
  document.getElementById('menu_zones').classList.remove('text-gray-500');
  document.getElementById('menu_zones').classList.remove('hover:bg-gray-700');
  document.getElementById('menu_zones').classList.remove('hover:bg-opacity-25');
  document.getElementById('menu_zones').classList.remove('hover:text-gray-100');
  document.getElementById('menu_zones').classList.add('text-gray-100');
  document.getElementById('menu_zones').classList.add('bg-opacity-25');
  document.getElementById('menu_zones').classList.add('bg-gray-700');
  document.getElementById('menu_mass_exclude').classList.remove('text-gray-500');
  document.getElementById('menu_mass_exclude').classList.remove('hover:bg-gray-700');
  document.getElementById('menu_mass_exclude').classList.remove('hover:bg-opacity-25');
  document.getElementById('menu_mass_exclude').classList.remove('hover:text-gray-100');
  document.getElementById('menu_mass_exclude').classList.add('text-gray-100');
  document.getElementById('menu_mass_exclude').classList.add('bg-opacity-25');
  document.getElementById('menu_mass_exclude').classList.add('bg-gray-700');
  document.getElementById('menu_mass_exclude').classList.add('border-e-2');
  document.getElementById('menu_mass_exclude').classList.add('border-indigo-400');
  window.dispatchEvent(new CustomEvent('open-zones-menu'));
  zones_table = new DataTable("#zones_table",
  {
   perPageSelect: [20, 100, 500, ["All", 0]],
     rowRender: (row, tr, _index) => {
    if (tr.childNodes) {
     tr.attributes.class = "border-y border-slate-200 dark:border-slate-600 hover:cursor-pointer hover:bg-slate-100 dark:hover:bg-slate-800";
     tr.childNodes.forEach(td => {
      td.attributes.class = "p-1 text-center";
     });
        }
   },
   data: {
    headings: [
     {
      text: 'Select',
      data: 'checked',
     },
     {
      text: 'Zone',
      data: 'zone'
     },
     {
      text: 'Owner',
      data: 'owner',
     },
     {
      text: 'Excluded?',
      data: 'excluded',
     },
     {
      text: 'Duplicate?',
      data: 'duplicate',
     },
    ],
   },
   columns: [
    { 
      select: 0,
      data: 'checked',
      type: 'other',
      headerClass: 'font-medium p-3',
      render: (value, _td, _rowIndex, _cellIndex) => `<span class="checkbox" name="zone_select_${value.id}"><div class="box-border h-4 w-4 rounded-md border border-slate-900 dark:border-slate-300 inline-block ${value.checked ? 'bg-green-400' : 'bg-inherit'}"></div></span>`
    },
    {
     headerClass: 'font-medium p-3',
     select: 1,
     data: 'zone'
    },
    {
     select: 2,
     data: 'owner',
     headerClass: 'font-medium p-3',
     render: data => {
      if ("null" === data[0].data)
       return "N/A";
     }
    },
    {
     select: 3,
     data: 'excluded',
     type: 'boolean',
     headerClass: 'font-medium p-3',
     render: (value, _td, _rowIndex, _cellIndex) => `<span class="px-2 rounded-md ${value ? "bg-orange-400 dark:bg-orange-800 dark:text-slate-100" : "bg-green-400 dark:bg-green-700 dark:text-white"}">${value ? "Yes" : "No"}</span>`
    },
    {
      select: 4,
      data: "duplicate",
      type: 'other',
      headerClass: 'font-medium p-3',
      render: (value, _td, _rowIndex, _cellIndex) => value.not_excluded_server_count > 1 ? `<span class="px-2 rounded-md bg-orange-400 dark:bg-orange-800 dark:text-slate-100">Yes</span>` : `No`,
    }
   ]
  });

  zones_table.dom.addEventListener("click", event => {
    if ( event.target.matches("tbody > tr *") ) {
      event.preventDefault();
      event.stopPropagation();
      var _index = event.target.closest("tr").dataset.index;
      zones_table.data.data[_index].cells[0].data.checked = !zones_table.data.data[_index].cells[0].data.checked;
      zones_table.update();
    }
  });
 });
 function load_zones(server_id)
 {
  zones_table.data.data = [];
  zones_table.update();
  fetch('{{ route('mass_operations_get_zones') }}', {
   method: 'POST',
   headers: {
    'X-CSRF-TOKEN': csrfToken,
    'Content-Type': 'application/json',
    'Accept': 'application/json',
   },
   body: JSON.stringify({ server_id: server_id}),
  })
   .then(response => response.json())
   .then(response => {
    window.dispatchEvent(new CustomEvent('loading-hide'));
    var table_data = [];
    response.zones.forEach((zone) => {
     const record = { excluded: (zone.excluded == 1) ? true : false, zone: zone.zone, owner: zone.owner, checked: {id: zone.id, checked: false}, duplicate: { not_excluded_server_count: zone.not_excluded_server_count, servers: zone.duplicate_servers} };
     table_data.push(record);
    }, undefined, table_data);
    zones_table.insert(table_data);
   });
 }

 function count_selected_zones()
 {
  var count = 0;
  zones_table.data.data.forEach((row) => {
    if ( row.cells[0].data.checked )
    {
      count++;
    }
  });
  return count;
 }

 function exclude_zones(_agent_id)
 {
  if ( count_selected_zones() > 0 && _agent_id !== null )
  {
   zones_to_be_excluded = [];
   //mass_exclude_post
   zones_table.data.data.forEach((row) => {
    if ( row.cells[0].data.checked )
    {
     zones_to_be_excluded.push({'zone': row.cells[1].data[0].data, 'agent_id': _agent_id, 'zone_id': row.cells[0].data.id});
    }
   });
   fetch('{{ route('mass_operations_exclude') }}', {
      method: 'POST',
      headers: {
        'X-CSRF-TOKEN': csrfToken,
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: JSON.stringify({'zones_array': zones_to_be_excluded}),
    })
      .then(response => response.json())
      .then(response => {
        load_zones(_agent_id);
      });
  }
 }

 function remove_exclude_zones(_agent_id)
 {
  if ( count_selected_zones() > 0 && _agent_id !== null )
  {
   zones_to_remove_exclude = [];
   //mass_exclude_post
   zones_table.data.data.forEach((row) => {
    if ( row.cells[0].data.checked )
    {
      zones_to_remove_exclude.push({'zone': row.cells[1].data[0].data, 'agent_id': _agent_id, 'zone_id': row.cells[0].data.id});
    }
   });
   fetch('{{ route('mass_operations_remove_exclude') }}', {
      method: 'POST',
      headers: {
        'X-CSRF-TOKEN': csrfToken,
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: JSON.stringify({'zones_array': zones_to_remove_exclude}),
    })
      .then(response => response.json())
      .then(response => {
        load_zones(_agent_id);
      });
  }
 }

 /* _select_type = 0 -> Select all
 ** _select_type = 1 -> Select only excluded
 ** _select_type = 2 -> Select only NOT excluded
 ** _select_type = 3 -> Deselect all
 ** _select_type = 4 -> Selecte duplicates
 */
 function select_all_zones(_select_type = 0)
 {
  zones_table.data.data.forEach((row) =>
  {
    _select_type == 0 ? ( row.cells[0].data.checked = true )  : {} ;
    _select_type == 1 ? ( row.cells[3].data ? row.cells[0].data.checked = true : row.cells[0].data.checked = false ) : {};
    _select_type == 2 ? ( row.cells[3].data ? row.cells[0].data.checked = false : row.cells[0].data.checked = true ) : {};
    _select_type == 3 ? ( row.cells[0].data.checked = false )  : {} ;
    _select_type == 4 ? ( row.cells[4].data.not_excluded_server_count > 1 ? row.cells[0].data.checked = true : row.cells[0].data.checked = false ) : {};
  });
    zones_table.refresh();
 }
</script>
@endsection
