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

<style>
.notification_btn_steps {
    border-radius: 15px;
    padding: 2px 16px;
    margin-bottom: 10px;
    font-size: 10px;
    font-weight: 400;
    color: #fff;
    background: #508ff4;
}
#checkboxContainer{
  display: flex;
  flex-wrap: wrap;
}
.form-checkes {
      display: flex;
      justify-content: center;
      background-color: #fff;
      border-radius: 10%;
      border: 3px solid #14cfc8; /* Align items vertically in the center */
      margin-right: 20px; /* Adjust the margin to provide space between checkboxes */
      margin-top: 10px;
      overflow: hidden;
    }
.form-checkes label {
      align-self: center;
      padding: 10px;
      cursor: pointer;
      display: inline;
      white-space: normal;
      max-height: 2em;
      /* overflow: hidden;  */
    }
.form-checkes input[type="checkbox"] {
      height: 20px;
      width: 20px;
      border-radius: 50%;
      border: 2px solid #14cfc8;
      align-self: center;
      margin-right: 5px;
      visibility: hidden;
      display: none;
      
    }
.form-checkes:has(input:checked){
  background-color: #14cfc8;
  color: #fff;
}

#mainArticleContainer{
  display: flex;
  flex-wrap: wrap;
}
#checkboxContainer2{
  display: flex;
  flex-wrap: wrap;
}
#operatorcolumncheckbox{
  display: flex;
  flex-wrap: wrap;
}
#operatorcheckboxContainer{
  display: flex;
  flex-wrap: wrap;
}
</style>
<section class="main_content dashboard_part default_content">

    <div class="container-fluid">
        <div class="col">
          <h2>Select require article you want data</h2>
          <div id="checkboxContainer2"></div>
                


                <h2 style="margin-top: 20px;">Select require article column</h2>
                  <div id="checkboxContainer"></div>
                 
                
                

                <button style="margin-top: 20px;" class="status_btn" id="generateReport">Click here to generate report</button>

                <h2 style="margin-top: 20px;">Generate production report</h2>
                <div class="row">
                  <div class="col-5">
                    <div id="checkboxContainer3"></div>
                  </div>
                  <div class="col-2">
                    <div class="" style="background-color: #000;height: 100%;width: 0.5%;border-radius: 1%;"></div>
                  </div>
                  <div class="col-5">
                    <input type="date" id="birthday" name="birthday">
                  </div>
                  
                  
                </div>

                <div class="row">
                  <div class="col-12">
                    <div class="d-flex justify-content-center align-items-center">
                      <button style="margin-top: 20px;" class="status_btn" id="generateReports">Generate report</button>
                    </div>
                  </div>
                </div>
                

                
                
                
                <!-- <div style="display: inline-block;">
                  <div style="display: inline-block;"  id="checkboxContainer3"></div>
                <div style="display: inline-block;background-color: #000;height: 80px;width: 2px;"></div>
                <input style="display: inline-block;" type="date" id="birthday" name="birthday">
                
                </div> -->
                
                

                <h2 style="margin-top: 20px;">Select require Operator</h2>
                <div id="operatorcheckboxContainer"></div>

                <h2 style="margin-top: 20px;">Select require operator column</h2>
                <div id="operatorcolumncheckbox"></div>

                <a style="margin-top: 20px;" class="status_btn" id="op_generate_report">Generate report</a>

                <h2 style="margin-top: 20px;">Select require operator wages report</h2>
                <div class="row">
                  <div class="col-5">
                    <input type="radio" id="Monthly" name="op_report" value="Monthly">
                <label for="Monthly">Monthly</label><br>
                <input type="radio" id="Weekly" name="op_report" value="Weekly">
                <label for="Weekly">Weekly</label><br>
                  </div>
                  <div class="col-2">
                    <div style="background-color: #000;width: 1%;height: 100%;"></div>
                  </div>
                  <div class="col-5">
                    <label for="start_date">Start date</label>
                    <input type="date" id="start_date" name="start_date">
                    <br>
                    <label for="end_date">End date</label>
                <input type="date" id="end_date" name="start_date">
                  </div>
                </div>
                
                
                <a style="margin-top: 20px;" class="status_btn" id="op_generateReports">Generate report</a>
        </div>
        
    </div>

