{% extends 'dashboard/admin_dashboard/main.html' %}
{% load static %}
{% block content %}

<h4 class="fw-bold py-3 mb-4">User</h4>
<div style="padding: 10px;">
  {% if messages %}
    {% for message in messages %}
      <div class="alert {% if 'success' in message.tags %}alert-success alert-dismissible{% elif 'danger' in message.tags %}alert-danger alert-dismissible{% endif %}" role="alert" id="success-alert">
        {{ message }}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div>
    {% endfor %}
  {% endif %}
</div>

<div class="row">
  <div class="col-lg-12 col-md-12">
    <div class="card">
      <div class="mt-3 d-flex justify-content-start">
        <a href="{% url 'admin_user_add' %}" class="btn btn-primary" style="margin: 10px;">Add User</a>
        <button id="upload-csv" class="btn btn-info" style="margin: 10px;" data-bs-toggle="modal" data-bs-target="#csvUploadModal">Import User</button>
      </div>

      <div class="table-responsive" style="margin: 10px;">
        <table class="table table-bordered table-striped" id="user_table" style="width: 100%;">
          <thead>
            <tr>
              <th>ID</th>
              <th>First Name</th>
              <th>Last Name</th>
              <th>Employee Code</th>
              <th>Email</th>
              <th>Image</th>
              <th>Company</th>
              <th>Department</th>
              <th>Location</th>
              <th>Role</th>
              <th>Approval Required</th>
              <th>Status</th>
              <th>Action</th>
            </tr>
          </thead>
        </table>
        {% csrf_token %}
      </div>
    </div>
  </div>
</div>

<!-- CSV Upload Modal -->
<div class="modal fade" id="csvUploadModal" tabindex="-1" aria-labelledby="csvUploadModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content custom-modal">
      <div class="modal-header">
        <h5 class="modal-title" id="csvUploadModalLabel">Upload Users via CSV</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="csv-info mb-3">
          <p class="text-muted">Upload a CSV file in the correct format. <a href="{% static 'csv/demo_users.csv' %}" class="text-primary fw-bold">Download sample CSV</a> to see the required format.</p>
        </div>
        <form id="csvUploadForm" enctype="multipart/form-data">
          <div class="form-group">
            <label for="csvFile" class="form-label">Select CSV File</label>
            <div class="custom-file-upload">
              <input type="file" class="form-control" id="csvFile" name="csv_file" accept=".csv" required>
              <span class="file-name d-block mt-2">No file chosen</span>
              <button type="button" class="btn btn-outline-secondary btn-sm choose-file mt-2">Choose File</button>
            </div>
            <small class="form-text text-muted mt-2">Only .csv files are accepted (max size: 5MB).</small>
          </div>
          {% csrf_token %}
          <button type="submit" class="btn btn-primary w-100 mt-3">Upload CSV</button>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
      </div>
    </div>
  </div>
</div>

<!-- Custom CSS -->
<link rel="stylesheet" href="{% static 'css/custom.css' %}">

<!-- Scripts -->
<script src="{% static 'plugins/jQuery/jQuery-2.1.3.min.js' %}"></script>
<script src="{% static 'dist/js/pages/user_delete.js' %}"></script>

<script>
$(document).ready(function() {
  var csrfToken = $('input[name=csrfmiddlewaretoken]').val();

  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrfToken);
      }
    }
  });

  var table = $('#user_table').DataTable({
    "ajax": {
      "url": "{% url 'admin_user_ajax_page_ajax' %}",
      "type": "POST"
    },
    "columns": [
      { data: 'id' },
      { data: 'first_name' },
      { data: 'last_name' },
      { data: 'employee_code' },
      { data: 'email' },
      {
        data: 'image',
        render: function(data) {
          let imageUrl = data ? '{{IMAGEPATH}}' + data : '{{DEFAULT_IMAGE}}';
          return '<img src="' + imageUrl + '" alt="User Image" width="50" height="50"/>';
        }
      },
      { data: 'company_name' },
      { data: 'department_name' },
      { data: 'location_name' },
      { data: 'type' },
      {
        data: 'approval_require',
        render: function(data) {
          return data == 1 ? 'Yes' : 'No';
        }
      },
      {
        data: 'is_active',
        render: function(data) {
          return data == 1 ? 'Active' : 'Inactive';
        }
      },
      {
        data: null,
        render: function(data, type, row) {
          var editUrl = "{% url 'admin_user_edit' 0 %}".replace('0', row.id);
          var deleteUrl = "{% url 'admin_user_delete' 0 %}".replace('0', row.id);
          return `<a href="${editUrl}" class="btn btn-primary" title="Edit"><i class="bx bx-pencil"></i></a>
                  <button class="btn btn-danger delete-link" data-id="${row.id}" value="${deleteUrl}" title="Delete"><i class="bx bx-trash"></i></button>`;
        }
      }
    ],
    processing: true,
    serverSide: true,
    responsive: true,
    ordering: false,
    lengthMenu: [
      [10, 25, 50, 100],
      [10, 25, 50, 100]
    ],
    layout: {
      topStart: {
        buttons: ['csv', 'pageLength']
      }
    }
  });

  function clearFileInput() {
    $('#csvFile').val('');
    $('.file-name').text('No file chosen');
  }

  $('#csvUploadForm').on('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    $.ajax({
      url: "{% url 'admin_user_csv_upload' %}",
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(response) {
        $('#csvUploadModal').modal('hide');
        clearFileInput();
        table.ajax.reload();

        if (response.status === 'success') {
          var countMessage = response.count ? ` (${response.count} users added)` : '';
          showAlert('success', response.message + countMessage);

          if (response.failed_rows_excel) {
            const binary = atob(response.failed_rows_excel);
            const array = new Uint8Array(binary.length);
            for (let i = 0; i < binary.length; i++) {
              array[i] = binary.charCodeAt(i);
            }
            const blob = new Blob([array], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = response.failed_rows_filename || 'failed_uploads.xlsx';
            link.click();
            showAlert('warning', 'Some rows failed to upload. Downloaded error report (Excel).');
          }
        } else {
          showAlert('danger', response.message);
        }
      },
      error: function(xhr) {
        $('#csvUploadModal').modal('hide');
        clearFileInput();
        var message = xhr.responseJSON?.message || 'An error occurred while uploading the file.';
        showAlert('danger', message);
      }
    });
  });

  function showAlert(type, message) {
    $(`<div class="alert alert-${type} alert-dismissible fade show mt-3" role="alert">
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div>`).insertBefore('.card').delay(5000).fadeOut(1000, function() {
        $(this).remove();
      });
  }

  $('#csvUploadModal').on('hidden.bs.modal', clearFileInput);

  $('#csvFile').on('change', function() {
    var fileName = this.files.length > 0 ? this.files[0].name : 'No file chosen';
    $(this).siblings('.file-name').text(fileName);
  });

  $('.choose-file').on('click', function() {
    $('#csvFile').click();
  });
});
</script>

{% endblock %}
