/**
 * Page User List
 */

'use strict';

// Datatable (js)
document.addEventListener('DOMContentLoaded', function (e) {
  let borderColor, bodyBg, headingColor;

  borderColor = config.colors.borderColor;
  bodyBg = config.colors.bodyBg;
  headingColor = config.colors.headingColor;

  // Variable declaration for table
  const dt_user_table = document.querySelector('.datatables-users'),
    userView = 'app-user-view-account.html',
    statusObj = {
      1: { title: 'Pending', class: 'bg-label-warning' },
      2: { title: 'Active', class: 'bg-label-success' },
      3: { title: 'Inactive', class: 'bg-label-secondary' }
    };
  var select2 = $('.select2');

  if (select2.length) {
    var $this = select2;
    $this.wrap('<div class="position-relative"></div>').select2({
      placeholder: 'Select Country',
      dropdownParent: $this.parent()
    });
  }

  if (dt_user_table) {
      const dt_user = new DataTable(dt_user_table, {
        ajax: kabupatenKotaListUrl,
        columns: [
            { data: 'id' },
            { data: 'id' },
            { data: 'kode_kabupaten_kota' }, 
            { data: 'nama_kabupaten_kota' }, 
            { data: 'nama_provinsi' },
            { data: null, defaultContent: '' }
        ],
        columnDefs: [
            {
                targets: 0,
                className: 'control',
                searchable: false,
                orderable: false,
                render: function() { return ''; }
            },
            {
                targets: 1,
                orderable: false,
                checkboxes: {
                    selectAllRender: '<input type="checkbox" class="form-check-input">'
                },
                render: function() {
                    return '<input type="checkbox" class="dt-checkboxes form-check-input">';
                }
            },
            {
                targets: 2,
                render: function (data, type, full, meta) {
                    return '<span class="text-truncate d-flex align-items-center text-heading">' + full['kode_kabupaten_kota'] + '</span>';
                }
            },
            {
                targets: 3,
                render: function (data, type, full, meta) {
                    return '<span class="text-truncate d-flex align-items-center text-heading">' + full['nama_kabupaten_kota'] + '</span>';
                }
            },
            {
                targets: 4,
                render: function (data, type, full, meta) {
                    return '<span class="text-truncate d-flex align-items-center text-heading">' + full['nama_provinsi'] + '</span>';
                }
            },
            {
                targets: -1,
                title: 'Actions',
                searchable: false,
                orderable: false,
                render: function (data, type, full, meta) {
                    return `
                        <div class="d-flex align-items-center">
                            <a href="javascript:;" class="btn btn-icon btn-text-secondary waves-effect waves-light rounded-pill delete-record"><i class="ti tabler-trash ti-md"></i></a>
                            <a href="javascript:;" class="btn btn-icon btn-text-secondary waves-effect waves-light rounded-pill"><i class="ti tabler-eye ti-md"></i></a>
                        </div>`;
                }
            }
        ],
        order: [[3, 'asc']],
        layout: {
            topStart: {
                rowClass: 'row m-3 my-0 justify-content-between',
                features: [
                    {
                        pageLength: {
                            menu: [10, 25, 50, 100],
                            text: '_MENU_'
                        }
                    }
                ]
            },
            topEnd: {
                features: [
                    {
                        search: {
                            placeholder: 'Search User',
                            text: '_INPUT_'
                        }
                    },
                    {
                        buttons: [
                            {
                                text: '<i class="ti tabler-plus me-0 me-sm-1 ti-xs"></i><span class="d-none d-sm-inline-block">Tambah Kabupaten/Kota</span>',
                                className: 'add-new btn btn-primary ms-2 waves-effect waves-light',
                                attr: {
                                    'data-bs-toggle': 'offcanvas',
                                    'data-bs-target': '#offcanvasAddKabupatenKota'
                                }
                            }
                        ]
                    }
                ]
            },
            bottomStart: {
                rowClass: 'row mx-3 justify-content-between',
                features: ['info']
            },
            bottomEnd: {
                rowClass: 'row mx-3 justify-content-between',
                features: ['paging']
            }
        }
    });
  }

  // Filter form control to default size
  // ? setTimeout used for user-list table initialization
  setTimeout(() => {
    const elementsToModify = [
      { selector: '.dt-buttons .btn', classToRemove: 'btn-secondary' },
      { selector: '.dt-search .form-control', classToRemove: 'form-control-sm' },
      { selector: '.dt-length .form-select', classToRemove: 'form-select-sm', classToAdd: 'ms-0' },
      { selector: '.dt-length', classToAdd: 'mb-md-6 mb-0' },
      {
        selector: '.dt-layout-end',
        classToRemove: 'justify-content-between',
        classToAdd: 'd-flex gap-md-4 justify-content-md-between justify-content-center gap-2 flex-wrap'
      },
      { selector: '.dt-buttons', classToAdd: 'd-flex gap-4 mb-md-0 mb-4' },
      { selector: '.dt-layout-table', classToRemove: 'row mt-2' },
      { selector: '.dt-layout-full', classToRemove: 'col-md col-12', classToAdd: 'table-responsive' }
    ];

    // Delete record
    elementsToModify.forEach(({ selector, classToRemove, classToAdd }) => {
      document.querySelectorAll(selector).forEach(element => {
        if (classToRemove) {
          classToRemove.split(' ').forEach(className => element.classList.remove(className));
        }
        if (classToAdd) {
          classToAdd.split(' ').forEach(className => element.classList.add(className));
        }
      });
    });
  }, 100);

  // Validation & Phone mask
  const phoneMaskList = document.querySelectorAll('.phone-mask'),
    addNewUserForm = document.getElementById('addNewUserForm');

  // Phone Number
  if (phoneMaskList) {
    phoneMaskList.forEach(function (phoneMask) {
      phoneMask.addEventListener('input', event => {
        const cleanValue = event.target.value.replace(/\D/g, '');
        phoneMask.value = formatGeneral(cleanValue, {
          blocks: [3, 3, 4],
          delimiters: [' ', ' ']
        });
      });
      registerCursorTracker({
        input: phoneMask,
        delimiter: ' '
      });
    });
  }
  // Add New User Form Validation
  const fv = FormValidation.formValidation(addNewUserForm, {
    fields: {
      userFullname: {
        validators: {
          notEmpty: {
            message: 'Please enter fullname '
          }
        }
      },
      userEmail: {
        validators: {
          notEmpty: {
            message: 'Please enter your email'
          },
          emailAddress: {
            message: 'The value is not a valid email address'
          }
        }
      }
    },
    plugins: {
      trigger: new FormValidation.plugins.Trigger(),
      bootstrap5: new FormValidation.plugins.Bootstrap5({
        // Use this for enabling/changing valid/invalid class
        eleValidClass: '',
        rowSelector: function (field, ele) {
          // field is the field name & ele is the field element
          return '.form-control-validation';
        }
      }),
      submitButton: new FormValidation.plugins.SubmitButton(),
      // Submit the form when all fields are valid
      // defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
      autoFocus: new FormValidation.plugins.AutoFocus()
    }
  });
});

$('.datatables-users tbody').on('click', '.verify-user', function () {
    const userId = $(this).data('id');
    const currentStatus = $(this).data('status'); // 1 = Active, 2 = Pending
    const actionText = (currentStatus === 1) ? 'menonaktifkan (set Pending)' : 'mengaktifkan';

    if (confirm('Apakah Anda yakin ingin ' + actionText + ' user ini?')) {
        $.ajax({
            url: '/users/' + userId + '/verify',
            type: 'POST',
            data: {
                _token: $('meta[name="csrf-token"]').attr('content'),
                _method: 'PATCH'
            },
            success: function (response) {
                // Reload tabel tanpa reset posisi pagination (false)
                $('.datatables-users').DataTable().ajax.reload(null, false);
                
                // Opsional: Notifikasi kecil di pojok (jika pakai library toastr)
                // toastr.success('Status berhasil diperbarui');
            },
            error: function (xhr) {
                alert('Gagal mengubah status user.');
            }
        });
    }
});