
{% 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;
  
}
</style>
<section class="main_content dashboard_part large_header_bg">

<div class="main_content_iner ">
<div class="container-fluid p-0 sm_padding_15px">
<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">Add Article</h3>
</div>
</div>
</div>
<div class="white_card_body">
<div class="card-body">
{% comment %} <form method="POST" action="{% url 'Add_article' %}" enctype="multipart/form-data"> {% endcomment %}
 
<form method="" enctype="multipart/form-data" id="reviewForm"> 

<div class="row mb-3">
<div class="col-md-12">
<label class="form-label" for="inputEmail4">Title</label>
<input type="text" class="form-control" id="inputEmail4" placeholder="Title" name="title">
</div>

</div>

<div class="row mb-3">
<div class="col-md-6">
<label class="form-label" for="inputEmail4">Bundle Size</label>
<input type="number" class="form-control"  id="piecesInput" placeholder="Enter Bundle Size" name="pieces">
</div>
<div class="col-md-6">
<label class="form-label" for="inputPassword4">Order Quantity</label>
<input type="number" class="form-control" id="orderQuantityInput" placeholder="Enter Order Quantity" name="orderQuantity">
</div>
</div> 

<div class="row mb-3">
<div class="col-md-6">
<label class="form-label" for="inputEmail4">Bundle Count</label>
<input type="number" class="form-control" id="bundleSizeInput" name="bundleSize">
</div>
<div class="col-md-6">
<label class="form-label" for="inputPassword4">Fabric Length (m)</label>
<input type="text" class="form-control" id="inputPassword4" placeholder="Enter Fabric Length" name="fabricLength">
</div>
</div>  

<div class="row mb-3">
<div class="col-md-4">
<label class="form-label" for="inputEmail4">Fabric</label>
<input type="text" class="form-control" id="inputEmail4" placeholder="Enter Fabric" name="fabric">
</div>
<div class="col-md-4">
<label class="form-label" for="inputPassword4">Style Description</label>
<input type="text" class="form-control" id="inputPassword4" placeholder="Enter Style Decription" name="style_description">
</div>
<div class="col-md-4">
<label class="form-label" for="inputPassword4">Color</label>
<input type="text" class="form-control" id="inputPassword4" placeholder="Enter color" name="color">
</div>
</div>  

<div class="row mb-4">

<div class="col-md-6">
<label class="form-label" for="inputPassword4">Start Date</label>
<input type="date" class="form-control" id="date_value" name="startDate" >

</div>
<div class=" col-md-6">
<label class="form-label" for="inputCity">Delivery Date</label>
<input type="date" class="form-control" id="inputCity" name="deliveryDate">
</div>
</div>


<div class="row mb-3">


<div class="col-lg-12">
<div class="card_box box_shadow position-relative mb_30">
<div class="white_box_tittle " style="padding:21px!important">
<div class="main-title2 ">
<button type="button" id="addGroupBtn"  class="btn btn-primary" data-bs-toggle="modal" data-bs-target=".bd-example-modal-lg" style="float:right">Add Group</button>
{% comment %} <h4 class="mb-2 nowrap">Basic Accordion</h4> {% endcomment %}
{% comment %} <p>Using the card component, you can extend the default collapse behavior to create an accordion</p> {% endcomment %}
</div>
</div>
<div class="box_body">
<div class="default-according" id="accordion">
{% comment %} <div class="card">

<div class="card-header" id="headingOne">
<h5 class="mb-0">
<button class="btn collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne">Front</button>
</h5>
</div>
<div class="collapse" id="collapseOne" aria-labelledby="headingOne" data-parent="#accordion" style>
<div class="card-body">
<p id="cardInfo">1234</p>
</div>


</div> {% endcomment %}
</div>
</div>



</div>
</div>
</div>
</div>

</div>

</div>
{% comment %} </div> {% endcomment %}
<button type="button" class="btn btn-primary" style="float:right" id="confirm-review">Add Article</button> 
{% comment %} <button type="submit"  onclick="handleSubmit()" class="btn btn-primary" style="float:right">Add Article</button> {% endcomment %}
</form>

