@include('header')

<!-- Tabs Navs -->
<div class="row clearfix" id="" style="margin:20px; width:100%;">
  <ul class="nav nav-tabs custom-pills services" id="avaTab" role="tablist">
    <li class="nav-item">
      <a class="nav-link" id="dashboard-tab" data-toggle="tab" href="#dashboard" role="tab" aria-controls="dashboard" aria-selected="true">Dashboard</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="incoming-tab" data-toggle="tab" href="#incoming" role="tab" aria-controls="incoming" aria-selected="false">Incoming Replications</a>
    </li>
    <li class="nav-item">
      <a class="nav-link active" id="outgoing-tab" data-toggle="tab" href="#outgoing" role="tab" aria-controls="outgoing" aria-selected="false">Outgoing Replications</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="replicationTasks-tab" data-toggle="tab" href="#replicationTasks" role="tab" aria-controls="replicationTasks" aria-selected="false">Replication Tasks</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="recoveryPlans-tab" data-toggle="tab" href="#recoveryPlans" role="tab" aria-controls="recoveryPlans" aria-selected="false">Recovery Plans</a>
    </li>
  </ul>
</div>
<!-- Tabs Navs -->
<!-- Tabs content -->
<div class="tab-content" id="avaTabContent">
  <div class="tab-pane fade" id="dashboard" role="tabpanel" aria-labelledby="dashboard-tab">
    @include('dashboard')
  </div>
  <div class="tab-pane fade" id="incoming" role="tabpanel" aria-labelledby="incoming-tab">
    @include('incomingReplications/incoming')
  </div>
  <div class="tab-pane fade show active" id="outgoing" role="tabpanel" aria-labelledby="outgoing-tab">
    @include('outgoingReplications/outgoing')
  </div>
  <div class="tab-pane fade" id="replicationTasks" role="tabpanel" aria-labelledby="replicationTasks-tab">
    @include('replicationTasks')
  </div>
  <div class="tab-pane fade" id="recoveryPlans" role="tabpanel" aria-labelledby="recoveryPlans-tab">
    @include('recoveryPlans/recoveryPlans')
  </div>
</div>

@include('footer')


<!-- Exapand Table in Recover Setting Information -->
<script>
  $(document).on('click', '.expandable-row', function() {
    // Your existing toggle logic
    // Find the chevron icon and rotate it
    $(this).find('i').toggleClass('fa-chevron-right fa-chevron-down');
    // Toggle the next detail rows
    $(this).nextUntil('tr.expandable-row').toggleClass('hidden-row');
  });
</script>

