'use strict';

$(function () {
  // --- Variable Definitions ---
  var dtApplicationTable = $('.datatables-job-applications');
  var statusFilter = $('#applicationStatusFilter');
  var select2 = $('.select2');

  // CSRF Token Setup for all AJAX requests
  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': pageData.csrfToken
    }
  });

  // --- Initialize Select2 ---
  if (select2.length) {
    select2.select2({
      placeholder: pageData.labels.selectStatus || 'Select Status',
      allowClear: true
    });
  }

  // --- DataTable Initialization ---
  if (dtApplicationTable.length) {
    var dtApplication = dtApplicationTable.DataTable({
      processing: true,
      serverSide: true,
      ajax: {
        url: pageData.urls.datatable,
        type: 'POST',
        data: function (d) {
          d.statusFilter = statusFilter.val();
          d.jobOpeningId = pageData.jobOpeningId;
        }
      },
      columns: [
        { data: 'id', name: 'id' },
        { data: 'candidateFullName', name: 'candidateFullName', orderable: false, searchable: true },
        { data: 'candidate_email', name: 'candidate_email' },
        { data: 'candidate_phone', name: 'candidate_phone' },
        { data: 'submitted_at', name: 'submitted_at' },
        { data: 'resumeLink', name: 'resumeLink', orderable: false, searchable: false },
        { data: 'status', name: 'status' },
        { data: 'actions', name: 'actions', orderable: false, searchable: false, className: 'text-center' }
      ],
      order: [[4, 'desc']],
      dom: '<"row me-2"<"col-md-2"<"me-3"l>><"col-md-10"<"dt-action-buttons text-xl-end text-lg-start text-md-end text-start d-flex align-items-center justify-content-end flex-md-row flex-column mb-3 mb-md-0"fB>>>t<"row mx-2"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',
      language: {
        sLengthMenu: '_MENU_',
        search: '',
        searchPlaceholder: pageData.labels.searchPlaceholder || 'Search Applications..'
      },
      buttons: [],
      responsive: {
        details: {
          display: $.fn.dataTable.Responsive.display.modal({
            header: function (row) {
              var data = row.data();
              return (pageData.labels.detailsFor || 'Details for') + ' ' + data['candidateFullName'];
            }
          }),
          type: 'column',
          renderer: function (api, rowIdx, columns) {
            var data = $.map(columns, function (col, i) {
              return col.columnIndex < (columns.length - 1) && col.title !== '' ?
                '<tr data-dt-row="' + col.rowIndex + '" data-dt-column="' + col.columnIndex + '">' +
                '<td>' + col.title + ':' + '</td> ' +
                '<td>' + col.data + '</td>' +
                '</tr>' : '';
            }).join('');
            return data ? $('<table class="table"/><tbody />').append(data) : false;
          }
        }
      },
      columnDefs: [
        { targets: 1, data: 'candidateFullName', name: 'candidateFullName' },
        { targets: 2, data: 'candidate_email', name: 'candidate_email' },
        { targets: 3, data: 'candidate_phone', name: 'candidate_phone' },
        { targets: 4, data: 'submitted_at', name: 'submitted_at' },
        { targets: 5, data: 'resumeLink', name: 'resumeLink' },
        { targets: 6, data: 'status', name: 'status' },
        { targets: 7, data: 'actions', name: 'actions' }
      ]
    });
  }

  // --- Filter Changes ---
  statusFilter.on('change', function () {
    if (dtApplication) {
      dtApplication.ajax.reload();
    }
  });

  // --- Status Change Handling ---
  $(document).on('click', '.change-status-btn', function (e) {
    e.preventDefault();
    var button = $(this);
    var updateUrl = button.data('url');
    var newStatus = button.data('new-status');
    var appId = button.data('app-id');
    var currentStatus = button.closest('td').find('.badge').data('current-status');

    if (newStatus === currentStatus) {
      return;
    }

    $.ajax({
      url: updateUrl,
      type: 'PUT',
      data: {
        status: newStatus
      },
      beforeSend: function() {
        button.closest('tr').css('opacity', 0.5);
      },
      success: function (response) {
        if (response.success) {
          if(dtApplication) {
            dtApplication.row(button.closest('tr')).invalidate().draw(false);
          }
        } else {
          Swal.fire({
            icon: 'error',
            title: pageData.labels.error || 'Error',
            text: response.message || pageData.labels.failedToUpdate || 'Failed to update status.',
            customClass: { confirmButton: 'btn btn-danger' },
            buttonsStyling: false
          });
          if(dtApplication) { button.closest('tr').css('opacity', 1); }
        }
      },
      error: function (jqXHR) {
        let message = pageData.labels.anErrorOccurred || 'An error occurred.';
        if (jqXHR.responseJSON?.message) { message = jqXHR.responseJSON.message; }
        Swal.fire({
          icon: 'error',
          title: pageData.labels.error || 'Error',
          text: message,
          customClass: { confirmButton: 'btn btn-danger' },
          buttonsStyling: false
        });
        if(dtApplication) { button.closest('tr').css('opacity', 1); }
      },
      complete: function() {
        if(dtApplication) { button.closest('tr').css('opacity', 1); }
      }
    });
  });

  // --- Delete Application Handling ---
  $(document).on('click', '.delete-application', function () {
    var button = $(this);
    var deleteUrl = button.data('url');
    var appId = button.data('id');

    Swal.fire({
      title: pageData.labels.areYouSure || 'Are you sure?',
      text: pageData.labels.deleteWarning || "You won't be able to revert this! The resume file will also be deleted.",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: pageData.labels.yesDelete || 'Yes, delete it!',
      cancelButtonText: pageData.labels.cancel || 'Cancel',
      customClass: { confirmButton: 'btn btn-primary me-3', cancelButton: 'btn btn-label-secondary' },
      buttonsStyling: false
    }).then(function (result) {
      if (result.isConfirmed) {
        $.ajax({
          url: deleteUrl,
          type: 'DELETE',
          success: function (response) {
            if (response.success) {
              Swal.fire({
                icon: 'success',
                title: pageData.labels.deleted || 'Deleted!',
                text: response.message,
                customClass: { confirmButton: 'btn btn-success' },
                buttonsStyling: false
              });
              if(dtApplication) {
                dtApplication.row(button.closest('tr')).remove().draw(false);
              }
            } else {
              Swal.fire({
                icon: 'error',
                title: pageData.labels.error || 'Error!',
                text: response.message || pageData.labels.failedToDelete || 'Failed to delete application.',
                customClass: { confirmButton: 'btn btn-danger' },
                buttonsStyling: false
              });
            }
          },
          error: function (jqXHR) {
            let message = pageData.labels.anErrorDuringDeletion || 'An error occurred during deletion.';
            if (jqXHR.responseJSON?.message) { message = jqXHR.responseJSON.message; }
            Swal.fire({
              icon: 'error',
              title: pageData.labels.error || 'Error!',
              text: message,
              customClass: { confirmButton: 'btn btn-danger' },
              buttonsStyling: false
            });
          }
        });
      }
    });
  });


});
