<section class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6">
        <h1><?php echo $page_title; ?></h1>
        <p class="text-muted mb-0"><?php echo $page_subtitle; ?></p>
      </div>
      <div class="col-sm-6 text-right">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item"><a href="<?php echo site_url('dashboard'); ?>">Dashboard</a></li>
          <li class="breadcrumb-item active">Manajemen Absensi</li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">
    <div class="card card-danger card-outline">
      <div class="card-header">
        <h3 class="card-title"><i class="fa fa-filter mr-1"></i> Filter Data</h3>
      </div>
      <div class="card-body">
        <form id="form-filter" method="get" action="<?php echo site_url('transaksi/absensi'); ?>">
          <div class="row">
            <div class="col-sm-5">
              <div class="form-group">
                <label>Divisi</label>
                <select name="divisi" id="filter_divisi" class="form-control">
                  <option value="">-- Semua Divisi --</option>
                  <?php foreach ($divisi_list as $div): ?>
                    <option value="<?php echo $div->id_divisi; ?>" <?php echo ($f_divisi == $div->id_divisi) ? 'selected' : ''; ?>>
                      <?php echo html_escape($div->nama_divisi); ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
            <div class="col-sm-4">
              <div class="form-group">
                <label>Status</label>
                <select name="status" id="filter_status" class="form-control">
                  <option value="">-- Semua Status --</option>
                  <option value="SUDAH" <?php echo ($f_status === 'SUDAH') ? 'selected' : ''; ?>>Sudah Absen</option>
                  <option value="BELUM" <?php echo ($f_status === 'BELUM') ? 'selected' : ''; ?>>Belum Absen</option>
                </select>
              </div>
            </div>
            <div class="col-sm-3">
              <div class="form-group">
                <label>Periode Aktif</label>
                <div class="form-control bg-light d-flex align-items-center">
                  <i class="fa fa-calendar mr-2 text-muted"></i>
                  <?php echo bulan_indonesia($f_bulan) . ' ' . $f_tahun; ?>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
    <div class="card card-danger card-outline" id="sect-sudah">
      <div class="card-header d-flex align-items-center flex-wrap gap-2">
        <h3 class="card-title mr-auto"><i class="fa fa-calendar mr-1"></i> Rekap Kehadiran per Pegawai</h3>

        <div class="d-flex" style="gap: 12px;">
          <a href="<?php echo site_url('transaksi/absensi/tambah'); ?>" class="btn btn-danger btn-sm">
            <i class="fa fa-plus mr-1"></i> Tambah Manual
          </a>
          <a href="<?php echo site_url('transaksi/absensi/import'); ?>" class="btn btn-info btn-sm">
            <i class="fa fa-upload mr-1"></i> Import Excel
          </a>
          <button type="button" class="btn btn-warning btn-sm" id="btn-reset-absensi">
            <i class="fa fa-refresh mr-1"></i> Reset
          </button>
        </div>
      </div>
      <div class="card-body">
        <table id="tbl-absensi" class="table table-bordered table-hover table-striped">
          <thead>
            <tr>
              <th style="width:40px;">#</th>
              <th>NIP</th>
              <th>Nama Lengkap</th>
              <th>Divisi</th>
              <th style="text-align:center;" title="Hari masuk">Masuk</th>
              <th style="text-align:center;" title="Hari sakit">Sakit</th>
              <th style="text-align:center;" title="Hari cuti/izin">Cuti/Izin</th>
              <th style="text-align:center;" title="Hari libur">Libur</th>
              <th style="text-align:center;" title="Jumlah pengajuan lembur APPROVED pada periode ini">Lembur</th>
              <th style="text-align:center;" title="Kali terlambat (deteksi otomatis dari shift)">Terlambat</th>
              <th style="width:80px;">Aksi</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>
  </div>
</section>

