/* ============================================================
   app.js — DataTables init + helpers
   ============================================================ */

$(function () {

  const dtLang = {
    search:            '',
    searchPlaceholder: 'Cari data...',
    lengthMenu:        'Tampilkan _MENU_ baris',
    info:              'Menampilkan _START_–_END_ dari _TOTAL_ data',
    infoEmpty:         'Tidak ada data',
    infoFiltered:      '(dari _MAX_ total)',
    zeroRecords:       'Data tidak ditemukan',
    emptyTable:        'Belum ada data',
    paginate: { first:'«', last:'»', next:'›', previous:'‹' },
  };

  $('.dt-table').each(function () {
    const $tbl = $(this);

    // Parse data-order — support format: [[0,"desc"]] atau [[0,'desc']]
    let order = [[0, 'asc']];
    const rawOrder = $tbl.attr('data-order');
    if (rawOrder) {
      try {
        // Normalize single quotes to double quotes untuk JSON.parse
        order = JSON.parse(rawOrder.replace(/'/g, '"'));
      } catch (e) {
        // Fallback: parse manual format [[col,'dir']]
        const m = rawOrder.match(/\[(\d+)\s*,\s*['"](\w+)['"]\]/);
        if (m) order = [[parseInt(m[1]), m[2]]];
      }
    }

    // Parse data-nosort: comma-separated
    const noSort = ($tbl.attr('data-nosort') || '')
      .split(',').map(s => s.trim()).filter(Boolean).map(Number);

    const pgLen = parseInt($tbl.attr('data-pglength') || '10', 10);

    $tbl.DataTable({
      language:   dtLang,
      order:      order,
      pageLength: pgLen,
      lengthMenu: [[5,10,25,50,100,-1],[5,10,25,50,100,'Semua']],
      columnDefs: noSort.length ? [{orderable:false, targets:noSort}] : [],
      dom: '<"dt-top"lf>rt<"dt-bottom"ip>',
    });
  });

  // Auto-dismiss flash alert
  setTimeout(function () {
    $('.alert-dismissible').fadeTo(400, 0, function () {
      $(this).slideUp(200, function () { $(this).remove(); });
    });
  }, 4000);

});