</section>

<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 type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/vfs_fonts.js"></script>

<script>

// Get the anchor element by its ID
var generateReportLink = document.getElementById('generateReport');

var op_generateReports = document.getElementById('op_generateReports');

var operatorID = []

var op_generate = document.getElementById('op_generate_report');

op_generate.addEventListener('click',function(){
  filterOperators();
})

function filterOperators() {
      // Get all checkboxes
      var checkboxes = document.querySelectorAll('input[type="checkbox"]');

// Array to store checked checkboxes
var checkedCheckboxes = [];
var articleCheckboxes = [];
var id = '';
// Iterate through checkboxes and check their status
checkboxes.forEach(function(checkbox) {
    id =  checkbox.id.split(")")
    console.log(id);
    if (id[1] === "OperatorID") {
        if (checkbox.checked) {
            articleCheckboxes.push(id[0]);
    }
    }
    if (id[1] === "OperatorColumn") {
        if (checkbox.checked) {
        checkedCheckboxes.push(id[0]);
    }
    }
    
});

var data ={
    "articleColumn":articleCheckboxes,
    "articleData":checkedCheckboxes
}
// Log the IDs of checked checkboxes
console.log('Checked Checkboxes:', data);
var serializedData = JSON.stringify(data);
var csrftoken = '{{ csrf_token }}';
$.ajax({
    url: '{% url "filterOperatorData" %}',
    method: 'POST',
    data: serializedData,
    contentType: 'application/json',
    beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
    },
    success: function(response) {
        // Handle NaN values in the "wage" field
        response.get_data.forEach(item => {
            item.wage = isNaN(item.wage) ? 0 : item.wage;
        });

        // Log the updated response
        console.log(response);

        // Now you can continue processing the response or call other functions
        createPdfs(response.get_data, Object.keys(response.get_data[0]).length);
    },
    error: function(e) {
        console.log('Error occurred while fetching the updated data.', e);
    }
});
}

function createPdfs(response,get_width) {
    console.log("inside create pdf");
    var width = []
    var articleTableHeadings = [];
    for (let index = 0; index < get_width; index++) {
        if (index === 0) {
            width.push('auto')
        }
        else{
            width.push("*")
        }
    }

    console.log(width);
    for (var key in response[0]){
        articleTableHeadings.push(key);
    }
    console.log(articleTableHeadings);
    var articleTableData = [articleTableHeadings];
    
    for (let index = 0; index < response.length; index++) {
        var rowData = [];
        for (let i = 0; i < articleTableHeadings.length; i++) {
            
            rowData.push(response[index][articleTableHeadings[i]]);
                articleTableData.push(rowData);
            
        }
    }
    console.log(articleTableData);

    var uniqueArray = [];

for (var i = 0; i < articleTableData.length; i++) {
  var currentRow = articleTableData[i];

  // Check if the current row is not already in the uniqueArray
  if (!uniqueArray.some(row => areArraysEqual(row, currentRow))) {
    uniqueArray.push(currentRow);
  }
}

console.log(uniqueArray);

var articleTTable = {
  table: {
    headerRows: 1,
    widths: width, 
    body: uniqueArray, 
    style:"tableStyle"
  },
  layout: 'lightHorizontalLines',
};

var docDefinition = {
  pageOrientation: 'portrait', // or 'landscape' as needed
  pageSize: 'A4', // or 'auto' for responsive size
  header: function(currentPage, pageCount, pageSize) {
    return  [
    // {
    //   image: reqImg,
    //   width: 100,
    //   margin: [0, 10],
    //   alignment:'center'
    // },
      {
        text: 'Things Access',
        alignment: 'center',
        margin: [0, 10],
        fontSize: 14, // Font size for the header
        style:'companyName'
      },
    ];
  },
  

  footer: function(currentPage, pageCount, pageSize) {
    return {
      // Footer content
      text: 'Page ' + currentPage + ' of ' + pageCount,
      alignment: 'center',
    };
  },
  content: [
  {
      image: 'data:image/png;base64, ',
      width: 100,
      margin: [0, 10],
      alignment:'center'
    },
    { text: 'Article info', style: 'header' }, // Add the first header
    articleTTable
  ],
 
  styles: {
    header: {
      fontSize: 12,
      bold: true,
      alignment: 'center',
      margin: [0, 10, 0, 10],
    },
    companyName:{
      fontSize:16,
      bold:true,
      alignment:'center',
      margin: [0, 20, 0, 0],
    },
    tableHeader:{
      background:"#9d0a0e"
    }
  },
};
pdfMake.createPdf(docDefinition).open();
   }