</div>
</div>
</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 Group</h4>
 {% comment %} <i class="fas fa-times remove-section-icon"></i> {% endcomment %}
</div>
</div>
<div class="box_body">

<div class="row mb-3">
<div class="col-md-12">
<label class="form-label" for="inputPassword4">Group title</label>
<input type="text" class="form-control group_title" id="group_title" name="group_title" >
</div>
</div>

<div class="row mb-3">
<div class="col-md-4">
<div class="email-sidebar" style="height: 250px; overflow-y: auto;">
  {% for skill in skills %}
   <div class="form-check">
      <input class="form-check-input check-step" type="checkbox" id="{{skill.id}}" name="{{skill.id}}" value="{{skill.title}}">
      <label class="form-check-label" for="cutting-checkbox" style="font-size:12px;">{{skill.title}}</label>
    </div>
    {% endfor %}
</div>
</div> 


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

</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="saveChangesBtn">Add Group</button>
</div>
</div>
</div>


{% comment %} <div class="modal fade" id="reviewModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Review Article</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
    <p>Name: <span id="title"></span></p>
    <p>Pieces:<span id="pieces"></span></p>
    <p>Order Quantity:<span id="orderQuantity"></span></p>
    <p>Bundle Size:<span id="bundleSize"></span></p>
    <p>Fabric Length:<span id="fabricLength"></span></p>
    <p>Start Date: <span id="startDate"></span></p>
    <p>End Date:<span id="deliveryDate"></span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" style="float:right" id="confirm-review">Add Article</button> 
</div>
</div>
</div>
</div> {% endcomment %}
<!-- review_form.html -->



<div id="back-top" style="display: none;">
<a title="Go to Top" href="#">
<i class="ti-angle-up"></i>
</a>
</div>

<!-- review_form.html -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
// Get the input elements
const piecesInput = document.getElementById('piecesInput');
const orderQuantityInput = document.getElementById('orderQuantityInput');
const bundleSizeInput = document.getElementById('bundleSizeInput');

// Add an event listener to the order quantity input
orderQuantityInput.addEventListener('input', calculateBundleSize);

// Function to calculate the bundle size
function calculateBundleSize() {
  // Get the values entered by the user
  const pieces = parseInt(piecesInput.value);
  const orderQuantity = parseInt(orderQuantityInput.value);
  
  // Calculate the bundle size
  const bundleSize = Math.round(orderQuantity / pieces);
  
  // Update the bundle size input value
  bundleSizeInput.value = bundleSize;
}