<!-- Line Chart (Four) -->
<!-- Dashboard  & Infromation  -->
<script>
  $(document).ready(function() {
    function generateXLabels(interval) {
      var now = new Date();
      var labels = [];
      for (var i = -6; i <= 0; i++) {
        var date = new Date(now);
        date.setMinutes(now.getMinutes() + i * interval);
        var timeString = ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
        var dateString = ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2);
        var label = timeString + '\n' + dateString;
        labels.push(label);
      }
      return labels;
    }

    var initialData = {
      labels: generateXLabels(5),
      datasets: [{
        label: '',
        data: [0, 10, 20, 30, 20, 10, 0],
        backgroundColor: 'transparent',
        borderColor: 'rgba(75, 192, 192, 1)',
        borderWidth: 1,
        fill: false
      }]
    };

    var chartOptions = {
      type: 'line',
      data: initialData,
      options: {
        plugins: {
          legend: {
            display: false
          }
        },
        scales: {
          x: {
            display: true,
            grid: {
              display: false
            }
          },
          y: {
            display: true,
            beginAtZero: false,
            ticks: {
              min: -30,
              max: 30,
              stepSize: 10
            }
          }
        },
        elements: {
          point: {
            radius: 0
          }
        }
      }
    };

    var ctx1 = document.getElementById('lineChart').getContext('2d');
    var lineChart1 = new Chart(ctx1, chartOptions);

    var ctx2 = document.getElementById('lineChart2').getContext('2d');
    var lineChart2 = new Chart(ctx2, chartOptions);

    var ctx3 = document.getElementById('lineChart3').getContext('2d');
    var lineChart3 = new Chart(ctx3, chartOptions);

    var ctx4 = document.getElementById('lineChart4').getContext('2d');
    var lineChart4 = new Chart(ctx4, chartOptions);

    var ctx3 = document.getElementById('lineChart5').getContext('2d');
    var lineChart3 = new Chart(ctx3, chartOptions);

    var ctx4 = document.getElementById('lineChart6').getContext('2d');
    var lineChart4 = new Chart(ctx4, chartOptions);

    // Event for the first chart
    $('#timeInterval').change(function() {
      var interval = $(this).val();
      var newLabels = generateXLabels(interval);
      var newData = new Array(7).fill(null).map(() => Math.random() * 60 - 30);

      lineChart1.data.labels = newLabels;
      lineChart1.data.datasets[0].data = newData;
      lineChart1.update();
    });

    // Event for the second chart
    $('#timeInterval2').change(function() {
      var interval = $(this).val();
      var newLabels = generateXLabels(interval);
      var newData = new Array(7).fill(null).map(() => Math.random() * 60 - 30);

      lineChart2.data.labels = newLabels;
      lineChart2.data.datasets[0].data = newData;
      lineChart2.update();
    });

    // Event for the third chart
    $('#timeInterval3').change(function() {
      var interval = $(this).val();
      var newLabels = generateXLabels(interval);
      var newData = new Array(7).fill(null).map(() => Math.random() * 60 - 30);

      lineChart3.data.labels = newLabels;
      lineChart3.data.datasets[0].data = newData;
      lineChart3.update();
    });

    // Event for the 4th chart
    $('#timeInterval4').change(function() {
      var interval = $(this).val();
      var newLabels = generateXLabels(interval);
      var newData = new Array(7).fill(null).map(() => Math.random() * 60 - 30);

      lineChart4.data.labels = newLabels;
      lineChart4.data.datasets[0].data = newData;
      lineChart4.update();
    });

    $('#timeInterval5').change(function() {
      var interval = $(this).val();
      var newLabels = generateXLabels(interval);
      var newData = new Array(7).fill(null).map(() => Math.random() * 60 - 30);

      lineChart5.data.labels = newLabels;
      lineChart5.data.datasets[0].data = newData;
      lineChart5.update();
    });

    $('#timeInterval6').change(function() {
      var interval = $(this).val();
      var newLabels = generateXLabels(interval);
      var newData = new Array(7).fill(null).map(() => Math.random() * 60 - 30);

      lineChart6.data.labels = newLabels;
      lineChart6.data.datasets[0].data = newData;
      lineChart6.update();
    });

    // Trigger initial update for both charts
    $('#timeInterval').change();
    $('#timeInterval2').change();
    $('#timeInterval3').change();
    $('#timeInterval4').change();
    $('#timeInterval5').change();
    $('#timeInterval6').change();
  });
</script>

<!-- Live Chart (Infromation "Traffic")-->
<script>
  $(document).ready(function() {
    var createChart = function(canvasId) {
      var ctx = $('#' + canvasId).get(0).getContext('2d');
      return new Chart(ctx, {
        type: 'line',
        data: {
          labels: [],
          datasets: [{
            label: 'Live Data',
            data: [],
            backgroundColor: 'rgba(0, 123, 255, 0.5)',
            borderColor: 'rgba(0, 123, 255, 1)',
            borderWidth: 1,
            lineTension: 0.1
          }]
        },
        options: {
          animation: {
            duration: 0 // No animation for data update
          },
          scales: {
            yAxes: [{
              ticks: {
                min: -30,
                max: 30,
                stepSize: 10
              }
            }],
            xAxes: [{
              type: 'time',
              time: {
                unit: 'second',
                displayFormats: {
                  second: 'HH:mm:ss'
                }
              },
              ticks: {
                autoSkip: true,
                maxTicksLimit: 10
              }
            }]
          }
        }
      });
    };

    var liveChart = createChart('liveChart');
    var liveChart2 = createChart('liveChart2');

    function addData(chart, label, data) {
      if (chart.data.labels.length > 9) {
        chart.data.labels.shift();
        chart.data.datasets.forEach((dataset) => {
          dataset.data.shift();
        });
      }
      chart.data.labels.push(label);
      chart.data.datasets.forEach((dataset) => {
        dataset.data.push(data);
      });
      chart.update({
        preservation: true
      });
    }

    function updateCharts() {
      var now = new Date();
      var timeString = now.toTimeString().split(' ')[0];
      addData(liveChart, timeString, Math.random() * 100);
      addData(liveChart2, timeString, Math.random() * 100 - 50);
    }

    setInterval(updateCharts, 1000);
  });