op_generateReports.addEventListener('click', function() {

  var startDate = document.getElementById('start_date');
  var endDate = document.getElementById('end_date');

  var checkboxes = document.querySelectorAll('input[type="checkbox"]');
  var radiobutton = document.querySelectorAll('input[type="radio"]');

  var type = "date";

  radiobutton.forEach(function(radio) {
    if (radio.checked) {
      console.log(radio.value);
      type = radio.value
    }
  })
  checkboxes.forEach(function(checkbox) {
    console.log('opVal',checkbox.value);
    if (checkbox.checked) {
      console.log('opcheck',checkbox.value);
      console.log(checkbox.id.split(")"));
      if (checkbox.id.split(')')[1] === "OperatorID") {
        operatorID.push({"ID":checkbox.id.split(")")[0]});
      }
      
    }

    
    
  })
  console.log('reportType',type);
  console.log(startDate.value);
  console.log(endDate.value);
  console.log("operatorID",operatorID);
  GetOperatorWages(operatorID,type,startDate.value,endDate.value);
  operatorID.length = 0

})

function GetOperatorWages(id,options,start_date,end_date) {
  var MachineState =  {
        id :id,
        reportType:options,
        start_date:start_date,
        end_date:end_date
      }
    var serializedData = JSON.stringify(MachineState);

    var csrftoken = '{{ csrf_token }}';
    $.ajax({
      url: '{% url "Get_operators_report" %}',
      method: 'POST',
      data: serializedData,
      contentType: 'application/json',
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      },
      success: function(response) {
        console.log(response)
        console.log(Object.keys(response.data_skill[0]).length);
        var completeBundles = []
        var operatorWage = []
        for (let i = 0; i < response.data_skill.length; i++) {
          operatorWage.push({"Name":response.data_skill[i].operator_name,"Wage":response.data_skill[i].operator_wage,
          "Total Earning":response.data_skill[i].total_earnings,"Total Production":response.data_skill[i].total_production,"Total Time(min)":response.data_skill[i].total_time_in_minutes})
          if (response.data_skill[i].completed_bundles.length>0) {
            for (let j = 0; j < response.data_skill[i].completed_bundles.length; j++) {
            completeBundles.push({"id":j+1,'Name':response.data_skill[i].operator_name,
            'bundle_id':response.data_skill[i].completed_bundles[j].bundle_ID,
            'startTime':response.data_skill[i].completed_bundles[j].startTime,
            'endTime':response.data_skill[i].completed_bundles[j].endTime,
            'total\nDuration':response.data_skill[i].completed_bundles[j].duration_in_minutes,
          })
          }
          }
          
          
        }
        // callFunction()
        if (completeBundles.length>0) {
          callFunction(operatorWage,Object.keys(operatorWage[0]).length,"op",Object.keys(completeBundles[0]),completeBundles)
        }
        else{
          callFunction(operatorWage,Object.keys(operatorWage[0]).length,"op",[],completeBundles)
        }
        
    },
      error: function() {
        console.log('Error occurred while fetching the updated data.');
      }
    });
}
// Add a click event listener
generateReportLink.addEventListener('click', function() {
    // Your code to generate the report goes here

    // Get all checkboxes
    var checkboxes = document.querySelectorAll('input[type="checkbox"]');

    // Array to store checked checkboxes
    var checkedCheckboxes = [];
    var articleCheckboxes = [];
    var id = '';
    // Iterate through checkboxes and check their status
    checkboxes.forEach(function(checkbox) {
        id =  checkbox.id.split(")")
        console.log(id);
        if (id[1] === "Article") {
            if (checkbox.checked) {
                articleCheckboxes.push(id[0]);
        }
        }
        if (id[1] === "Column") {
            if (checkbox.checked) {
            checkedCheckboxes.push(id[0]);
        }
        }
        
    });

    var data ={
        "articleColumn":articleCheckboxes,
        "articleData":checkedCheckboxes
    }
    // Log the IDs of checked checkboxes
    console.log('Checked Checkboxes:', checkedCheckboxes);
    var serializedData = JSON.stringify(data);
    var csrftoken = '{{ csrf_token }}';
    $.ajax({
      url: '{% url "filterArticleData" %}',
      method: 'POST',
      data: serializedData,
      contentType: 'application/json',
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      },
      success: function(response) {
        console.log(Object.keys(response.get_data[0]).length);
        createPdf(response.get_data,Object.keys(response.get_data[0]).length)
    },
      error: function() {
        console.log('Error occurred while fetching the updated data.');
      }
    });

    function createPdf(response,get_width) {
    console.log("inside create pdf");
    var width = []
    var articleTableHeadings = [];
    var matchedKay = [];
    for (let index = 0; index < get_width; index++) {
        if (index === 0) {
            width.push('auto')
        }
        else{
            width.push("*")
        }
    }

    console.log(width);
    for (var key in response[0]){
      if (key === "article_id"){
        articleTableHeadings.push("ID");
      }
      else if (key === "article_name"){
        articleTableHeadings.push("Name");
      }
      else if (key === "total_production"){
        articleTableHeadings.push("Total\nproduction");
      }
      else if (key === "today_production"){
        articleTableHeadings.push("Today\nproduction");
      }
      else if (key === "yesterday_production"){
        articleTableHeadings.push("Yesterday\nproduction");
      }
      else if (key === "day_before_yesterday_production"){
        articleTableHeadings.push("Before Yesterday\nproduction");
      }
      matchedKay.push(key)
        
    }
    console.log(articleTableHeadings);
    var articleTableData = [articleTableHeadings];
    
    for (let index = 0; index < response.length; index++) {
        var rowData = [];
        for (let i = 0; i < matchedKay.length; i++) {
            
            rowData.push(response[index][matchedKay[i]]);
                articleTableData.push(rowData);
            
        }
    }
    console.log(articleTableData);

    var uniqueArray = [];

for (var i = 0; i < articleTableData.length; i++) {
  var currentRow = articleTableData[i];

  // Check if the current row is not already in the uniqueArray
  if (!uniqueArray.some(row => areArraysEqual(row, currentRow))) {
    uniqueArray.push(currentRow);
  }
}

console.log(uniqueArray);

var articleTTable = {
  table: {
    headerRows: 1,
    widths: width, 
    body: uniqueArray, 
    style:"tableStyle"
  },
  layout: 'lightHorizontalLines',
};

var docDefinition = {
  pageOrientation: 'portrait', // or 'landscape' as needed
  pageSize: 'A4', // or 'auto' for responsive size
  header: function(currentPage, pageCount, pageSize) {
    return  [
    // {
    //   image: reqImg,
    //   width: 100,
    //   margin: [0, 10],
    //   alignment:'center'
    // },
      {
        text: 'Things Access',
        alignment: 'center',
        margin: [0, 10],
        fontSize: 14, // Font size for the header
        style:'companyName'
      },
    ];
  },
  

  footer: function(currentPage, pageCount, pageSize) {
    return {
      // Footer content
      text: 'Page ' + currentPage + ' of ' + pageCount,
      alignment: 'center',
    };
  },
  content: [
  {
      image: 'data:image/png;base64, ',
      width: 100,
      margin: [0, 10],
      alignment:'center'
    },
    { text: 'Article info', style: 'header' }, // Add the first header
    articleTTable
  ],
 
  styles: {
    header: {
      fontSize: 12,
      bold: true,
      alignment: 'center',
      margin: [0, 10, 0, 10],
    },
    companyName:{
      fontSize:16,
      bold:true,
      alignment:'center',
      margin: [0, 20, 0, 0],
    },
    tableHeader:{
      background:"#9d0a0e"
    }
  },
};
pdfMake.createPdf(docDefinition).open();
   }


});

function areArraysEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }

  for (var i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) {
      return false;
    }
  }

  return true;
}

    var artcleInfo = JSON.parse(decodeHTMLEntities("{{ request.session.articleinfo|safe }}").replace(/'([^']+)'/g, '"$1"'));

    console.log(artcleInfo);

    var operatorsInfo = JSON.parse(("{{ request.session.operatorsInfo|safe }}").replace(/'([^']+)'/g, '"$1"').replace(/None/g, null));

    console.log(operatorsInfo);
    var opratorName =[]
    for (let i = 0; i < operatorsInfo.length; i++) {

      opratorName.push({"id":operatorsInfo[i]["operator_data"]["id"],"name":operatorsInfo[i]["operator_data"]["name"]})
      
    }

    console.log(opratorName);

    opratorName.forEach(function(element){
  // Create a checkbox element
  var checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        checkbox.id = element.id + ")OperatorID"; // Use a unique ID for each checkbox

        // Create a label element
        var label = document.createElement("label");
        label.htmlFor = checkbox.id; // Set the 'for' attribute to match the checkbox ID
        label.appendChild(document.createTextNode(element.name)); // Set the label text

        var formCheck = document.createElement('div');
        formCheck.className = 'form-checkes';

        // Append the checkbox and label to the container element
        var container = document.getElementById('operatorcheckboxContainer'); // Adjust the container ID based on your HTML structure
        // container.appendChild(checkbox);
        // container.appendChild(label);
        formCheck.appendChild(checkbox);
        formCheck.appendChild(label);

        // Add a line break for better spacing
        // container.appendChild(document.createElement("br"));
        formCheck.appendChild(document.createElement("br"));
        container.appendChild(formCheck);
})

    var operatorsLists = [];