// Initialize the group index

  // Function to create and insert an accordion card
  function createAccordionCard(groupData, index) {
    // Create the card HTML
    var cardHtml = '<div class="card">' +
      '<div class="card-header" id="heading' + index + '">' +
      '<h5 class="mb-0">' +
      '<button class="btn collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse' + index + '" aria-expanded="false" aria-controls="collapse' + groupIndex + '">' + groupData.groupTitle + '</button>' +
      '</h5>' +
      '</div>' +
      '<div class="collapse" id="collapse' + index + '" aria-labelledby="heading' + index + '" data-parent="#accordion">' +
      '<div class="card-body">' +
      '<table class="table table-bordered">' +
      '<thead>' +
      '<tr>' +
      '<th>Title</th>' +
      '<th>Description</th>' +
      '</tr>' +
      '</thead>' +
      '<tbody>';

    // Iterate over the checkboxes and add them to the table
    groupData.checkboxes.forEach(function(checkbox) {
      cardHtml += '<tr>' +
        '<td>' + checkbox.title + '</td>' +
        '<td>' + checkbox.description + '</td>' +
        '</tr>';
    });

    // Close the table and card HTML
    cardHtml += '</tbody></table></div></div></div>';

    // Append the card HTML to the accordion
    $('#accordion').append(cardHtml);
  }
  var groupDataArray = []; // Array to store group data
  var groupIndex = 0;
  $(document).ready(function() {
    var dataPushed = false; // Flag variable to track data pushing  
    // Handle checkbox change event using event delegation
    $(document).on('change', '.check-step', function() {
      // Get the current group container
      var groupContainer = $(this).closest('.col-lg-12');
      var groupIndex = groupContainer.index();
      //console.log(groupIndex)
      // Get the selected checkbox data
      var selectedStep = $(this).val();
      var selectedSkillId = $(this).attr('id');

      // Find the group data in the groupDataArray or create a new one
      var groupData = groupDataArray[groupIndex] || {
        groupTitle: '',
        checkboxes: []
      };

      // Find the selected checkboxes list in the group container
      var selectedList = groupContainer.find('.selected-skills');

      if ($(this).is(':checked')) {
        // Generate a unique ID for the description item
        var itemId = selectedSkillId + '_' + groupIndex;

        // Create a new item if it doesn't exist
        var newItem = $('#' + itemId);

        if (newItem.length == 0) {
          newItem = $('<div class="row mb-3"><div class="col-md-3"><p>' + selectedStep + '</p></div><div class="col-md-9"><input type="text" class="form-control" placeholder="add description" name="description"  data-checkbox-id="' + selectedSkillId + '"></div></div>');
          newItem.attr('id', itemId);
          selectedList.append(newItem);

          // Add event listener for description input field
          newItem.find('input[name="description"]').on('input', function() {
            updateDescription(groupIndex, selectedSkillId, $(this).val());
          });
        }

        // Add the selected checkbox data to the group data
       // groupData.checkboxes.push({
          //id: selectedSkillId,
          //title: selectedStep,
          //description: ''
        //});

      } else {
        // Remove the item if the checkbox is unchecked
        selectedList.find('#' + selectedSkillId + '_' + groupIndex).closest('.row').remove();

        // Remove the selected checkbox data from the group data
        groupData.checkboxes = groupData.checkboxes.filter(function(item) {
          return item.id !== selectedSkillId;
        });
      }

      // Update the group data in the groupDataArray
      //groupDataArray[groupIndex] = groupData;
      updateGroupData(); // Update the group data whenever checkboxes change
    });

    // Event listener for the group title input field
    $(document).on('input', '.group_title', function() {
      // Get the current group container
      var groupContainer = $(this).closest('.col-lg-12');
      var groupIndex = groupContainer.index();

      // Find the group data in the groupDataArray or create a new one
      //var groupData = groupDataArray[groupIndex] || {
        //groupTitle: '',
        //checkboxes: []
      //};

      // Update the group title in the group data
      //groupData.groupTitle = $(this).val();

      // Update the group data in the groupDataArray
      //groupDataArray[groupIndex] = groupData;
      updateGroupData(); // Update the group data whenever group title changes
    });

    // Function to update the description in the groupDataArray
    function updateDescription(groupIndex, selectedSkillId, description) {
      // Find the group data in the groupDataArray
      var groupData = groupDataArray[groupIndex];

      if (groupData) {
        // Find the checkbox in the group data
        var checkbox = groupData.checkboxes.find(function(item) {
          return item.id === selectedSkillId;
        });

        if (checkbox) {
          // Update the description in the checkbox
          checkbox.description = description;
        }
      }

      updateGroupData() // Update the group data whenever description changes
    }

    // Function to update the group data with the latest values
    function updateGroupData() {
      //console.log(groupDataArray); // Log the updated group data
    }
  
       // Initialize the group index
  
    $('#saveChangesBtn').click(function() {
      // Save changes logic here
      // Create a new group data object
      var groupData = {
        groupTitle: $('.group_title').val(),
        checkboxes: []
      };

      // Iterate over the selected checkboxes in the modal
      $('.check-step:checked').each(function() {
        var checkboxId = $(this).attr('id');
        var checkboxTitle = $(this).val();
        var descriptionValue = $(this).closest('.row').find('input[name="description"][data-checkbox-id="' + checkboxId + '"]').val();
        // Add the selected checkbox data to the group data
        groupData.checkboxes.push({
          id: checkboxId, 
          title: checkboxTitle,
          description: descriptionValue
        });
      });
      
    
     // Increment the group index

  
  // Push the new group data to the groupDataArray
  groupDataArray.push(groupData);
  groupIndex++;
      // Reset the modal and group data
      $('.group_title').val('');
      $('.check-step').prop('checked', false);
      $('.selected-skills').empty();
         
      // Update the accordion card information
      createAccordionCard(groupData, groupIndex);
      
   
      // Hide the modal
      $('.modal').modal('hide');
      
    });
    
        
});
    // ...