</script>

<!-- Information "Traffic" Buttons actions -->
<script>
  $(document).ready(function() {
    // 1
    $('#liveButton').click(function() {
      $('#liveChartContainer').removeClass('hidden');
      $('#recordedChartContainer').addClass('hidden');
    });

    $('#recordedButton').click(function() {
      $('#liveChartContainer').addClass('hidden');
      $('#recordedChartContainer').removeClass('hidden');
    });

    // 2
    $('#liveButton2').click(function() {
      $('#liveChartContainer2').removeClass('hidden');
      $('#recordedChartContainer2').addClass('hidden');
    });

    $('#recordedButton2').click(function() {
      $('#liveChartContainer2').addClass('hidden');
      $('#recordedChartContainer2').removeClass('hidden');
    });


    $('.btn-graf-status').click(function() {
      // Remove 'active' class from all buttons and then add it to the clicked one
      $('.btn-graf-status').removeClass('active');
      $(this).addClass('active');
    });
    $('.btn-graf-status-out').click(function() {
      // Remove 'active' class from all buttons and then add it to the clicked one
      $('.btn-graf-status-out').removeClass('active');
      $(this).addClass('active');
    });

  });
</script>

<!-- Scatter Chart (dotChart) -->
<script>
  // Function to initialize a scatter chart
  function initScatterChart(chartId) {
    const ctx = document.getElementById(chartId).getContext('2d');
    const scatterChart = new Chart(ctx, {
      type: 'scatter',
      data: {
        datasets: [{
          label: 'Sample Dataset',
          backgroundColor: '#007CBB',
          borderColor: '#003D79',
          pointRadius: 10,
          data: [{
              x: 3,
              y: 5,
              date: '01/01/2024',
              time: '12:00:00 PM',
              dataTransferred: '0.00B',
              disksKeys: '2000',
              quiescedType: 'Unquiesced replica'
            },
            // ... more data points ...
          ],
        }]
      },
      options: {
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                const point = context.raw;
                return [
                  `Date: ${point.date}, ${point.time}`,
                  `Data transferred: ${point.dataTransferred}`,
                  `Disks keys: ${point.disksKeys}`,
                  `Quiesced type: ${point.quiescedType}`
                ];
              }
            }
          }
        },
        scales: {
          x: {
            ticks: {
              display: false
            },
            grid: {
              drawBorder: true,
              borderColor: 'rgba(0, 0, 0, 0.25)',
              color: 'rgba(0, 0, 0, 0)'
            }
          },
          y: {
            ticks: {
              display: false
            },
            grid: {
              drawBorder: true,
              borderColor: 'rgba(0, 0, 0, 0.25)',
              color: 'rgba(0, 0, 0, 0)'
            }
          }
        }
      }
    });
  }

  // Initialize the first scatter chart
  initScatterChart('dotChart');

  // Initialize the second scatter chart
  initScatterChart('dotChart2');

  // Initialize the third scatter chart
  initScatterChart('dotChart3');

  // Initialize the fourth scatter chart
  initScatterChart('dotChart4');
</script>