// Iterate over the keys in "operator_data"
for (var key in operatorsInfo[0]["operator_data"]) {
  if (operatorsInfo[0]["operator_data"].hasOwnProperty(key)) {
    if (key !="id") {
      console.log(key);
      operatorsLists.push(key)
    }
    
  }
}

console.log(operatorsLists);

operatorsLists.forEach(function(element){
  // Create a checkbox element
  var checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        checkbox.id = element + ")OperatorColumn"; // Use a unique ID for each checkbox

        // Create a label element
        var label = document.createElement("label");
        label.htmlFor = checkbox.id; // Set the 'for' attribute to match the checkbox ID
        label.appendChild(document.createTextNode(element)); // Set the label text

        var formCheck = document.createElement('div');
        formCheck.className = 'form-checkes';

        // Append the checkbox and label to the container element
        var container = document.getElementById('operatorcolumncheckbox'); // Adjust the container ID based on your HTML structure
        // container.appendChild(checkbox);
        // container.appendChild(label);
        formCheck.appendChild(checkbox);
        formCheck.appendChild(label);

        // Add a line break for better spacing
        // container.appendChild(document.createElement("br"));
        formCheck.appendChild(document.createElement("br"));
        container.appendChild(formCheck)
})
    function decodeHTMLEntities(text) {
  var textarea = document.createElement('textarea');
  textarea.innerHTML = text;
  return textarea.value;
}
var artileList = [];
   for (articles in artcleInfo) {

    console.log(artcleInfo[articles]);

    for (articlesData in artcleInfo[articles]) {
      if (articlesData!="article_id") {
        artileList.push(articlesData);
        console.log(articlesData);
      }
        
    }
    
   }
   console.log(artileList);
   var uniqueArr = artileList.filter((value, index, self) => {
    return self.indexOf(value) === index;
});

console.log(uniqueArr);

