<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; ?> - Status: <strong><?php echo $periode->status; ?></strong></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"><a href="<?php echo site_url('transaksi/payroll'); ?>">Sistem Payroll</a></li>
          <li class="breadcrumb-item active">Detail</li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">
    <div class="card card-danger card-outline">
      <div class="card-header d-flex align-items-center">
        <h3 class="card-title mr-auto"><i class="fa fa-table mr-1"></i> Preview Payroll Pegawai</h3>
        <a href="<?php echo site_url('transaksi/payroll'); ?>" class="btn btn-secondary btn-sm"><i class="fa fa-arrow-left mr-1"></i> Kembali</a>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table id="tbl-payroll-detail" class="table table-bordered table-hover table-striped" style="width:100%">
            <thead>
              <tr>
                <th style="width:40px;">#</th>
                <th>NIP</th>
                <th>Nama Pegawai</th>
                <th>Divisi</th>
                <th style="text-align:right;">Gaji Pokok</th>
                <th style="text-align:right;">Tunjangan</th>
                <th style="text-align:right;">Lembur</th>
                <th style="text-align:right;">Potongan</th>
                <th style="text-align:right;">Gaji Neto</th>
                <th style="width:80px;">Aksi</th>
              </tr>
            </thead>
          </table>
        </div>
        <div class="alert alert-warning mt-3 mb-0" id="payroll-empty-warning" style="display:none;">
          <i class="fa fa-info-circle mr-1"></i> Belum ada hasil payroll untuk periode ini. Klik Proses pada halaman daftar periode.
        </div>
      </div>
    </div>
  </div>
</section>