<!-- RPO Table -->
<script>
  $(document).ready(function() {
    function handleTableClick($table, $overlay) {
      $table.find('td').click(function() {
        // Remove 'active-cell' class from all cells and add to the clicked one
        $table.find('td').removeClass('active-cell');
        $(this).addClass('active-cell');
        $(this).prevAll().addClass('active-cell');

        // Get the text from the 'title' attribute of the clicked cell
        var titleText = $(this).attr('title');
        // Get the position of the clicked cell
        var cellPos = $(this).position();
        // Get the height of the clicked cell to calculate top position
        var cellHeight = $(this).outerHeight();

        // Set the text of the overlay
        $overlay.text(titleText);
        // Position the overlay right below the clicked cell
        $overlay.css({
          'display': 'block',
          'top': (cellPos.top + cellHeight) + 'px', // Position below the cell
          'left': cellPos.left + 'px', // Align with the cell horizontally
          'pointer-events': 'none' // Allows clicks to go through the overlay
        });
      });
    }

    // Apply the function to the first table and overlay
    handleTableClick($('#rpoTd1'), $('#customTitleOverlay1'));

    // Apply the function to the second table and overlay
    handleTableClick($('#rpoTd2'), $('#customTitleOverlay2'));

    // Apply the function to the second table and overlay
    handleTableClick($('#rpoTd3'), $('#customTitleOverlay3'));

    // Apply the function to the second table and overlay
    handleTableClick($('#rpoTd4'), $('#customTitleOverlay4'));
  });
</script>

<!-- popover -->
<script>
  $(document).ready(function() {
    $('#btn-popover-info , #btn-popover-info-1').popover({
      html: true,
      content: `
      @include('/outgoingReplications/information/infoPopoverGuest')
            `,
      template: '<div class="popover" role="tooltip" style="min-width: 500px;"><div class="arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'
    });

    $('#btn-info-nics , #btn-info-nics1').popover({
      html: true,
      content: `
      @include('/outgoingReplications/information/infoPopoverNics')
            `,
      template: '<div class="popover" role="tooltip" style="min-width: 500px;"><div class="arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'
    });

    // Collapse function for multiple buttons
    $(".btn-link-collapse").click(function(e) {
      e.preventDefault();
      var target = $(this).data("target");
      $(target).toggle(); // This will toggle the visibility of the collapse element
    });


  });
</script>

<!-- Form step -->
<script>
  function setupFormSteps(modalId) {
    var modal = $("#" + modalId);
    var steps = modal.find(".main-form");
    var currentStep = 0;
    var nextButton = modal.find(".next-button");
    var backButton = modal.find(".back-button");
    var sidebarLinks = modal.find(".sidebar-step");

    function updateSidebar(step) {
      sidebarLinks.removeClass("active");
      $(sidebarLinks[step]).addClass("active");
    }

    function showStep(step) {
      steps.hide();
      $(steps[step]).show();
      backButton.toggle(step !== 0); // Show 'Previous' button except on the first step

      if (step === steps.length - 1) {
        nextButton.text("Finish");
      } else {
        nextButton.text("Next");
      }

      updateSidebar(step); // Update the sidebar active state
    }

    // Initialize the first step
    showStep(currentStep);

    nextButton.click(function() {
      if (currentStep < steps.length - 1) {
        currentStep++;
      } else {
        // Handle the final step (Finish) action here
      }
      showStep(currentStep);
    });

    backButton.click(function() {
      if (currentStep > 0) {
        currentStep--;
      }
      showStep(currentStep);
    });
  }

  $(document).ready(function() {
    // outgoing
    setupFormSteps('newProtection');
    setupFormSteps('newMigration');
    setupFormSteps('fastMigrate');
    setupFormSteps('migrateModal');
    setupFormSteps('failoverModal');
    setupFormSteps('testModal');
    setupFormSteps('newRecoveryStep');
    // Incoming
    setupFormSteps('incoming-newProtection');
    setupFormSteps('incoming-newMigration');
    setupFormSteps('incoming-fastMigrate');
    setupFormSteps('incoming-migrateModal');
    setupFormSteps('incoming-failoverModal');
    setupFormSteps('incoming-testModal');
  });
</script>

