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

<style>
.machines-cell {

  overflow: hidden; /* Hide the overflow */
  text-overflow: ellipsis; /* Add ellipsis (...) if the content exceeds the box width */
  max-width: 200px; /* Adjust the max-width as per your requirements */
}

.machine-title {
  display: inline; /* Display machine titles inline */
  margin-right: 5px; /* Add some space between machine titles */
}


</style>


<section class="main_content dashboard_part large_header_bg">



<div class="main_content_iner ">
<div class="container-fluid p-0">
<div class="row justify-content-center">



<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">
<h3 class="m-0">Article machines</h3>
</div>
</div>
</div>
<div class="white_card_body">
<div class="QA_section">
<div class="white_box_tittle list_header" style="display: flex;
    justify-content: flex-start;important">
<h4> </h4>

<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:200px;overflow:auto">
{% for article in data_artcile %}
  <a class="dropdown-item" onclick="selectArticle('{{article.ID}}','{{article.title}}')">{{article.title}}</a>
{% endfor %}
</div>
</div>

<div class="dropdown" style="margin-left:39px">
<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" >

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


   
<div class="add_button ms-2">

</div>
</div>
</div>
<div class="QA_table mb_30">

<table class="table lms_table_active table-striped">
<thead>
<tr>

<th scope="col"></th>
<th scope="col">ID</th>
{% comment %} <th scope="col">Des ID</th>  {% endcomment %}
<th scope="col">Title</th>
<th scope="col">Description</th>
<th scope="col">Selected Machines</th>
<th scope="col">Assigned Machines</th>
<th scope="col">Add Machines</th>
{% comment %} <th scope="col">View machine</th> {% endcomment %}

</tr>
</thead>
<tbody id="steps-container" style="cursor:pointer">
 

</tbody>
</table>
</div>
<button type="button" id="addMachineBundleBtn" class="btn btn-primary" style="float:right">Add Machine Bundle</button>
</div>
</div>
</div>
</div>
<div class="col-12">
</div>
</div>
</div>
</div>


<div class="footer_part">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="footer_iner text-center">
</div>
</div>
</div>
</div>
</div>
</section>


<div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content p-4">

<div id="groupContainer">
<div class="col-lg-12">
<div class="card_box box_shadow position-relative mb_30 " >
<div class="white_box_tittle " style="padding:12px!important">
<div class="main-title2">
<h4 class="mb-2 nowrap" style="margin:10px">Add Machine </h4>
<span id="modalArticleName" style="font-size: 10px;
    margin-left: 10px;"></span>
</div>
</div>
<div class="box_body">

<div class="row mb-3">
<div class="col-md-5">
<div class="email-sidebar" style="height: 250px; overflow-y: auto;">
  <div class="machine-style">Unassigned Machines</div>
   
  {% for unassign_machine in unassigned_machine %}
   <div class="form-check">
      <input class="form-check-input check-step" type="checkbox" id="{{unassign_machine.ID}}" name="{{unassign_machine.ID}}" value="{{unassign_machine.title}}"  data-concatenated-value="{{unassign_machine.step_title}}">
      <label class="form-check-label" for="cutting-checkbox" style="font-size:12px;">{{unassign_machine.title}}</label>
    </div>
    {% endfor %}
  <div class="machine-style">Assigned Machines</div>
   
  {% for assign_machine in assigned_machine %}
   <div class="form-check">
      <input class="form-check-input check-step" type="checkbox" id="{{assign_machine.machine_id}}" name="{{assign_machine.id}}" value="{{assign_machine.title}}" data-concatenated-value="{{assign_machine.article_title}} / {{assign_machine.group_title}} /  {{assign_machine.step_title}} / {{assign_machine.title}} ">
      <label class="form-check-label" for="cutting-checkbox" style="font-size:12px;">{{assign_machine.title}} / {{assign_machine.article_title}} / {{assign_machine.group_title}} /  {{assign_machine.step_title}}</label>
    </div>
    {% endfor %}

    
</div>
</div>


<div class="col-md-7">
<div class="email-sidebar"  style="height: 250px; overflow-y: auto;">
<p>Selected Machine</p>
<ul class="text-start mt-2 selected-machine">
</ul>
</div>
</div>

</div>
<p id="checkedCount">Checked : 0</p> 
</div>

<!-- !-- Hidden input field for description_id --> 
  <input type="hidden" id="modal-description-id" value="">
  <input type="hidden" id="modal-order-id" value="">
  
</div>

<div class="modal-footer">

<button type="button" class="btn btn-primary" id="saveChangesBtn">Add Machine</button>
</div>
</div>
</div>




<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.6.0.min.js"></script>
<script src="https://unpkg.com/sortablejs@1.13.0/Sortable.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min.js"></script>

