{% extends 'base/base.html' %}
{% block start %}

<style>
.design-white-box{
    margin: auto;
    background-color: white;
    border-radius: 10px;
    margin-bottom: 12px;
    padding: 18px 10px 20px 20px

}

</style>
<section class="main_content dashboard_part default_content">

<div class="main_content_iner ">
<div class="container-fluid p-0">
<div class="row ">
<div class="col-lg-12">
<div class="single_element">
<div class="quick_activity">
<div class="row">
<div class="col-12">
<div class="quick_activity_wrap">

<div id="totalCard" class="single_quick_activity" style="cursor:pointer">
<div class="count_content">
<p>Total</p>
<h3><span>{{total}}</span> </h3>
</div>
{% comment %} <a href="#" class="notification_btn">Today</a> {% endcomment %}
<!-- <div id="bar1" class="barfiller">
<div class="tipWrap">
<span class="tip"></span>
</div>
<span class="fill" data-percentage="{{total}}"></span>
</div> -->
</div>

<div id="completeCard" class="single_quick_activity" style="cursor:pointer">
<div class="count_content">
<p>Complete</p>
<h3><span>{{complete}}</span> </h3>
</div>
{% comment %} <a href="#" class="notification_btn yellow_btn">This Week</a> {% endcomment %}
<!-- <div id="bar2" class="barfiller" >
<div class="tipWrap">
<span class="tip"></span>
</div>
<span class="fill" data-percentage="{{complete}}"></span>
</div> -->
</div>

<div id="faultyCard"  class="single_quick_activity" style="cursor:pointer">
<div class="count_content">
<p>Faulty</p>
<h3><span>{{faulty}}</span> </h3>
</div>
{% comment %} <a href="#" class="notification_btn green_btn">This Month</a> {% endcomment %}
<!-- <div id="bar3" class="barfiller">
<div class="tipWrap">
<span class="tip"></span>
</div>
<span class="fill" data-percentage="{{faulty}}"></span>
</div> -->
</div>

<div id="progressCard"  class="single_quick_activity" style="cursor:pointer">
<div class="count_content">
<p>Progress</p>
<h3><span>{{progress}}</span></h3>
</div>
{% comment %} <a href="#" class="notification_btn violate_btn">Anual</a> {% endcomment %}
<!-- <div id="bar4" class="barfiller">
<div class="tipWrap">
<span class="tip"></span>
</div>
<span class="fill" data-percentage="{{progress}}"></span>
</div> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>


<div  id="total_category" class="total_category" style="display: none;">
<div class="row design-white-box">
<div class="col-lg-2">

   <div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select Article
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton" style="height:auto;overflow:auto">
{% for article in data_artcile %}
  <a class="dropdown-item" onclick="selectArticle('{{article.ID}}','{{article.title}}')">{{article.title}}</a>
{% endfor %}
</div>
</div>
</div>
<div class="col-lg-4">
<div class="dropdown" >
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton_1" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select Group
</button>
<div class="dropdown-menu group_menu" aria-labelledby="dropdownMenuButton_1" >

{% comment %} <a class="dropdown-item" onclick="selectMachine('{{machine.ID}}','{{machine.title}}')">{{machine.title}}</a> {% endcomment %}
</div>
</div>
</div>
</div>
</div>
</div>





<div class="col-lg-12">
<div class="white_card card_height_100 mb_30 QA_section">
<div class="white_card_header">
<div class="box_header m-0">
<div class="main-title">
<h3 class="m-0">Bundles</h3>
</div>

</div>
</div>

<div class="white_card_body">

<div class="QA_table">


<table class="table pt-0 lms_table_active">
<thead>
<tr>

<th scope="col">ID</th>
<th scope="col">Article</th>
<th scope="col">Group</th>
<th scope="col">Tag ID</th>
<th scope="col">State</th>
<th scope="col">QA State</th>
<th scope="col">Created On</th>
</tr>
</thead>
<tbody>


</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>



</section>


<div id="back-top" style="display: none;">
<a title="Go to Top" href="#">
<i class="ti-angle-up"></i>
</a>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min.js"></script>