<!-- slide content -->
<script>
  var h = false;
  $('.btn-slideContent').click(function(event) {
    if (h === false) {
      // Hide the columns, except in #attach-table and #attachRep-table
      $('td:not(#attach-table td, #attachRep-table td):nth-child(3), th:not(#attach-table th, #attachRep-table th):nth-child(3)').hide("fast");
      $('td:not(#attach-table td, #attachRep-table td):nth-child(4), th:not(#attach-table th, #attachRep-table th):nth-child(4)').hide("fast");
      $('td:not(#attach-table td, #attachRep-table td):nth-child(5), th:not(#attach-table th, #attachRep-table th):nth-child(5)').hide("fast");
      $('td:not(#attach-table td, #attachRep-table td):nth-child(6), th:not(#attach-table th, #attachRep-table th):nth-child(6)').hide("fast");
      $('td:not(#attach-table td, #attachRep-table td):nth-child(7), th:not(#attach-table th, #attachRep-table th):nth-child(7)').hide("fast");
      // Show the slide content
      $('td:nth-child(8), th:nth-child(8)').show("fast");
    } else {
      // Show the columns, except in #attach-table and #attachRep-table
      $('td:not(#attach-table td, #attachRep-table td):nth-child(3), th:not(#attach-table th, #attachRep-table th):nth-child(3)').show("fast");
      $('td:not(#attach-table td, #attachRep-table td):nth-child(4), th:not(#attach-table th, #attachRep-table th):nth-child(4)').show("fast");
      $('td:not(#attach-table td, #attachRep-table td):nth-child(5), th:not(#attach-table th, #attachRep-table th):nth-child(5)').show("fast");
      $('td:not(#attach-table td, #attachRep-table td):nth-child(6), th:not(#attach-table th, #attachRep-table th):nth-child(6)').show("fast");
      $('td:not(#attach-table td, #attachRep-table td):nth-child(7), th:not(#attach-table th, #attachRep-table th):nth-child(7)').show("fast");
      // Hide the slide content
      $('td:nth-child(8), th:nth-child(8)').hide("fast");
    }
    h = !h; // Toggle the value of h
  });

  // Function to toggle content for a specific table, button, and content class
  function toggleContent(tableId, buttonClass, contentClass) {
    var isVisible = false;
    $(tableId + ' ' + buttonClass).click(function() {
      // Toggle the visibility of the specific content within the table
      $(this).closest('tr').find(contentClass).toggle('fast');
      isVisible = !isVisible; // Update the visibility flag

      if (isVisible) {
        // If content is visible, hide the third column and show the fourth
        $(this).closest('table').find('th:nth-child(3), td:nth-child(3)').hide('fast');
        $(this).closest('table').find('th:nth-child(4), td:nth-child(4)').show('fast');
      } else {
        // If content is hidden, show the third column and hide the fourth
        $(this).closest('table').find('th:nth-child(3), td:nth-child(3)').show('fast');
        $(this).closest('table').find('th:nth-child(4), td:nth-child(4)').hide('fast');
      }
    });
  }

  // Apply the function to each table and button-content pair
  toggleContent('#second_table', '.btn-slideContent2', '.slideContent2');
  toggleContent('#third_table', '.btn-slideContent3', '.slideContent3');
  toggleContent('#fourth_table', '.btn-slideContent4', '.slideContent4');
  toggleContent('#fifth_table', '.btn-slideContent5', '.slideContent5');
</script>

<!-- progress bar -->
<script>
  // Example: Update progress to 75%
  $(document).ready(function() {
    var newProgress = '75%'; // New progress percentage
    $('.progress-bar-step').css('width', newProgress);
    // Additional code to update status text if needed
  });
</script>