<script>

  var articleId;
  var group_id;
  var dataSteps;
  var article_name;
  var group_name;
  var selectedMachines = [];
  var machinesHtml = '';
  

  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 "getStepsbyGroup" %}',
      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);
         dataSteps = response.step_data; // Assuming the server returns the 'data_steps' in the response
        //console.log(dataSteps);
        updateStepsOnPage(dataSteps);
        
  
        // 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.');
      }
    });

}

var machinesdata = [];
var newlist = [];
var unassignMachine = [];

//console.log(machinesHtml,'out')

function updateStepsOnPage(dataSteps) {
  // Clear the existing steps
  $('#steps-container').empty();
  

  // Log the selectedMachines array
  //console.log(selectedMachines,'in');
  //machinesHtml = '';
    //console.log(selectedMachines.length,'12len');
    // Iterate over the selected machines and build machinesHtml
    
 
  dataSteps.steps.forEach(function(item, index) {
    var orderNo = index + 1;
    var orderId = parseInt(orderNo); // Convert orderNo to an integer
    var assignedMachine = '';

    
    // Iterate over the machines array and create HTML for each machine
     item.machines.forEach(function(machine, machineIndex) {
         assignedMachine += '<div class="machine-title">' + machine.title + '</div>';

        // Add a comma after each machine title except for the last one
        if (machineIndex < item.machines.length - 1) {
            assignedMachine += ', ';
        }
    });

    var stepHtml = '<tr data-order="' + orderNo + '" class="step-row">' +
       '<td>' +
      '<i class="move-icon fas fa-arrows-alt-v"></i>' +
      '</td>' +
       '<td>' + orderNo + '</td>' +
      //'<td>' + item.description_id + '</td>' +
      '<td>' + item.title + '</td>' +
      '<td>' + item.description + '</td>' +
      '<td class="machines-cell">' + machinesHtml + '</td>' +
      '<td class="machines-cell">' + assignedMachine + '</td>' +
      '<td>' + '<button type="button"  class="btn btn-primary" data-bs-toggle="modal" data-bs-target=".bd-example-modal-lg"  data-description_id="' + item.description_id + '" data-order_id="' + orderId + '">Add</button>' + '</td>' +
      '</tr>';

    // Append the new steps
    $('#steps-container').append(stepHtml);
    //order_id = orderNo;
  });




  // Enable drag and drop functionality using Sortable.js
  var stepsContainer = document.getElementById('steps-container');
  var sortable = Sortable.create(stepsContainer, {
    animation: 150,
    onEnd: function(event) {
      var rows = Array.from(stepsContainer.getElementsByClassName('step-row'));
      var updatedSteps = [];

      rows.forEach(function(row, index) {
        var orderNoCell = row.getElementsByTagName('td')[1];
        var order_idAttr = row.getElementsByTagName('button')[0].getAttribute('data-order_id');

        orderNoCell.textContent = index + 1;
        row.setAttribute('data-order', index + 1);
        row.getElementsByTagName('button')[0].setAttribute('data-order_id', index + 1);

        var itemIndex = parseInt(row.getAttribute('data-order')) - 1;
        var item = dataSteps.steps.splice(itemIndex, 1)[0];
        updatedSteps.push(item);
      });

      dataSteps.steps = dataSteps.steps.concat(updatedSteps);
      console.log(dataSteps.steps ,'a')
    }
  });
}