<div class="modal fade" id="modal-detail-absensi" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable" role="document">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title"><i class="fa fa-calendar-check-o mr-1"></i> Detail Kehadiran</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="d-flex justify-content-between align-items-center flex-wrap mb-3">
          <div>
            <h5 class="mb-1" id="detail-pegawai-nama">-</h5>
            <p class="text-muted mb-0" id="detail-pegawai-meta">-</p>
          </div>
          <div class="badge badge-light border px-3 py-2" id="detail-periode-badge">-</div>
        </div>
        <div class="row mb-3" id="detail-summary">
          <div class="col-sm-4 mb-2 mb-sm-0">
            <div class="alert alert-secondary py-2 mb-0 text-center">
              <small class="d-block">Total Hari Periode</small>
              <strong id="sum-total-hari">0</strong>
            </div>
          </div>
          <div class="col-sm-4 mb-2 mb-sm-0">
            <div class="alert alert-success py-2 mb-0 text-center">
              <small class="d-block">Sudah Ada Record</small>
              <strong id="sum-hari-terisi">0</strong>
            </div>
          </div>
          <div class="col-sm-4">
            <div class="alert alert-danger py-2 mb-0 text-center">
              <small class="d-block">Belum Ada Record</small>
              <strong id="sum-hari-kosong">0</strong>
            </div>
          </div>
        </div>
        <div class="table-responsive">
          <table class="table table-bordered table-sm table-hover" id="tbl-detail-inline">
            <thead>
              <tr>
                <th style="width:120px;">Tanggal</th>
                <th style="width:90px;">Hari</th>
                <th style="width:140px;">Status</th>
                <th style="width:110px;">Info</th>
                <th style="width:120px;">Jam Masuk</th>
                <th style="width:120px;">Jam Keluar</th>
                <th>Keterangan</th>
                <th style="width:90px;">Aksi</th>
              </tr>
            </thead>
            <tbody id="detail-inline-body">
              <tr><td colspan="8" class="text-center text-muted py-4">Memuat data...</td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<style>
.row-attendance-empty {
  background-color: #fff1f1 !important;
}

.row-attendance-empty td {
  background-color: #fff1f1 !important;
}

#tbl-detail-inline .form-control {
  min-width: 100px;
}

#tbl-detail-inline tr.row-inline-empty td {
  background-color: #fff3f3 !important;
}

#tbl-detail-inline tr.row-inline-alpha td {
  background-color: #fff8f1 !important;
}

#tbl-detail-inline tr.row-inline-masuk td {
  background-color: #f3fff7 !important;
}

#tbl-detail-inline tr.row-system-holiday td {
  background-color: #f0f7ff !important;
  color: #666;
}

#tbl-detail-inline tr.row-system-holiday .form-control {
  background-color: #f5f5f5 !important;
  color: #999 !important;
}

#tbl-detail-inline tr.row-non-working-day td {
  background-color: #f9f9f9 !important;
  color: #999;
}

#tbl-detail-inline tr.row-non-working-day .form-control {
  background-color: #efefef !important;
  color: #bbb !important;
}

#tbl-detail-inline tr.row-non-working-day .btn-save-inline:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>