<script>
  $(document).ready(function() {
    //ToolTip
    $('[data-toggle="tooltip"]').tooltip();
    // ===================================
    // ========Outgoing/Incoming==========
    // ===================================

    // =========Select All Checkbox=======
    // Select all checkboxes when the "selectAll" checkbox is clicked
    $("#clr-dg-select-all-clr-id-643").change(function() {
      $(".select-checkbox").prop("checked", $(this).prop("checked"));
    });

    // Deselect the "selectAll" checkbox if any individual checkbox is unchecked
    $(".select-checkbox").change(function() {
      if (!$(this).prop("checked")) {
        $("#clr-dg-select-all-clr-id-643").prop("checked", false);
      }
    });

    // Show/hide warning alert based on the "Power Off" state
    $(".select-checkbox").change(function() {
      if ($(this).prop("checked") && $(this).closest("tr").find("td:eq(5)").text().trim() === "Power Off") {
        showWarningAlert();
      } else {
        hideWarningAlert();
      }
    });

    function showWarningAlert() {
      $(".alert-warning-custom1").show();
    }

    function hideWarningAlert() {
      $(".alert-warning-custom1").hide();
    }

    function toggleWarningAlert() {
      if ($(".select-checkbox:checked").closest("tr").find("td:eq(5):contains('Power Off')").length > 0) {
        showWarningAlert();
      } else {
        hideWarningAlert();
      }
    }
    // =========Select All Checkbox End=======
    // =========Select One Radio=======
    // Event handler for radio button click

    // Event handler for radio button click in tables with class 'radio-table'
    $('.radio-table1 input[type="radio"]').on('click', function() {
      // Uncheck all other radio buttons in the same table
      $(this).closest('table').find('input[type="radio"]').not(this).prop('checked', false);
    });

    $('.radio-table2 input[type="radio"]').on('click', function() {
      // Uncheck all other radio buttons in the same table
      $(this).closest('table').find('input[type="radio"]').not(this).prop('checked', false);
    });
    // =========Select One Radio End=======

    //slide content
    $('.toggle-detail').on('click', function() {
      $('#detail-pane').toggleClass('active');
      $('.slideContent').toggleClass('slide-right');
    });

    //select column
    // Load saved column states
    loadColumnStates();

    $('#toggle-columns-btn').click(function() {
      $('#column-toggles').toggle();
    });

    $('.column-toggle-checkbox').change(function() {
      var columnClass = $(this).attr('id').replace('toggle-', '');
      var column = $('.' + columnClass);
      $(this).is(':checked') ? column.fadeIn() : column.fadeOut();
      saveColumnState($(this).attr('id'), $(this).is(':checked'));
    });

    $('#select-all').click(function() {
      $('.column-toggle-checkbox').prop('checked', true).change();
    });

    $('#deselect-all').click(function() {
      $('.column-toggle-checkbox').prop('checked', false).change();
    });

    $('#reset-columns').click(function() {
      $('.column-toggle-checkbox').prop('checked', true).change();
      resetColumnStates();
    });

    function saveColumnState(columnId, state) {
      if (typeof(Storage) !== 'undefined') {
        localStorage.setItem(columnId, state);
      }
    }

    function loadColumnStates() {
      $('.column-toggle-checkbox').each(function() {
        var state = localStorage.getItem($(this).attr('id'));
        if (state !== null) {
          $(this).prop('checked', state === 'true').change();
        }
      });
    }

    function resetColumnStates() {
      $('.column-toggle-checkbox').each(function() {
        localStorage.removeItem($(this).attr('id'));
      });
    }

    // select 2
    $('#clr-form-control-161').select2();
    $('#clr-form-control-161').on('select2:select', function(e) {
      if (e.params.data.id === 'clr-option-clr-id-6') {
        $('#clr-form-control-161').val(['clr-option-clr-id-6']).trigger('change');
      } else {
        updateBadge(e.params.data.id, e.params.data.text);
        $('#clr-form-control-161').val($('#clr-form-control-161').val().filter(val => val !== 'clr-option-clr-id-6')).trigger('change');
      }
    });
    $(document).on('click', '.select2-selection__choice__remove', function() {
      var value = $(this).parent().data('value');
      updateBadge(value, '');
      if ($('#clr-form-control-161').val() && $('#clr-form-control-161').val().length === 0) {
        $('#clr-form-control-161').val(['clr-option-clr-id-6']).trigger('change');
      }
    });

    function updateBadge(value, text) {
      // Your implementation to update badges goes here
    }
  });
</script>