<div class="modal fade" id="modal-detail-komponen" 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-list-alt mr-1"></i> Rincian Komponen Gaji</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-komponen-nama">-</h5>
            <p class="text-muted mb-0" id="detail-komponen-meta">-</p>
          </div>
          <div class="text-right">
            <div class="badge badge-light border px-3 py-2 mb-2" id="detail-komponen-periode">-</div>
            <div>
              <button type="button" class="btn btn-sm btn-success" id="btn-add-adjustment" style="display:none;width: stretch !important;">
                <i class="fa fa-plus mr-1"></i> Tambah Penyesuaian
              </button>
            </div>
          </div>
        </div>

        <div class="alert alert-info py-2 mb-3" id="adjustment-lock-note" style="display:none;">
          <i class="fa fa-lock mr-1"></i> Penyesuaian hanya bisa dilakukan saat status periode <strong>PROCESSED</strong>.
        </div>

        <div class="row mb-3">
          <div class="col-sm-6 col-lg-2 mb-2 mb-lg-0">
            <div class="alert alert-secondary py-2 mb-0 text-center">
              <small class="d-block">Gaji Pokok</small>
              <strong id="sum-gapok">Rp 0</strong>
            </div>
          </div>
          <div class="col-sm-6 col-lg-2 mb-2 mb-lg-0">
            <div class="alert alert-success py-2 mb-0 text-center">
              <small class="d-block">Tunjangan</small>
              <strong id="sum-tunjangan">Rp 0</strong>
            </div>
          </div>
          <div class="col-sm-6 col-lg-2 mb-2 mb-lg-0">
            <div class="alert alert-primary py-2 mb-0 text-center">
              <small class="d-block">Lembur</small>
              <strong id="sum-lembur">Rp 0</strong>
            </div>
          </div>
          <div class="col-sm-6 col-lg-2 mb-2 mb-lg-0">
            <div class="alert alert-danger py-2 mb-0 text-center">
              <small class="d-block">Potongan</small>
              <strong id="sum-potongan">Rp 0</strong>
            </div>
          </div>
          <div class="col-sm-12 col-lg-4">
            <div class="alert alert-dark py-2 mb-0 text-center">
              <small class="d-block">Gaji Neto</small>
              <strong id="sum-neto">Rp 0</strong>
            </div>
          </div>
        </div>

        <div class="table-responsive">
          <table class="table table-bordered table-sm table-hover" id="tbl-komponen-detail">
            <thead>
              <tr>
                <th style="width:120px;">Jenis</th>
                <th>Komponen</th>
                <th style="width:110px;">Tipe Nilai</th>
                <th style="width:110px;">Jumlah Hari</th>
                <th style="width:130px;">Sumber</th>
                <th>Catatan</th>
                <th style="width:170px; text-align:right;">Nilai</th>
                <th style="width:130px; text-align:center;">Aksi</th>
              </tr>
            </thead>
            <tbody id="detail-komponen-body">
              <tr><td colspan="8" class="text-center text-muted py-4">Pilih data payroll untuk melihat rincian.</td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

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

  var $ = window.jQuery;

  if (!$.fn || !$.fn.DataTable) {
    console.error('DataTables belum tersedia di halaman detail payroll');
    return;
  }

  var idPeriode = <?php echo (int) $id_periode; ?>;
  var csrfTokenName = '<?php echo $this->security->get_csrf_token_name(); ?>';
  var csrfCookieName = '<?php echo $this->config->item('csrf_cookie_name'); ?>';
  var currentPayrollId = 0;
  var currentCanAdjust = false;

  function getCookie(name) {
    var escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    var match = document.cookie.match(new RegExp('(?:^|; )' + escaped + '=([^;]*)'));
    return match ? decodeURIComponent(match[1]) : '';
  }

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

  function badgeJenis(jenis) {
    var key = ((jenis || '') + '').toUpperCase();
    if (key === 'TUNJANGAN') {
      return '<span class="badge badge-success">TUNJANGAN</span>';
    }
    if (key === 'POTONGAN') {
      return '<span class="badge badge-danger">POTONGAN</span>';
    }
    return '<span class="badge badge-secondary">' + escapeHtml(key || '-') + '</span>';
  }

  function badgeSumber(sumber) {
    var key = ((sumber || '') + '').toUpperCase();
    if (key === 'FORMULA') {
      return '<span class="badge badge-primary">FORMULA</span>';
    }
    if (key === 'PER_HARI') {
      return '<span class="badge badge-info">PER_HARI</span>';
    }
    if (key === 'LEMBUR_APPROVED') {
      return '<span class="badge badge-warning">LEMBUR</span>';
    }
    if (key === 'SYSTEM_DEFAULT') {
      return '<span class="badge badge-secondary">DEFAULT</span>';
    }
    if (key === 'CUSTOM_MANUAL') {
      return '<span class="badge badge-dark">CUSTOM</span>';
    }
    return '<span class="badge badge-light border">' + escapeHtml(key || '-') + '</span>';
  }

  function parseCurrencyInput(value) {
    var cleaned = String(value || '').replace(/[^0-9.-]/g, '');
    var parsed = parseFloat(cleaned);
    return isNaN(parsed) ? 0 : parsed;
  }

  function applySummary(summary) {
    summary = summary || {};
    $('#sum-gapok').text(summary.gaji_pokok_text || 'Rp 0');
    $('#sum-tunjangan').text(summary.total_tunjangan_text || 'Rp 0');
    $('#sum-lembur').text(summary.total_lembur_text || 'Rp 0');
    $('#sum-potongan').text(summary.total_potongan_text || 'Rp 0');
    $('#sum-neto').text(summary.gaji_neto_text || 'Rp 0');
  }

  function renderKomponenRows(komponen) {
    if (!komponen || !komponen.length) {
      $('#detail-komponen-body').html('<tr><td colspan="8" class="text-center text-muted py-4">Tidak ada rincian komponen.</td></tr>');
      return;
    }

    var html = '';
    $.each(komponen, function (_, item) {
      var isEditable = !!item.is_editable && currentCanAdjust;
      if (isEditable) {
        html += '<tr class="row-adjustment-custom" data-adjustment-id="' + (item.id_adjustment || '') + '">' +
          '<td><select class="form-control form-control-sm field-jenis"><option value="TUNJANGAN"' + (item.jenis === 'TUNJANGAN' ? ' selected' : '') + '>TUNJANGAN</option><option value="POTONGAN"' + (item.jenis === 'POTONGAN' ? ' selected' : '') + '>POTONGAN</option></select></td>' +
          '<td><input type="text" class="form-control form-control-sm field-nama" value="' + escapeHtml(item.nama_komponen || '') + '" maxlength="100"></td>' +
          '<td>NOMINAL</td>' +
          '<td class="text-center">-</td>' +
          '<td>' + badgeSumber(item.sumber) + '</td>' +
          '<td><input type="text" class="form-control form-control-sm field-catatan" value="' + escapeHtml(item.catatan || '') + '" maxlength="255" placeholder="Opsional"></td>' +
          '<td><input type="number" min="0" step="0.01" class="form-control form-control-sm field-nilai text-right" value="' + escapeHtml(item.nilai || 0) + '"></td>' +
          '<td class="text-center"><button type="button" class="btn btn-xs btn-danger btn-save-adjustment" title="Simpan"><i class="fa fa-save"></i></button> <button type="button" class="btn btn-xs btn-secondary btn-delete-adjustment" title="Hapus"><i class="fa fa-trash"></i></button></td>' +
        '</tr>';
      } else {
        html += '<tr>' +
          '<td>' + badgeJenis(item.jenis) + '</td>' +
          '<td>' + escapeHtml(item.nama_komponen || '-') + '</td>' +
          '<td>' + escapeHtml(item.tipe_nilai || '-') + '</td>' +
          '<td class="text-center">' + (item.jumlah_hari === null ? '-' : parseInt(item.jumlah_hari, 10)) + '</td>' +
          '<td>' + badgeSumber(item.sumber) + '</td>' +
          '<td>' + escapeHtml(item.catatan || '-') + '</td>' +
          '<td class="text-right">' + escapeHtml(item.nilai_text || 'Rp 0') + '</td>' +
          '<td class="text-center"><span class="text-muted">-</span></td>' +
        '</tr>';
      }
    });

    $('#detail-komponen-body').html(html);
  }

  function renderDraftAdjustmentRow() {
    var row = '<tr class="row-adjustment-custom row-adjustment-draft" data-adjustment-id="">' +
      '<td><select class="form-control form-control-sm field-jenis"><option value="TUNJANGAN">TUNJANGAN</option><option value="POTONGAN">POTONGAN</option></select></td>' +
      '<td><input type="text" class="form-control form-control-sm field-nama" maxlength="100" placeholder="Nama komponen custom"></td>' +
      '<td>NOMINAL</td>' +
      '<td class="text-center">-</td>' +
      '<td>' + badgeSumber('CUSTOM_MANUAL') + '</td>' +
      '<td><input type="text" class="form-control form-control-sm field-catatan" maxlength="255" placeholder="Opsional"></td>' +
      '<td><input type="number" min="0" step="0.01" class="form-control form-control-sm field-nilai text-right" value="0"></td>' +
      '<td class="text-center"><button type="button" class="btn btn-xs btn-danger btn-save-adjustment" title="Simpan"><i class="fa fa-save"></i></button> <button type="button" class="btn btn-xs btn-secondary btn-cancel-adjustment" title="Batal"><i class="fa fa-times"></i></button></td>' +
    '</tr>';

    $('#detail-komponen-body').prepend(row);
  }

  var table = $('#tbl-payroll-detail').DataTable({
    processing: true,
    serverSide: true,
    ajax: {
      url: '<?php echo site_url('transaksi/payroll/ajax_detail_list'); ?>/' + idPeriode,
      type: 'POST',
      data: function (d) {
        d[csrfTokenName] = getCookie(csrfCookieName);
      },
      dataSrc: function (json) {
        var total = parseInt(json.recordsTotal || 0, 10);
        $('#payroll-empty-warning').toggle(total === 0);
        return json.data || [];
      },
      error: function (xhr) {
        console.error('Payroll detail ajax error:', xhr.status, xhr.responseText);
        Swal.fire({
          icon: 'error',
          title: 'Gagal Memuat Detail Payroll',
          text: 'Silakan refresh halaman. Jika masih gagal, hubungi admin sistem.',
          confirmButtonColor: '#800000'
        });
      }
    },
    columns: [
      {
        data: null,
        orderable: false,
        render: function (data, type, row, meta) {
          return meta.row + meta.settings._iDisplayStart + 1;
        }
      },
      { data: 'nip', render: function (data) { return '<code>' + escapeHtml(data) + '</code>'; } },
      { data: 'nama_lengkap' },
      { data: 'nama_divisi' },
      { data: 'gaji_pokok_text', className: 'text-right' },
      { data: 'total_tunjangan_text', className: 'text-right' },
      { data: 'total_lembur_text', className: 'text-right' },
      { data: 'total_potongan_text', className: 'text-right' },
      { data: 'gaji_neto_text', className: 'text-right' },
      { data: 'aksi', orderable: false, className: 'text-center' }
    ],
    pageLength: 25,
    order: [[2, 'asc']],
    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'
      }
    }
  });

  $(document).on('click', '.btn-detail-komponen', function () {
    var idPayroll = $(this).data('id');
    currentPayrollId = parseInt(idPayroll, 10) || 0;
    $('#detail-komponen-body').html('<tr><td colspan="8" class="text-center text-muted py-4">Memuat data...</td></tr>');
    $('#modal-detail-komponen').modal('show');

    $.ajax({
      url: '<?php echo site_url('transaksi/payroll/detail_komponen_json'); ?>/' + idPeriode + '/' + idPayroll,
      type: 'GET',
      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;
      }

      var payroll = response.payroll || {};
      var periode = response.periode || {};
      var summary = response.summary || {};
      var komponen = response.komponen || [];
      currentCanAdjust = !!response.can_adjust;
      var adjustmentMessage = response.adjustment_message || 'Penyesuaian hanya bisa dilakukan saat status periode PROCESSED.';

      $('#detail-komponen-nama').text(payroll.nama_lengkap || '-');
      $('#detail-komponen-meta').text((payroll.nip || '-') + ' | ' + (payroll.divisi || '-') + ' | ' + (payroll.jabatan || '-'));
      $('#detail-komponen-periode').text('Periode ' + (periode.bulan || '--') + '/' + (periode.tahun || '----') + ' - ' + (periode.status || '-'));

      applySummary(summary);
      renderKomponenRows(komponen);
      $('#btn-add-adjustment').toggle(currentCanAdjust);
      $('#adjustment-lock-note').toggle(!currentCanAdjust);
      $('#adjustment-lock-note').html('<i class="fa fa-lock mr-1"></i> ' + escapeHtml(adjustmentMessage));
    }).fail(function (xhr) {
      console.error('detail_komponen_json error:', xhr.status, xhr.responseText);
      Swal.fire({
        icon: 'error',
        title: 'Gagal Memuat Detail',
        text: 'Silakan coba lagi.',
        confirmButtonColor: '#800000'
      });
    });
  });

  $('#btn-add-adjustment').on('click', function () {
    if (!currentCanAdjust) {
      return;
    }
    if ($('#detail-komponen-body .row-adjustment-draft').length > 0) {
      return;
    }
    renderDraftAdjustmentRow();
  });

  $(document).on('click', '.btn-cancel-adjustment', function () {
    $(this).closest('tr').remove();
  });

  $(document).on('click', '.btn-save-adjustment', function () {
    if (!currentCanAdjust) {
      Swal.fire({ icon: 'warning', title: 'Periode Terkunci', text: 'Penyesuaian hanya diizinkan saat status PROCESSED.', confirmButtonColor: '#800000' });
      return;
    }

    var $button = $(this);
    var $row = $button.closest('tr');
    var payload = {
      id_periode: idPeriode,
      id_payroll: currentPayrollId,
      id_adjustment: $row.data('adjustment-id') || '',
      jenis: $row.find('.field-jenis').val(),
      nama_komponen: ($row.find('.field-nama').val() || '').trim(),
      nilai: parseCurrencyInput($row.find('.field-nilai').val()),
      catatan: ($row.find('.field-catatan').val() || '').trim()
    };
    payload[csrfTokenName] = getCookie(csrfCookieName);

    if (!payload.nama_komponen || payload.nama_komponen.length < 3) {
      Swal.fire({ icon: 'warning', title: 'Validasi', text: 'Nama komponen minimal 3 karakter.', confirmButtonColor: '#800000' });
      return;
    }

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

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

      applySummary(response.summary || {});
      renderKomponenRows(response.komponen || []);
      table.ajax.reload(null, false);
      Swal.fire({ icon: 'success', title: 'Tersimpan', text: response.message || 'Penyesuaian berhasil disimpan.', timer: 1300, showConfirmButton: false });
    }).fail(function (xhr) {
      console.error('adjustment_save error:', xhr.status, xhr.responseText);
      Swal.fire({ icon: 'error', title: 'Gagal Menyimpan', text: 'Silakan coba lagi.', confirmButtonColor: '#800000' });
    }).always(function () {
      $button.prop('disabled', false).html('<i class="fa fa-save"></i>');
    });
  });

  $(document).on('click', '.btn-delete-adjustment', function () {
    if (!currentCanAdjust) {
      return;
    }

    var $button = $(this);
    var $row = $button.closest('tr');
    var idAdjustment = parseInt($row.data('adjustment-id'), 10) || 0;
    if (idAdjustment < 1) {
      $row.remove();
      return;
    }

    Swal.fire({
      title: 'Hapus Penyesuaian?',
      text: 'Data penyesuaian custom akan dihapus dari payroll pegawai ini.',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Ya, hapus',
      cancelButtonText: 'Batal',
      confirmButtonColor: '#800000'
    }).then(function (result) {
      if (!result.isConfirmed) {
        return;
      }

      var payload = {
        id_periode: idPeriode,
        id_payroll: currentPayrollId,
        id_adjustment: idAdjustment
      };
      payload[csrfTokenName] = getCookie(csrfCookieName);

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

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

        applySummary(response.summary || {});
        renderKomponenRows(response.komponen || []);
        table.ajax.reload(null, false);
        Swal.fire({ icon: 'success', title: 'Terhapus', text: response.message || 'Penyesuaian berhasil dihapus.', timer: 1200, showConfirmButton: false });
      }).fail(function (xhr) {
        console.error('adjustment_delete error:', xhr.status, xhr.responseText);
        Swal.fire({ icon: 'error', title: 'Gagal Menghapus', text: 'Silakan coba lagi.', confirmButtonColor: '#800000' });
      }).always(function () {
        $button.prop('disabled', false).html('<i class="fa fa-trash"></i>');
      });
    });
  });
}

initWhenJQueryReady(0);
</script>