<script>
function initWhenJQueryReady(retryCount) {
  if (!window.jQuery) {
    if (retryCount < 50) {
      setTimeout(function () { initWhenJQueryReady(retryCount + 1); }, 100);
      return;
    }
    console.error('jQuery gagal dimuat. Script absensi tidak dijalankan.');
    return;
  }

  var $ = window.jQuery;
  var csrfTokenName = '<?php echo $this->security->get_csrf_token_name(); ?>';
  var csrfCookieName = '<?php echo $this->config->item('csrf_cookie_name'); ?>';
  var statusOptions = [
    { value: '', label: '-- Tidak Ada Record --' },
    { value: 'MASUK', label: 'MASUK' },
    { value: 'ALPHA', label: 'ALPHA' },
    { value: 'SAKIT', label: 'SAKIT' },
    { value: 'CUTI', label: 'CUTI' },
    { value: 'IZIN', label: 'IZIN' },
    { value: 'LIBUR', label: 'LIBUR' },
    { value: 'LEMBUR', label: 'LEMBUR' }
  ];

  function escapeHtml(value) {
    return $('<div>').text(value == null ? '' : value).html();
  }

  function readCookie(name) {
    var cookies = document.cookie ? document.cookie.split('; ') : [];
    for (var i = 0; i < cookies.length; i++) {
      var parts = cookies[i].split('=');
      var key = parts.shift();
      if (key === name) {
        return decodeURIComponent(parts.join('='));
      }
    }
    return '';
  }

  function buildStatusOptions(selected) {
    return statusOptions.map(function (option) {
      return '<option value="' + option.value + '"' + (selected === option.value ? ' selected' : '') + '>' + option.label + '</option>';
    }).join('');
  }

  function statusBadgeHtml(status) {
    var value = (status || '').toUpperCase();
    if (!value) {
      return '<span class="badge badge-secondary">Kosong</span>';
    }
    if (value === 'MASUK') {
      return '<span class="badge badge-success">MASUK</span>';
    }
    if (value === 'ALPHA') {
      return '<span class="badge badge-danger">ALPHA</span>';
    }
    if (value === 'SAKIT') {
      return '<span class="badge badge-warning">SAKIT</span>';
    }
    if (value === 'CUTI' || value === 'IZIN') {
      return '<span class="badge badge-info">' + value + '</span>';
    }
    if (value === 'LIBUR') {
      return '<span class="badge badge-secondary">LIBUR</span>';
    }
    if (value === 'LEMBUR') {
      return '<span class="badge badge-primary">LEMBUR</span>';
    }
    return '<span class="badge badge-light border">' + escapeHtml(value) + '</span>';
  }

  function applyDetailRowVisual($row) {
    var status = (($row.find('.field-status').val() || '') + '').toUpperCase();
    var isSystemHoliday = $row.data('is-system-holiday') === 1;
    var isExpectedWorkingDay = $row.data('is-expected-working-day') === 1;
    var hasRecord = $row.data('has-record') === 1;
    
    $row.removeClass('row-inline-empty row-inline-alpha row-inline-masuk row-system-holiday row-non-working-day');

    // Non-working days (Sabtu/Minggu tanpa jadwal kerja)
    if (!isSystemHoliday && !isExpectedWorkingDay && !hasRecord) {
      $row.addClass('row-non-working-day');
    } else if (isSystemHoliday) {
      $row.addClass('row-system-holiday');
    } else if (!status) {
      $row.addClass('row-inline-empty');
    } else if (status === 'ALPHA') {
      $row.addClass('row-inline-alpha');
    } else if (status === 'MASUK') {
      $row.addClass('row-inline-masuk');
    }

    $row.find('.cell-status-badge').html(statusBadgeHtml(status));
  }

  function refreshDetailSummary() {
    var total = $('#detail-inline-body tr[data-tanggal]').length;
    var filled = 0;

    $('#detail-inline-body tr[data-tanggal]').each(function () {
      var status = (($(this).find('.field-status').val() || '') + '').toUpperCase();
      if (status !== '') {
        filled++;
      }
    });

    $('#sum-total-hari').text(total);
    $('#sum-hari-terisi').text(filled);
    $('#sum-hari-kosong').text(Math.max(total - filled, 0));
  }

  function buildAbsensiTable() {
    if (!window.jQuery || !window.jQuery.fn || !window.jQuery.fn.DataTable) {
      console.error('DataTables library not loaded');
      return null;
    }

    return $('#tbl-absensi').DataTable({
    processing: true,
    serverSide: true,
    ajax: {
      url: '<?php echo site_url('transaksi/absensi/ajax_list'); ?>',
      type: 'GET',
      data: function (d) {
        d.tahun = '<?php echo $f_tahun; ?>';
        d.bulan = '<?php echo (int) $f_bulan; ?>';
        d.divisi = $('#filter_divisi').val();
        d.filter_status = $('#filter_status').val();
      },
      error: function (xhr) {
        console.error('Absensi ajax_list error:', xhr.status, xhr.responseText);
        Swal.fire({
          icon: 'error',
          title: 'Gagal Memuat Rekap Kehadiran',
          text: 'Silakan refresh halaman. Jika masih gagal, hubungi admin sistem.',
          confirmButtonColor: '#800000'
        });
      }
    },
    createdRow: function (row, data) {
      if (data.row_class) {
        $(row).addClass(data.row_class);
      }
    },
    columns: [
      { data: null, orderable: false, render: function (data, type, row, meta) { return meta.row + meta.settings._iDisplayStart + 1; } },
      { data: 'nip' },
      { data: 'nama_lengkap' },
      { data: 'nama_divisi' },
      { data: 'masuk', className: 'text-center', orderable: true },
      { data: 'sakit', className: 'text-center', orderable: true },
      { data: 'cuti_izin', className: 'text-center', orderable: false },
      { data: 'libur', className: 'text-center', orderable: true },
      { data: 'lembur', className: 'text-center', orderable: true },
      { data: 'terlambat', className: 'text-center', orderable: true },
      { data: 'aksi', className: 'text-center', orderable: false }
    ],
    language: {
      processing: 'Memuat...',
      search: 'Cari:',
      lengthMenu: 'Tampilkan _MENU_ data',
      info: 'Menampilkan _START_ sampai _END_ dari _TOTAL_ data',
      infoEmpty: 'Tidak ada data',
      infoFiltered: '(difilter dari _MAX_ data)',
      zeroRecords: 'Data tidak ditemukan',
      paginate: {
        first: 'Awal',
        last: 'Akhir',
        next: 'Berikutnya',
        previous: 'Sebelumnya'
      }
    },
    pageLength: 25,
    order: [[2, 'asc']]
  });
  }

  var table = buildAbsensiTable();
  if (!table) {
    setTimeout(function () {
      table = buildAbsensiTable();
    }, 300);
  }

  $('#filter_divisi, #filter_status').on('change', function () {
    if (table) {
      table.draw();
    }
  });

  $('#btn-reset-absensi').on('click', function () {
    var divisi = $('#filter_divisi').val() || '';
    var periodeLabel = '<?php echo html_escape((string) ($f_periode_label ?? '-')); ?>';
    var divisiLabel = $('#filter_divisi option:selected').text() || '-- Semua Divisi --';

    Swal.fire({
      icon: 'warning',
      title: 'Reset Data Absensi?',
      html: 'Periode: <b>' + escapeHtml(periodeLabel) + '</b><br>Filter Divisi: <b>' + escapeHtml(divisiLabel) + '</b><br><br>Data absensi sesuai filter akan dihapus.',
      showCancelButton: true,
      confirmButtonText: 'Ya, Reset',
      cancelButtonText: 'Batal',
      confirmButtonColor: '#f0ad4e'
    }).then(function (result) {
      if (!result.isConfirmed) {
        return;
      }

      var postData = {
        tahun: '<?php echo (int) $f_tahun; ?>',
        bulan: '<?php echo (int) $f_bulan; ?>',
        divisi: divisi
      };
      postData[csrfTokenName] = readCookie(csrfCookieName);

      $.ajax({
        url: '<?php echo site_url('transaksi/absensi/reset_periode'); ?>',
        type: 'POST',
        data: postData,
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      }).done(function (response) {
        if (!response.success) {
          Swal.fire({
            icon: 'error',
            title: 'Reset Ditolak',
            text: response.message || 'Reset gagal diproses.',
            confirmButtonColor: '#800000'
          });
          return;
        }

        Swal.fire({
          icon: response.needs_reprocess ? 'info' : 'success',
          title: 'Reset Berhasil',
          text: response.message || 'Data absensi berhasil direset.',
          confirmButtonColor: '#28a745'
        });

        if (table) {
          table.draw(false);
        }
      }).fail(function (xhr) {
        var message = 'Reset gagal diproses.';
        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }
        Swal.fire({ icon: 'error', title: 'Reset Gagal', text: message, confirmButtonColor: '#800000' });
      });
    });
  });

  function renderDetailRows(rows, pegawaiId) {
    if (!rows.length) {
      return '<tr><td colspan="8" class="text-center text-muted py-4">Tidak ada data periode ini.</td></tr>';
    }

    return rows.map(function (row) {
      var status = (row.status || '').toUpperCase();
      var rowClass = '';
      var isSystemHoliday = row.is_system_holiday === 1 || row.is_system_holiday === true;
      var isExpectedWorkingDay = row.is_expected_working_day === 1 || row.is_expected_working_day === true;
      var hasRecord = row.has_record === 1 || row.has_record === true;
        var isNonWorkingDay = !isSystemHoliday && !isExpectedWorkingDay && !hasRecord;
      
      if (isNonWorkingDay) {
        rowClass = 'row-non-working-day';
      } else if (isSystemHoliday) {
        rowClass = 'row-system-holiday';
      } else if (!status) {
        rowClass = 'row-inline-empty';
      } else if (status === 'ALPHA') {
        rowClass = 'row-inline-alpha';
      } else if (status === 'MASUK') {
        rowClass = 'row-inline-masuk';
      }

      // Disable inputs if system holiday; non-working days are read-only, expected working days are editable
      var statusFieldDisabled = isSystemHoliday ? ' disabled' : '';
      var jamFieldDisabled = isSystemHoliday ? ' disabled' : '';
      var saveButtonDisabled = isSystemHoliday ? ' disabled' : '';
      var keteranganTooltip = '';

      return '<tr class="' + rowClass + '" data-id-absensi="' + (row.id_absensi || '') + '" data-tanggal="' + row.tanggal + '" data-id-pegawai="' + pegawaiId + '" data-is-system-holiday="' + (isSystemHoliday ? 1 : 0) + '" data-is-expected-working-day="' + (isExpectedWorkingDay ? 1 : 0) + '" data-has-record="' + (hasRecord ? 1 : 0) + '">' +
        '<td>' + escapeHtml(row.tanggal) + '</td>' +
        '<td>' + escapeHtml(row.hari) + '</td>' +
        '<td><select class="form-control form-control-sm field-status"' + statusFieldDisabled + '>' + buildStatusOptions(row.status || '') + '</select></td>' +
        '<td class="cell-status-badge">' + statusBadgeHtml(status) + (isSystemHoliday ? ' <small class="badge badge-secondary">Sistem</small>' : '') + (isNonWorkingDay && !status ? ' <small class="badge badge-info">Tidak Jadwal</small>' : '') + '</td>' +
        '<td><input type="time" class="form-control form-control-sm field-jam-masuk" value="' + escapeHtml((row.jam_masuk || '').substring(0, 5)) + '"' + jamFieldDisabled + '></td>' +
        '<td><input type="time" class="form-control form-control-sm field-jam-keluar" value="' + escapeHtml((row.jam_keluar || '').substring(0, 5)) + '"' + jamFieldDisabled + '></td>' +
        '<td><input type="text" class="form-control form-control-sm field-keterangan" value="' + escapeHtml(row.keterangan || '') + '" placeholder="Keterangan"' + (isSystemHoliday ? ' disabled' : '') + keteranganTooltip + '></td>' +
        '<td class="text-center"><button type="button" class="btn btn-xs btn-danger btn-save-inline"' + saveButtonDisabled + '><i class="fa fa-save"></i></button></td>' +
      '</tr>';
    }).join('');
  }

  $(document).on('click', '.btn-detail-absensi', function () {
    var pegawaiId = $(this).data('id');
    $('#detail-inline-body').html('<tr><td colspan="7" class="text-center text-muted py-4">Memuat data...</td></tr>');
    $('#modal-detail-absensi').modal('show');

    $.ajax({
      url: '<?php echo site_url('transaksi/absensi/detail_json'); ?>/' + pegawaiId,
      type: 'GET',
      data: {
        tahun: '<?php echo $f_tahun; ?>',
        bulan: '<?php echo (int) $f_bulan; ?>'
      },
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    }).done(function (response) {
      if (!response.success) {
        Swal.fire({ icon: 'error', title: 'Gagal Memuat Detail', text: response.message || 'Data tidak ditemukan', confirmButtonColor: '#800000' });
        return;
      }

      $('#detail-pegawai-nama').text(response.pegawai.nama_lengkap);
      $('#detail-pegawai-meta').text(response.pegawai.nip + ' | ' + (response.pegawai.divisi || '-'));
      $('#detail-periode-badge').text('Periode ' + (response.periode && response.periode.label ? response.periode.label : '-'));
      $('#detail-inline-body').html(renderDetailRows(response.rows, response.pegawai.id_pegawai));
      $('#detail-inline-body tr[data-tanggal]').each(function () {
        applyDetailRowVisual($(this));
      });
      refreshDetailSummary();
    }).fail(function (xhr) {
      console.error('detail_json error', xhr.status, xhr.responseText);
      Swal.fire({ icon: 'error', title: 'Gagal Memuat Detail', text: 'Silakan coba lagi.', confirmButtonColor: '#800000' });
    });
  });

  $(document).on('change', '.field-status', function () {
    var $row = $(this).closest('tr');
    var value = (($(this).val() || '') + '').toUpperCase();
    if (!value) {
      $row.find('.field-jam-masuk').val('');
      $row.find('.field-jam-keluar').val('');
    }
    applyDetailRowVisual($row);
    refreshDetailSummary();
  });

  $(document).on('click', '.btn-save-inline', function () {
    var $button = $(this);
    var $row = $button.closest('tr');
    var isSystemHoliday = $row.data('is-system-holiday') === 1;
    var isExpectedWorkingDay = $row.data('is-expected-working-day') === 1;
    var hasRecord = $row.data('has-record') === 1;
    var isNonWorkingDay = !isSystemHoliday && !isExpectedWorkingDay && !hasRecord;
    
    // Check if this is a system holiday (should not be editable)
    if (isSystemHoliday) {
      Swal.fire({
        icon: 'info',
        title: 'Hari Libur Sistem',
        text: 'Tanggal ini adalah hari libur yang ditentukan dalam kalender. Data ini tidak dapat diubah.',
        confirmButtonColor: '#007bff'
      });
      return;
    }
    
    // Check if this is a non-working day (warn user but allow if they proceed)
    if (isNonWorkingDay) {
      var status = (($row.find('.field-status').val() || '') + '').toUpperCase();
      if (!status) {
        Swal.fire({
          icon: 'warning',
          title: 'Bukan Hari Kerja',
          text: 'Tanggal ini bukan hari kerja menurut jadwal kerja. Jika ingin menambahkan data, pilih status terlebih dahulu.',
          confirmButtonColor: '#007bff'
        });
        return;
      }
    }
    var postData = {
      id_absensi: $row.data('id-absensi') || '',
      id_pegawai: $row.data('id-pegawai'),
      tanggal: $row.data('tanggal'),
      status: $row.find('.field-status').val(),
      jam_masuk: $row.find('.field-jam-masuk').val(),
      jam_keluar: $row.find('.field-jam-keluar').val(),
      keterangan: $row.find('.field-keterangan').val()
    };
    postData[csrfTokenName] = readCookie(csrfCookieName);

    $button.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');

    $.ajax({
      url: '<?php echo site_url('transaksi/absensi/simpan_inline'); ?>',
      type: 'POST',
      data: postData,
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    }).done(function (response) {
      if (!response.success) {
        Swal.fire({ icon: 'error', title: 'Gagal Menyimpan', text: response.message || 'Perubahan tidak dapat disimpan', confirmButtonColor: '#800000' });
        return;
      }

      var data = response.data || {};
      $row.attr('data-id-absensi', data.id_absensi || '');
      applyDetailRowVisual($row);
      refreshDetailSummary();

      Swal.fire({ icon: 'success', title: 'Tersimpan', text: response.message, timer: 1200, showConfirmButton: false });
      if (table) {
        table.draw(false);
      }
    }).fail(function (xhr) {
      var message = 'Perubahan tidak dapat disimpan';
      if (xhr.status === 403) {
        message = 'Token keamanan kadaluarsa. Silakan refresh halaman lalu coba simpan lagi.';
      }
      if (xhr.responseJSON && xhr.responseJSON.message) {
        message = xhr.responseJSON.message;
      }
      Swal.fire({ icon: 'error', title: 'Gagal Menyimpan', text: message, confirmButtonColor: '#800000' });
    }).always(function () {
      $button.prop('disabled', false).html('<i class="fa fa-save"></i>');
    });
  });
}

initWhenJQueryReady(0);
</script>