$(document).on('click', '[data-bs-target=".bd-example-modal-lg"]', function() {
  var descriptionId = $(this).data('description_id');
  $('#modal-description-id').val(descriptionId);
   var order_id = $(this).data('order_id');
    //console.log(order_id,'orderno')
  $('#modal-order-id').val(order_id);

  var itemIndex = $(this).closest('tr').index();
  var item = dataSteps.steps[itemIndex];
  $('#modalTitle').text(item.title);


var concatenatedValue = '';
  if (article_name) {
    concatenatedValue += article_name;
    if (group_name) {
      concatenatedValue += ' / ' + group_name;
    }
    concatenatedValue += ' / ' + item.title;
    concatenatedValue += ' / ' + item.description;
  } else {
    concatenatedValue = item.title;
  }

$('#modalArticleName').text(concatenatedValue);



  // Assigned machines for the current step
//machinesdata = [];
item.machines.forEach(function(machine) {
  machinesdata.push({
    dateTime : machine.start_date,
    machines: machine.ID,
    title: machine.title,
   
  });
});
console.log(item ,'aq')
//newlist = machinesdata;

//updateStepsOnPage(dataSteps);
console.log(machinesdata ,'machinedata')

var selectedMachines_assigned = new Set(); // Store selected machine titles

$('.check-step').each(function() {
  var checkbox = $(this);
  var checkboxValue = checkbox.val();
  var checkboxConcatenatedValue = checkbox.data('concatenated-value');
  var checkboxMachineID = checkbox.attr('id');

  var matchedMachine = machinesdata.find(function(machine) {
    return machine.machines === checkboxMachineID;
  });

  if (
    matchedMachine &&
    checkboxConcatenatedValue.includes(article_name) &&
    checkboxConcatenatedValue.includes(group_name) &&
    checkboxConcatenatedValue.includes(item.title)
  ) {
    checkbox.prop('checked', true);

    selectedMachines_assigned.add(matchedMachine); // Add machine title to the selectedMachines_assigned set
  } else {
    checkbox.prop('checked', false);
  }
});

$('.selected-machine').empty(); // Remove previously selected machine data

selectedMachines_assigned.forEach(function(machine) {
  var machineTitle = machine.title;
  var machineDatetime = machine.dateTime;
  
  var datetimeInputHtml = '<input type="datetime-local" class="datetime-input form-control" placeholder="Enter time and date" value="' + machineDatetime + '">';

  $('.selected-machine').append('<li><div class="row"><div class="col-md-4">' + machineTitle + '</div><div class="col-md-8">' + datetimeInputHtml + '</div></div></li>');
});

// Find the existing machine data in selectedMachines array based on description_id and order_id
var existingMachineIndex = selectedMachines.findIndex(function(machine) {
  return (
    machine.description_id.toString() === descriptionId.toString() &&
    machine.order_id.toString() === order_id.toString()
  );
});

if (existingMachineIndex !== -1) {
  // If machine data exists, check if `data` is an array and convert to an array if necessary
  if (!Array.isArray(selectedMachines[existingMachineIndex].data)) {
    selectedMachines[existingMachineIndex].data = Array.from(selectedMachines[existingMachineIndex].data);
  }

  // Update the data array with the merged set
  selectedMachines[existingMachineIndex].data = Array.from(new Set([...selectedMachines[existingMachineIndex].data, ...selectedMachines_assigned]));
} else {
  // If machine data does not exist, add a new object to selectedMachines array
  selectedMachines.push({
    description_id: descriptionId.toString(),
    order_id: order_id.toString(),
    data: Array.from(selectedMachines_assigned)
  });
}

//console.log(selectedMachines, 'e');

checkedCount = $('.check-step:checked').length; // Update the checkedCount
updateCheckedCount(); // Update the count in the <p> element

  
  

}); 



// Array to store selected machines
var checkedCount = 0;
// Function to update the count in the <p> element
function updateCheckedCount() {
  $('p#checkedCount').text('Checked: ' + checkedCount);
}


// Event handler for checkbox change
// Event handler for checkbox change
$(document).on('change', '.check-step', function() {
  var machineId = $(this).attr('id');
  var machineTitle = $(this).val();
  var datetime = $(this).closest('li').find('.datetime-input').val();
  var descriptionId = $('#modal-description-id').val();
  var orderid = $('#modal-order-id').val();

  // Check if the machine already exists for the description ID
  var existingMachine = selectedMachines.find(function(machine) {
    return machine.description_id === descriptionId;
  });

  if (existingMachine) {
    var existingMachineData = existingMachine.data.find(function(machineData) {
      return machineData.machines === machineId.toString();
    });

    if (existingMachineData) {
      if ($(this).is(':checked')) {
        // Machine already exists and checkbox is checked, show an alert message
        alert('This machine is already selected.');
      } else {
        // Machine already exists and checkbox is unchecked, remove the machine
        existingMachine.data = existingMachine.data.filter(function(machine) {
          return machine.machines !== machineId.toString();
        });
        // If no machines left for the description ID, remove it from selectedMachines array
        if (existingMachine.data.length === 0) {
          selectedMachines = selectedMachines.filter(function(machine) {
            return machine.description_id !== descriptionId;
          });
        }
        // Remove machine and input field from selected-machine div
        $('.selected-machine li').filter(function() {
          return $(this).text().includes(machineTitle);
        }).remove();
      }
      return;
    }
  }

  if ($(this).is(':checked')) {
    if (existingMachine) {
      // Check if the machine ID already exists in the selectedMachines array
      var machineExists = selectedMachines.some(function(machine) {
        return machine.data.some(function(machineData) {
          return machineData.machines === machineId.toString();
        });
      });

      if (machineExists) {
        // Machine already exists and checkbox is checked, show an alert message
        alert('This machine is already selected.');
        return;
      }

      // Add machine and input field to existing description ID
      existingMachine.data.push({
        dateTime: datetime, // Initialize with an empty value
        machines: machineId.toString(),
        title: machineTitle
      });
    } else {
      // Add new description ID and machine to selectedMachines array
      selectedMachines.push({
        description_id: descriptionId,
        order_id: orderid,
        data: [{
          dateTime: datetime, // Initialize with an empty value
          machines: machineId.toString(),
          title: machineTitle
        }]
      });
    }

    // Add machine and input field to selected-machine div
    $('.selected-machine').append('<li><div class="row"><div class="col-md-4">' + machineTitle + '</div><div class="col-md-8"><input type="datetime-local" class="datetime-input form-control" placeholder="Enter time and date"></div></div></li>');

    // Check the checkbox with the specified machine ID
    $('#' + machineId).prop('checked', true);

  } else {
    // Remove machine from selectedMachines array
    var existingMachineIndex = -1;

    selectedMachines.forEach(function(machine, index) {
      if (machine.description_id === descriptionId) {
        existingMachineIndex = index;
        return false; // Exit the loop
      }
    });

    if (existingMachineIndex > -1) {
      selectedMachines[existingMachineIndex].data = selectedMachines[existingMachineIndex].data.filter(function(machine) {
        return machine.machines !== machineId.toString();
      });

      // If no machines left for the description ID, remove it from selectedMachines array
      if (selectedMachines[existingMachineIndex].data.length === 0) {
        selectedMachines.splice(existingMachineIndex, 1);
      }
    }

    // Remove machine and input field from selected-machine div
    $('.selected-machine li').filter(function() {
      return $(this).text().includes(machineTitle);
    }).remove();

    // Uncheck the checkbox with the specified machine ID
    $('#' + machineId).prop('checked', false);
  }

  checkedCount = $('.check-step:checked').length; // Update the checkedCount
  updateCheckedCount(); // Update the count in the <p> element
});