<script>
  $(document).ready(function() {
    $('#total_category').show();
});
var article_name;
function selectArticle(id,title) {

    // Create a data object to send to the server
    // Convert the id to an integer4
   
   article_name =  document.getElementById('dropdownMenuButton').textContent = title;


    articleId = parseInt(id, 10);

    // Create a data object to send to the server
    var data = {
        'id': articleId
    };
    //console.log(data);
    // Serialize the data object
    var serializedData = JSON.stringify(data);
    console.log(serializedData);
    
    // Get the CSRF token value from the cookie
    var csrftoken = Cookies.get('csrftoken');
    // Send the serialized data to the server using AJAX
    $.ajax({
      url: '{% url "getgroupbundle" %}',
      method: 'POST',
      data: serializedData,
      contentType: 'application/json',
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      },
      success: function(response) {
        console.log('Received the ID on the server');
        console.log(response);
        var dataGroup = response.data_group; // Assuming the server returns the 'data_steps' in the response
        //console.log(dataGroup,'aqsa');
        // Add an event listener to the "Select Group" button
        document.getElementById('dropdownMenuButton_1').addEventListener('click', function() {
        var dropdownMenu = document.querySelector('.group_menu');
        while (dropdownMenu.length > 0) {
              dropdownMenu[0].remove();
          }
        // Clear existing dropdown items
        dropdownMenu.innerHTML = '';

        // Assuming the response is stored in the 'dataGroup' variable
        for (var i = 0; i < dataGroup.length; i++) {
          var groupinfo = dataGroup[i];
          var dropdownItem = document.createElement('a');
          dropdownItem.className = 'dropdown-item';
          dropdownItem.setAttribute('onclick', "selectGroup('" + groupinfo.id + "', '" + groupinfo.title + "')");
          dropdownItem.textContent = groupinfo.title;
          dropdownMenu.appendChild(dropdownItem);
        }
      });
   
        // Handle the response from the server if needed
      },
      error: function(error) {
        // Handle the error response, e.g., show an error message
        alert('Error submitting the review. Please try again.');
      }
    });

   
  }

function selectGroup(id,title){

    group_id = parseInt(id, 10);
    group_name = title
   
    document.getElementById('dropdownMenuButton_1').textContent = title;

    //console.log(group_id)
    // Create a data object to send to the server
    var data = {
        'id': group_id
    };
    //console.log(data);
    // Serialize the data object
    var serializedData = JSON.stringify(data);
    console.log(serializedData);
    
    // Get the CSRF token value from the cookie
    var csrftoken = Cookies.get('csrftoken');
    // Send the serialized data to the server using AJAX
    $.ajax({
      url: '{% url "getbundlebyGroup" %}',
      method: 'POST',
      data: serializedData,
      contentType: 'application/json',
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      },
      success: function(response) {
        console.log('Received the ID on the server');
        //console.log(response);
         Totalbundle_data = response.bundle_data; // Assuming the server returns the 'data_steps' in the response

         updateBundleOnPage(Totalbundle_data);
        
  
        // Handle the response from the server if needed
      },
      error: function(error) {
        // Handle the error response, e.g., show an error message
        alert('Error submitting the review. Please try again.');
      }
    });

}



$(document).ready(function() {

  // Click event for the 'Total' card
  $('#totalCard').on('click', function() {
    // Update the table data
    console.log('aqsa')
    updateBundleOnPage();
  });

  

  
  // Click event for the 'Complete' card
  $('#completeCard').on('click', function() {
    // Update the table data
   $('#total_category').hide();
    var state = 3;
    updateTableData(state);
  });

  // Click event for the 'Faulty' card
  $('#faultyCard').on('click', function() {
    // Update the table data
   $('#total_category').hide();
    var state = 4;
    updateTableData(state);
  });

  // Click event for the 'Progress' card
  $('#progressCard').on('click', function() {
    // Update the table data
    $('#total_category').hide();
     var state = 2;
    updateTableData(state);
  });

 
  
});

// Function to update the table data based on the selected card
  function updateTableData(state) {
    // Perform an AJAX request to fetch the updated data from the server
    var bundleState =  {
        state :state
      }
    var serializedData = JSON.stringify(bundleState);
    var csrftoken = '{{ csrf_token }}';
    $.ajax({
      url: '{% url "bundleState" %}',
      method: 'POST',
      data: serializedData,
      contentType: 'application/json',
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      },
      success: function(response) {
        //console.log(response.dataBundle)
       

        var table = $('.lms_table_active').DataTable();
        table.clear().draw(); // Clear existing rows in the table
        if ( response.dataBundle == 'No data found'){
             table.clear().draw(); // Clear any existing rows (if any)
             //table.rows.add(['No data found']).draw();
          }
        else {
        // Iterate over the response and add new rows to the DataTable instance
        for (var i = 0; i < response.dataBundle.length; i++) {
          var orderNo = i + 1;
          var row = response.dataBundle[i];
          var newRow = [
            orderNo,
            row.article_title,
            row.group_title,
            row.tag_ID,
            row.state,
            row.qa_states,
            row.created_on
          ];

          table.row.add(newRow);
        }

        // Draw the table with the new data
        table.draw();
        }
    },
      error: function() {
        console.log('Error occurred while fetching the updated data.');
      }
    });
  }


function updateBundleOnPage(Totalbundle_data) {
  $('#total_category').show();
  var table = $('.lms_table_active').DataTable();
  table.clear().draw(); // Clear existing rows in the table

  // Iterate over the response and add new rows to the DataTable instance
  for (var i = 0; i < Totalbundle_data.length; i++) {
    var orderNo = i + 1;
    var row = Totalbundle_data[i];
    var newRow = [
      orderNo,
      row.article_title,
      row.group_title,
      row.tag_ID,
      row.state,
      row.qa_states,
      row.created_on
    ];

    table.row.add(newRow);
  }

  // Draw the table with the new data
  table.draw();
     // Reinitialize DataTable after adding new data

}
     

</script> 




{% endblock %}

