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

<h4 class="fw-bold py-3 mb-4"><span class="text-muted fw-light">Masters / Designation /</span> All Designation</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_designation_add' %}" class="btn btn-primary" style="margin: 10px;">
            Add Designation</a>
            <!-- Updated for Bootstrap 5: data-bs-toggle and data-bs-target -->
            <button id="upload-csv" class="btn btn-info" style="margin: 10px;" data-bs-toggle="modal" data-bs-target="#csvUploadModal">Import Designation</button>
          </div>

        <div class="table-responsive" style="margin: 10px;">
          <table class="table table-bordered table-striped" id="designation_table" style="width: 100%;">
            <thead>
              <tr>
                <th>ID</th>
                <th>DESIGNATION NAME</th>
                <th>CREATED AT</th>
                <th>UPDATED AT</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 Departments via CSV</h5>
        <!-- Updated for Bootstrap 5: data-bs-dismiss -->
        <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">
        <div class="csv-info mb-3">
          <p class="text-muted">Upload a CSV file in the correct format. <a href="{% static 'csv/demo_designation.csv' %}" class="text-primary font-weight-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-file" id="csvFile" name="csv_file" accept=".csv" required>
              <span class="file-name">No file chosen</span>
              <button type="button" class="btn btn-outline-secondary btn-sm choose-file">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 btn-upload w-100">Upload CSV</button>
        </form>
      </div>
      <div class="modal-footer">
        <!-- Updated for Bootstrap 5: data-bs-dismiss -->
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
      </div>
    </div>
  </div>
</div>

<!-- Ensure jQuery is loaded before Bootstrap and DataTables -->
<script src="{% static 'plugins/jQuery/jQuery-2.1.3.min.js' %}" type="text/javascript"></script>
<script src="{% static 'dist/js/pages/designation_delete.js' %}" type="text/javascript"></script>
<!-- Custom CSS for Modal -->
<link rel="stylesheet" href="{% static 'css/custom.css' %}">
<script>
$(document).ready(function() {
    // Retrieve CSRF token from the cookie (better than from hidden input)
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrfToken = getCookie('csrftoken');
    console.log("CSRF Token: ", csrfToken);

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

    // Set AJAX URL (from Django template tag)
    var ajaxUrl = "{% url 'admin_designation_ajax_page_ajax' %}";

    // Initialize DataTable
    var table = $('#designation_table').DataTable({
        "ajax": {
            "url": ajaxUrl,
            "type": "POST"
        },
        "columns": [
            { data: 'id' },
            { data: 'name' },
            { data: 'created_at' },
            { data: 'updated_at' },
            {
                data: null,
                render: function(data, type, row) {
                    var editUrl = "{% url 'admin_designation_edit' 0 %}".replace('0', row.id);
                    var deleteUrl = "{% url 'admin_designation_delete' 0 %}".replace('0', row.id);
                    return `
                        <a title="EDIT" href="${editUrl}" class="btn btn-primary" data-toggle="tooltip" title="Edit">
                            <i class="bx bx-pencil"></i>
                        </a>
                        <button title="DELETE" class="btn btn-danger delete-link" data-id="${row.id}" value="${deleteUrl}">
                            <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": [
                    {
                        extend: 'csv',
                        text: 'Export'
                    },
                    'pageLength'
                ]
            }
        },
    });

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

    // Handle CSV Upload form submit
    $('#csvUploadForm').on('submit', function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            url: "{% url 'admin_designation_csv_upload' %}",
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                console.log("AJAX Response:", response);
                $('#csvUploadModal').modal('hide');
                clearFileInput();
                table.ajax.reload();

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

                    // Handle failed rows Excel download
                    if (response.failed_rows_excel) {
                        downloadFailedRowsExcel(response.failed_rows_excel, response.failed_rows_filename);
                        showAlert('warning', 'Some rows failed to upload. Downloaded error report (Excel).');
                    }
                } else {
                    showAlert('danger', response.message);
                }
            },
            error: function(xhr) {
                var errorMessage = xhr.responseJSON?.message || 'An error occurred while uploading the file.';
                $('#csvUploadModal').modal('hide');
                clearFileInput();
                showAlert('danger', errorMessage);
            }
        });
    });

    // Reusable alert function
    function showAlert(type, message) {
        $('<div class="alert alert-' + type + '" role="alert">' + message +
            '<button type="button" class="close" data-dismiss="alert"><span>&times;</span></button></div>')
            .insertBefore('.content-header')
            .delay(5000)
            .fadeOut();
    }

    // Download the failed rows Excel file
    function downloadFailedRowsExcel(base64Data, filename) {
        var binary = atob(base64Data);
        var array = new Uint8Array(binary.length);
        for (var i = 0; i < binary.length; i++) {
            array[i] = binary.charCodeAt(i);
        }
        var blob = new Blob([array], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = filename || 'failed_uploads.xlsx';
        link.click();
        window.URL.revokeObjectURL(link.href);
    }

    // Clear file input when modal is closed
    $('#csvUploadModal').on('hidden.bs.modal', clearFileInput);

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

    // Trigger file selection dialog
    $('.choose-file').on('click', function() {
        $(this).siblings('#csvFile').click();
    });
});
</script>
{% endblock %}