// Event handler for datetime input change
$(document).on('change', '.datetime-input', function() {
  var machineId = $(this).data('machine-id');
  var datetime = $(this).val();
 
  selectedMachines.forEach(function(machine) {
    machine.data.forEach(function(m) {
      if (m.machine === machineId) {
        m.dateTime = datetime; // Update the assignment of datetime
      }
    });
  });
});


$('#saveChangesBtn').click(function() {
  $('.selected-machine li').each(function() {
    var machineTitle = $(this).first().text().trim();
    var datetime = $(this).find('.datetime-input').val();
    var machineId = getMachineIdByTitle(machineTitle);

    console.log(datetime , machineId,'aqsa')
    selectedMachines.forEach(function(machine) {
      machine.data.forEach(function(m) {
        if (m.machines=== machineId) {
          m.dateTime = datetime;
        }
      });
    });
  });
  
  console.log(selectedMachines);
 // Iterate over the existing table rows and update the machinesHtml
$('#steps-container tr').each(function(index) {
  var stepRow = $(this);
  var orderid = stepRow.find('td:nth-child(2)').text(); // Get the description ID from the row
  var machinesCell = stepRow.find('td:nth-child(5)');
  machinesCell.html(''); // Clear the existing machinesHtml

  selectedMachines.forEach(function(machine) {
    if (machine.order_id == orderid) {
      var machineTitles = machine.data.map(function(m) {
        unassignMachine.push(m.title);
        return '<div class="machine-title">' + m.title + '</div>';
      });
      
      machinesCell.append(machineTitles.join(', ')); // Join machine titles with commas and add to machinesCell
    }
  });
});

  // Clear the modal
  clearModal();
});

// Function to clear the modal
function clearModal() {
  $('.selected-machine').empty();
  $('.check-step').prop('checked', false);
  checkedCount = 0;
  updateCheckedCount();
  

  $('.bd-example-modal-lg').modal('hide');
}

// Function to clear the modal



function getMachineIdByTitle(title) {
  var machineId = null;
  selectedMachines.forEach(function(machine) {
    machine.data.forEach(function(m) {
      if (m.title === title) {
        machineId = m.machines;
        
        return false; // Exit the loop
      }
    });

    if (machineId !== null) {
      return false; // Exit the loop
    }
  });

  return machineId;
}



</script>




   
<script>
$(document).ready(function() {
  $('#addMachineBundleBtn').click(function() {

     var dataToSend = {
      articleId: articleId,
      group_id: group_id,
      selectedMachines:selectedMachines
      
    };

    var serializedData = JSON.stringify(dataToSend);
    console.log(serializedData);

    // Get the CSRF token value from the template variable
    var csrftoken = '{{ csrf_token }}';

    // Perform AJAX request or any other action to send the data
    $.ajax({
      url: '{% url "add_Machine_Bundle" %}',
      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.machine_bundle);
        window.location.reload();

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


{% endblock %}