{% 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="total" 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="activeop" class="single_quick_activity" style="cursor:pointer">
<div class="count_content">
<p>Active</p>
<h3><span>{{active_op}}</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="{{active_op}}"></span>
</div> -->
</div>

<!-- <div id="presentop"  class="single_quick_activity" style="cursor:pointer">
<div class="count_content">
<p>Present</p>
<h3><span>{{active_op}}</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="{{present}}"></span>
</div>
</div> -->

<div id="absentop"  class="single_quick_activity" style="cursor:pointer">
<div class="count_content">
<p>Absent</p>
<h3><span>{{absent}}</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="{{absent}}"></span>
</div> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>


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

    <div class="white_card card_height_100 mb_30">
      <div class="white_card_header">
      <div class="box_header m-0">
      <div class="main-title">
      <h5 class="m-0">Today's active operators (hourly)</h5>
      </div>
      <!-- <div class="header_more_tool">
      <div class="dropdown">
      <span class="dropdown-toggle" id="dropdownMenuButton" data-bs-toggle="dropdown">
      <i class="ti-more-alt"></i>
      </span>
      <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
      <a class="dropdown-item" href="#"> <i class="ti-eye"></i> Action</a>
      <a class="dropdown-item" href="#"> <i class="ti-trash"></i> Delete</a>
      <a class="dropdown-item" href="#"> <i class="fas fa-edit"></i> Edit</a>
      <a class="dropdown-item" href="#"> <i class="ti-printer"></i> Print</a>
      <a class="dropdown-item" href="#"> <i class="fa fa-download"></i> Download</a>
      </div>
      </div>
      </div> -->
      </div>
      </div>
      <!-- <div class="d-flex align-items-center justify-content-center">
        <h4>Todays Active Operators</h4>
      </div> -->
      
      <div class="white_card_body pb-0">
      
      <canvas id="OperatorsLineChart" style="height:307px;"></canvas>
      </div>
      </div>
  <!-- <div class="white_card card_height_100 mb_30">
  <div class="white_card_header">
  <div class="box_header m-0">
  <div class="main-title">
  <h3 class="m-0"></h3>
  </div>
  <div class="header_more_tool">
  <div class="dropdown">
  <span class="dropdown-toggle" id="dropdownMenuButton" data-bs-toggle="dropdown">
  <i class="ti-more-alt"></i>
  </span>
  <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
  <a class="dropdown-item" href="#"> <i class="ti-eye"></i> Action</a>
  <a class="dropdown-item" href="#"> <i class="ti-trash"></i> Delete</a>
  <a class="dropdown-item" href="#"> <i class="fas fa-edit"></i> Edit</a>
  <a class="dropdown-item" href="#"> <i class="ti-printer"></i> Print</a>
  <a class="dropdown-item" href="#"> <i class="fa fa-download"></i> Download</a>
  </div>
  </div>
  </div>
  </div>
  </div>
  <div class="white_card_body pb-0">
  <div id="line-chart"> </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">Operator</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">Name</th>
<th scope="col">CNIC</th>
<th scope="col">Cell</th>
<th scope="col">Address</th>
<th scope="col" style="width:144px!important">Skill</th>
<th scope="col">Tag Id</th>
<th scope="col">Timing</th>
<th scope="col">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>
 var data_operator = "{{ operator_info_data }}";
 // Function to decode HTML entities
function decodeHTMLEntities(text) {
        var textarea = document.createElement('textarea');
        textarea.innerHTML = text;
        return textarea.value;
    }

    // Decode the HTML-encoded data
    var decodedData = decodeHTMLEntities(data_operator);

    decodedData = decodedData.replace(/'([^']+)'/g, '"$1"').replace(/None/g, null)

    // var jsondata = JSON.parse(decodedData)
    // var jsonData = JSON.parse(decodedData);
// Replace HTML entities with double quotes
// const jsonText = data_operator.replace(/&#x27;/g, '"');

// // Replace "None" with null
// const jsonStringWithNull = jsonText.replace(/"None"/g, 'null');

// // Parse the updated JSON string
// const jsonArray = JSON.parse(jsonStringWithNull);

// console.log(jsonArray);
const jsonStringWithNull = decodedData.replace(/"timing": None/g, '"timing": null');
const jsonArray = JSON.parse(jsonStringWithNull);
    console.log(jsonArray);