</script>


<script>
 $(document).ready(function() {
  $('#confirm-review').click(function() {
    var title = $('[name="title"]').val();
    var pieces = $('[name="pieces"]').val();
    var orderQuantity = $('[name="orderQuantity"]').val();
    var bundleSize = $('[name="bundleSize"]').val();
    var fabricLength = $('[name="fabricLength"]').val();
    var fabric = $('[name="fabric"]').val();
    var style_description = $('[name="style_description"]').val();
    var color = $('[name="color"]').val();
    var startDate = $('[name="startDate"]').val();
    var deliveryDate = $('[name="deliveryDate"]').val();

    var dataToSend = {
      title: title,
      pieces: pieces,
      orderQuantity: orderQuantity,
      bundleSize: bundleSize,
      fabricLength: fabricLength,
      fabric:fabric,
      style_description : style_description,
      color:  color,
      startDate: startDate,
      deliveryDate: deliveryDate,
      groupDataArray: groupDataArray
    };

    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_article_data" %}',
      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');
        window.location.href="{% url 'article_page' %}"
        console.log(response.data_article);

        // 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>  

<script>
  // Get the current date
  var currentDate = new Date();

  // Format the date to YYYY-MM-DD
  var year = currentDate.getFullYear();
  var month = String(currentDate.getMonth() + 1).padStart(2, '0');
  var day = String(currentDate.getDate()).padStart(2, '0');
  var formattedDate = `${year}-${month}-${day}`;
  console.log(formattedDate);

  // Set the defaultValue of the input field
  document.getElementById('date_value').value = formattedDate;
</script>


{% comment %} <script>
function CreateFields(id, title, bundleSize) {
   document.getElementById('dropdownMenuButton').textContent = title;
    var dataToSend = {
        id: id
     };

  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 "Get_opeartions" %}',
    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.data_skill,response.data_skill.length);
      skills(response.data_skill,response.data_skill.length)
      
      // 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>
 <script> 
  function skills(data_skill, data_skill_length) {
  // Clear previous input fields
  document.getElementById("inputFieldsContainer").innerHTML = "";

  for (var i = 0; i < data_skill_length; i++) {
    // Create title input field
    var titleLabel = document.createElement("label");
    titleLabel.textContent = "Operations:";
    var titleInput = document.createElement("input");
    titleInput.setAttribute("type", "text");
    titleInput.setAttribute("class", "form-control");
    titleInput.setAttribute("name", "operation");
    titleInput.value = data_skill[i].title; // Set the value from data_skill

    // Create operations input field
    var operationsLabel = document.createElement("label");
    operationsLabel.textContent = "Description:";
    var operationsInput = document.createElement("input");
    operationsInput.setAttribute("type", "text");
    operationsInput.setAttribute("class", "form-control");
    operationsInput.setAttribute("name", "description");

    // Create main_part_id input field
    var mainPartIdInput = document.createElement("input");
    mainPartIdInput.setAttribute("type", "hidden");
    mainPartIdInput.setAttribute("name", "mainPartId");
    mainPartIdInput.value = data_skill[i].main_part_id; // Set the value from data_skill
    // Create id input field
    var idInput = document.createElement("input");
    idInput.setAttribute("type", "hidden");
    idInput.setAttribute("name", "id");
    idInput.value = data_skill[i].id;

    // Create div elements for layout
    var rowDiv = document.createElement("div");
    rowDiv.setAttribute("class", "row mb-3");

    var titleDiv = document.createElement("div");
    titleDiv.setAttribute("class", "col-md-6");

    var operationsDiv = document.createElement("div");
    operationsDiv.setAttribute("class", "col-md-6");

    // Append input fields to the corresponding div elements
    titleDiv.appendChild(titleLabel);
    titleDiv.appendChild(titleInput);
    operationsDiv.appendChild(operationsLabel);
    operationsDiv.appendChild(operationsInput);

    // Append main_part_id input field
    rowDiv.appendChild(mainPartIdInput);
    rowDiv.appendChild(idInput);

    // Append div elements to the row div
    rowDiv.appendChild(titleDiv);
    rowDiv.appendChild(operationsDiv);

    // Append the row div to the container
    document.getElementById("inputFieldsContainer").appendChild(rowDiv);
  }
}

  function handleSubmit() {
    //event.preventDefault(); // Prevent the form from submitting
     // Do something with the field values
    // Get form field values
      var title = $('[name="operation"]').map(function() {
        return $(this).val();
      }).get();

      var description = $('[name="description"]').map(function() {
        return $(this).val();
      }).get();

      var mainPartId = $('[name="mainPartId"]').map(function() {
        return $(this).val();
      }).get();
    
    var mainIdInput = $('[name="id"]').map(function() {
        return $(this).val();
      }).get();

      // Combine title, description, and mainPartId arrays into a single array of objects
      var operations = [];
      for (var i = 0; i < title.length; i++) {
        var operation = {
          id: mainIdInput[i],
          title: title[i],
          description: description[i]
        };
        operations.push(operation);
      }

   
    // Do something with the field values
    console.log('Operations:', operations);

    // Get form field values
      var title = $('[name="title"]').val();
      var pieces = $('[name="pieces"]').val();
      var orderQuantity = $('[name="orderQuantity"]').val();
      var bundleSize = $('[name="bundleSize"]').val();
      var fabricLength = $('[name="fabricLength"]').val();
      var startDate = $('[name="startDate"]').val();
      var deliveryDate = $('[name="deliveryDate"]').val();
      var mainPartId = $('[name="mainPartId"]').val();
      var fabric = $('[name="fabric"]').val();
      var style_description = $('[name="style_description"]').val();
      var color = $('[name="color"]').val();

      // Create an object with all the form data
      var formData = {
        title: title,
        pieces: pieces,
        orderQuantity: orderQuantity,
        bundleSize: bundleSize,
        fabricLength: fabricLength,
        fabric :fabric,
        style_description : style_description,
        color : color, 
        startDate: startDate,
        deliveryDate: deliveryDate,
        mainPartId: mainPartId,
        
      };

      // Combine the formData object with the operations array
      formData.operations = operations;

      
      // Serialize the form data
      var serializedData = JSON.stringify(formData);
      console.log('Form Data:', serializedData);

      var csrftoken = '{{ csrf_token }}';
      // Send the form data to the server using AJAX
      $.ajax({
        url: {% url 'Add_article_data' %}, // Replace with your server endpoint
        type: 'POST', // Or 'GET' depending on your server configuration
        data: serializedData,
        contentType: 'application/json',
          beforeSend: function(xhr, settings) {
            xhr.setRequestHeader('X-CSRFToken', csrftoken);
          },
        success: function(response) {
          // Handle the server response here
          window.location.href = "{% url 'article_page' %}";
          console.log('Server Response:', response);
        },
        error: function(error) {
          // Handle any error that occurred during the AJAX request
          console.error('AJAX Error:', error);
        }
      });
     
    // You can send the form data to the server using AJAX or perform any other action here
  } {% endcomment %}



{% comment %} </script>   {% endcomment %}



{% endblock %}