var birthdayInput = document.getElementById('birthday');
    // Create checkboxes for each element in the array
    uniqueArr.forEach(function(element) {
        // Create a checkbox element
        var formCheck = document.createElement('div');
        formCheck.className = 'form-checkes';
        var checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        checkbox.id = element + ")Column"; // Use a unique ID for each checkbox

        // Create a label element
        var label = document.createElement("label");
        label.htmlFor = checkbox.id; // Set the 'for' attribute to match the checkbox ID
        label.appendChild(document.createTextNode(element)); // Set the label text

        // Append the checkbox and label to the container element
        var container = document.getElementById('checkboxContainer'); // Adjust the container ID based on your HTML structure
        formCheck.append(checkbox);
        formCheck.append(label);
        // container.appendChild(checkbox);
        // container.appendChild(label);

        // Add a line break for better spacing
        formCheck.appendChild(document.createElement("br"));
        formCheck.appendChild(document.createElement("br"));
        container.append(formCheck);
        // container.appendChild(document.createElement("br"));
    });

     // Create checkboxes for each element in the array
     artcleInfo.forEach(function(element) {
        // Create a checkbox element
        var checkbox = document.createElement("input");
        var formCheck = document.createElement('div');
        formCheck.className = 'form-checkes';
        checkbox.type = "checkbox";
        checkbox.id = element.article_name + ")Article"; // Use a unique ID for each checkbox

        // Create a label element
        var label = document.createElement("label");
        label.htmlFor = checkbox.id; // Set the 'for' attribute to match the checkbox ID
        label.appendChild(document.createTextNode(element.article_name)); // Set the label text

        // Append the checkbox and label to the container element
        var container = document.getElementById('checkboxContainer2'); // Adjust the container ID based on your HTML structure
        // container.appendChild(checkbox);
        // container.appendChild(label);

        formCheck.append(checkbox);
        formCheck.append(label)

        // Add a line break for better spacing
        // container.appendChild(document.createElement("br"));
        container.append(formCheck);
    });

    var productReportList = ['weekly','monthly'];

    

    for (let i = 0; i < productReportList.length; i++) {

      var containers = document.getElementById('checkboxContainer3');
      var label = document.createElement("label");
      label.htmlFor = productReportList[i]; // Set the 'for' attribute to match the checkbox ID
      label.appendChild(document.createTextNode(productReportList[i])); // Set the label text
      var checkbox = document.createElement("input");
        checkbox.type = "radio";
        checkbox.name = ")production";
        checkbox.id = productReportList[i]+")production"
        containers.appendChild(checkbox);
      containers.appendChild(label);
      // Add a line break for better spacing
      containers.appendChild(document.createElement("br"));
      
    }

    var generateProductionReportLink = document.getElementById('generateReports');


    generateProductionReportLink.addEventListener('click',function () {
       // Get all checkboxes
    var radioboxes = document.querySelectorAll('input[type="radio"]');
    var checkboxes = document.querySelectorAll('input[type="checkbox"]');
    console.log("productionCheck",checkboxes);

    var options = ""
    radioboxes.forEach(function(radio) {
        var id =  radio.id.split(")")
        
        if (radio.checked) {
          console.log("radios",id);
          options = id[0]
        }
        
    });

    console.log("options",options);
    var article_ids = []
    checkboxes.forEach(function(checkbox) {
      var id = checkbox.id.split(")");
      console.log(id);
      if (checkbox.checked) {
        if (id[1]==="Article") {
          console.log("artcleInfo",artcleInfo);
          for (let i = 0; i < artcleInfo.length; i++) {

            if (artcleInfo[i].article_name === id[0]) {
              article_ids.push({"ID":artcleInfo[i].article_id})
            }
            
          }
          
        }
      }
    })

    console.log(article_ids);

    var selectedDate = birthdayInput.value;
    console.log(selectedDate);
    
    if (selectedDate!="") {
      getproductionreport(article_ids,null,selectedDate)
      radioboxes.forEach(function(radio) {
        radio.checked = false
      })
    }
    else{
      getproductionreport(article_ids,options,null)
    }

    


    })

    

    function getproductionreport(id,options,date) {
    // Perform an AJAX request to fetch the updated data from the server
    var MachineState =  {
        id :id,
        reportType:options,
        date:null
      }
    var serializedData = JSON.stringify(MachineState);

    var csrftoken = '{{ csrf_token }}';
    $.ajax({
      url: '{% url "Get_production_report" %}',
      method: 'POST',
      data: serializedData,
      contentType: 'application/json',
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      },
      success: function(response) {
        var completeBundle = [] 
        console.log(response)
        console.log(Object.keys(response.data_skill[0]).length);
       
        // callFunction()
        callFunction(response.data_skill,Object.keys(response.data_skill[0]).length,"p",[],[])
    },
      error: function() {
        console.log('Error occurred while fetching the updated data.');
      }
    });
  }



  function callFunction(response,get_width,check,get_tableTwo_width,tableTwo) {
    var width = []
    var tabletwoWidth=[]
    var articleTableHeadings = [];
    console.log("get_tableTwo_width",get_tableTwo_width);
    console.log("tableTwo",tableTwo);
    if (check === "op") {
      for (let index = 0; index < get_width; index++) {
        if (index === 0) {
            width.push('auto')
        }
        else{
            width.push("*")
        }
    }

    for (let index = 0; index < get_tableTwo_width.length; index++) {
        if (index === 0) {
          tabletwoWidth.push('auto')
        }
        else{
          tabletwoWidth.push("*")
        }
    }
    // var tableTwoKey = []
    // for (key in tableTwo ) {
    //   console.log(key);
    //   tableTwoKey.push(key);
      
    // }

    console.log(tabletwoWidth);

    var bundlesDetailsDatass = [get_tableTwo_width];

    for (let j = 0; j < tableTwo.length; j++) {
      var rowData = []
      for (let i = 0; i < get_tableTwo_width.length; i++) {
            
            rowData.push(tableTwo[j][get_tableTwo_width[i]]);
            if (rowData.length>0) {
              bundlesDetailsDatass.push(rowData);
            }
            
            
        }
    }

    console.log("bundlesDetailsDatass",bundlesDetailsDatass);

    console.log(width);
    for (var key in response[0]){
      if(key!="completed_bundles"){
        articleTableHeadings.push(key);
      }
        
    }
    console.log(articleTableHeadings);
    var articleTableData = [articleTableHeadings];
    
    for (let index = 0; index < response.length; index++) {
        var rowData = [];
        for (let i = 0; i < articleTableHeadings.length; i++) {
            
            rowData.push(response[index][articleTableHeadings[i]]);
                articleTableData.push(rowData);
            
        }
    }
    console.log(articleTableData);

    var uniquebundlesData = [];
    //bundlesDetailsDatass

    for (let j = 0; j < bundlesDetailsDatass.length; j++) {
      var currentRow = bundlesDetailsDatass[j]
      if (!uniquebundlesData.some(row => areArraysEqual(row, currentRow))) {
        uniquebundlesData.push(currentRow);
  }
    }

    var uniqueArray = [];

for (var i = 0; i < articleTableData.length; i++) {
  var currentRow = articleTableData[i];

  // Check if the current row is not already in the uniqueArray
  if (!uniqueArray.some(row => areArraysEqual(row, currentRow))) {
    uniqueArray.push(currentRow);
  }
}

console.log(uniqueArray);

var articleTTable = {
  table: {
    headerRows: 1,
    widths: width, 
    body: uniqueArray, 
    style:"tableStyle"
  },
  layout: 'lightHorizontalLines',
};

var bdTable = {
  table: {
    headerRows: 1,
    widths: tabletwoWidth, 
    body: uniquebundlesData, 
    style:"tableStyle",
  },
  layout: 'lightHorizontalLines',
};

var docDefinition = {
  pageOrientation: 'portrait', // or 'landscape' as needed
  pageSize: 'A4', // or 'auto' for responsive size
  header: function(currentPage, pageCount, pageSize) {
    return  [
    // {
    //   image: reqImg,
    //   width: 100,
    //   margin: [0, 10],
    //   alignment:'center'
    // },
      {
        text: 'Things Access',
        alignment: 'center',
        margin: [0, 10],
        fontSize: 14, // Font size for the header
        style:'companyName'
      },
    ];
  },
  

  footer: function(currentPage, pageCount, pageSize) {
    return {
      // Footer content
      text: 'Page ' + currentPage + ' of ' + pageCount,
      alignment: 'center',
    };
  },
  content: [
  {
      image: 'data:image/png;base64, ',
      width: 100,
      margin: [0, 10],
      alignment:'center'
    },
    { text: 'Operators wages', style: 'header' },
    articleTTable,
    { text: 'Bundle details', style: 'header' }, 
    bdTable
  ],
 
  styles: {
    header: {
      fontSize: 12,
      bold: true,
      alignment: 'center',
      margin: [10, 10, 10, 10],
    },
    companyName:{
      fontSize:16,
      bold:true,
      alignment:'center',
      margin: [0, 20, 0, 0],
    },
    tableHeader:{
      background:"#9d0a0e"
    },
    tableStyle: {
      margin: [0, 10, 0, 10], // Adjust the margins as needed
      fontSize: 7, // Adjust the font size as needed
      // Add any other styling properties you need
    },
  },
};
pdfMake.createPdf(docDefinition).open();
    }
    else{
      for (let index = 0; index < get_width-1; index++) {
        if (index === 0) {
            width.push('auto')
        }
        else{
            width.push("*")
        }
    }

    console.log(width);
    for (var key in response[0]){
      if(key!="ID"){
        articleTableHeadings.push(key);
      }
        
    }
    console.log(articleTableHeadings);
    var articleTableData = [articleTableHeadings];
    
    for (let index = 0; index < response.length; index++) {
        var rowData = [];
        for (let i = 0; i < articleTableHeadings.length; i++) {
            
            rowData.push(response[index][articleTableHeadings[i]]);
                articleTableData.push(rowData);
            
        }
    }
    console.log(articleTableData);

    var uniqueArray = [];

for (var i = 0; i < articleTableData.length; i++) {
  var currentRow = articleTableData[i];

  // Check if the current row is not already in the uniqueArray
  if (!uniqueArray.some(row => areArraysEqual(row, currentRow))) {
    uniqueArray.push(currentRow);
  }
}

console.log(uniqueArray);

var articleTTable = {
  table: {
    headerRows: 1,
    widths: width, 
    body: uniqueArray, 
    style:"tableStyle"
  },
  layout: 'lightHorizontalLines',
};

var docDefinition = {
  pageOrientation: 'portrait', // or 'landscape' as needed
  pageSize: 'A4', // or 'auto' for responsive size
  header: function(currentPage, pageCount, pageSize) {
    return  [
    // {
    //   image: reqImg,
    //   width: 100,
    //   margin: [0, 10],
    //   alignment:'center'
    // },
      {
        text: 'Things Access',
        alignment: 'center',
        margin: [0, 10],
        fontSize: 14, // Font size for the header
        style:'companyName'
      },
    ];
  },
  

  footer: function(currentPage, pageCount, pageSize) {
    return {
      // Footer content
      text: 'Page ' + currentPage + ' of ' + pageCount,
      alignment: 'center',
    };
  },
  content: [
  {
      image: 'data:image/png;base64, ',
      width: 100,
      margin: [0, 10],
      alignment:'center'
    },
    { text: 'Article Production', style: 'header' }, // Add the first header
    articleTTable
  ],
 
  styles: {
    header: {
      fontSize: 12,
      bold: true,
      alignment: 'center',
      margin: [0, 10, 0, 10],
    },
    companyName:{
      fontSize:16,
      bold:true,
      alignment:'center',
      margin: [0, 20, 0, 0],
    },
    tableHeader:{
      background:"#9d0a0e"
    }
  },
};
pdfMake.createPdf(docDefinition).open();
   }
    }



</script>


{% endblock %}