$(document).ready(function() {

   function TotalOperator(jsonArray) {

    // console.log(data_operator);
  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 < jsonArray.length; i++) {
    var orderNo = i + 1;
    var row = jsonArray[i];
    var newRow = [
            i+1,
            row.Name,
            row.cnic,
            row.cell,
            row.address,
            row.skill,
            row.tag_id,
            row.timing,
            row.status,
            row.created_on
    ];

    table.row.add(newRow);
  }

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

}
TotalOperator(jsonArray)
    
  // Click event for the 'Total' card
 $('#total').on('click', function() {
    // Update the table data
    // console.log("total",jsonData);
   TotalOperator(jsonArray);
  });



  // Click event for the 'Complete' card
  $('#activeop').on('click', function() {
    // Update the table data
   
    var operator_state = 1;
    updateTableData(operator_state);
  });

  // Click event for the 'Faulty' card
  $('#presentop').on('click', function() {
    // Update the table data
   
    var operator_state = 2;
    updateTableData(operator_state);
  });

  // Click event for the 'Progress' card
  $('#absentop').on('click', function() {
    // Update the table data
     var operator_state = 3;
    updateTableData(operator_state);
  });

 
  
});



// Function to update the table data based on the selected card
  function updateTableData(operator_state) {
    // Perform an AJAX request to fetch the updated data from the server
    var OperatorState =  {
        operator_state :operator_state
      }
      console.log("params");
    var serializedData = JSON.stringify(OperatorState);
    var csrftoken = '{{ csrf_token }}';
    $.ajax({
      url: '{% url "OperatorState" %}',
      method: 'POST',
      data: serializedData,
      contentType: 'application/json',
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      },
      success: function(response) {
        //console.log(response.dataOperator)
    
        var table = $('.lms_table_active').DataTable();
        table.clear().draw(); // Clear existing rows in the table
        if ( response.dataOperator == 'null'){
             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.dataOperator.length; i++) {
          var orderNo = i + 1;
          var row = response.dataOperator[i];
          var newRow = [
            orderNo,
            row.Name,
            row.cnic,
            row.cell,
            row.address,
            row.skill,
            row.tag_id,
            row.timing,
            row.operator_state,
            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.');
      }
    });
  }



  
  

</script>

<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 src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    var Hourlyarr =[]
    var Activearr =[]
  document.addEventListener('DOMContentLoaded',function () {

    getMachine();

function getMachine() {
    var csrftoken = Cookies.get('csrftoken');
    $.ajax({
      url: '{% url "operatorsHourly" %}',
      method: 'GET',
      contentType: 'application/json',
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      },
      success: function(response) {

        console.log(response);
        if (response.response.length>0) {
          for (let index = 0; index < response.response.length; index++) {
            console.log(response.response[index].hour_slot);
            Hourlyarr.push(response.response[index].hour_slot.split(' ')[1]);
            Activearr.push(parseInt(response.response[index].active_operators_count))
            
        }

        console.log(response.response[0].hour_slot);
        }
        

        var ctx = document.getElementById('OperatorsLineChart').getContext('2d');
var data = {
  labels: [],
  datasets: [{
    label: 'Counts',
    data: [],
    // backgroundColor: "rgba(30,184,204,255)",
    borderColor: "rgba(30,184,204,255)",
    fill: false,
  },
]
};

// Configure the chart options
var options = {
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: "Active operator", // Change the y-axis label here
        fontStyle: 'bold',
        fontSize:16,
        fontFamily:'comfortaa, cursive',
        fontColor:'#000000'
      },
      ticks: {
        fontColor: '#000000', 
        fontFamily:'comfortaa, cursive',
        callback: function(value) {if (value % 1 === 0) {return value;}}
      }
    }],
    xAxes: [{
      scaleLabel: {
        display: true,
        labelString: "Dates", // Change the x-axis label here
        fontStyle: 'bold',
        fontSize:16,
        fontFamily:'comfortaa, cursive',
        fontColor:'#000000'
      },
      ticks: {
        fontColor: '#000000', 
        fontFamily:'comfortaa, cursive',
      }
    }],
    y: {
      beginAtZero: false,
      stacked: false,
    },
    x: {
      beginAtZero: true,
      stacked: false
    }
  },
};

// Create the chart
var myChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: options
});
        
        

        //  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.');
      }
    });
  }

  console.log(Activearr)
    

  })

 
  
</script>




{% endblock %}

