<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"><a href="<?php echo site_url('master/mapping_komponen'); ?>">Mapping Gaji</a></li>
          <li class="breadcrumb-item active"><?php echo html_escape($pegawai->nama_lengkap); ?></li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">

    <!-- Info Pegawai -->
    <div class="callout callout-danger mb-3">
      <div class="row">
        <div class="col-md-6">
          <strong><i class="fa fa-user mr-1"></i> <?php echo html_escape($pegawai->nama_lengkap); ?></strong>
          &nbsp;<code><?php echo html_escape($pegawai->nip); ?></code>
        </div>
        <div class="col-md-6 text-right text-muted">
          <?php echo html_escape($pegawai->nama_divisi ?? '-'); ?> &bull;
          <?php echo html_escape($pegawai->nama_jabatan ?? '-'); ?>
        </div>
      </div>
    </div>

    <?php echo form_open(site_url('master/mapping_komponen/pegawai/' . $pegawai->id_pegawai), ['id' => 'form-mapping']); ?>

    <!-- GAPOK khusus -->
    <?php
      $gapok = null;
      $komponen_lain = [];
      foreach ($list_komponen as $k) {
        if (strtoupper($k->kode_komponen) === 'GAPOK') { $gapok = $k; }
        else { $komponen_lain[] = $k; }
      }
    ?>

    <?php if ($gapok): ?>
    <div class="card card-danger">
      <div class="card-header bg-gradient-danger text-white">
        <h3 class="card-title" style="color: white;"><i class="fa fa-money mr-1"></i> Gaji Pokok</h3>
      </div>
      <div class="card-body">
        <div class="row align-items-center">
          <div class="col-md-4">
            <label class="text-bold mb-0">Nominal Gaji Pokok <span class="text-danger">*</span></label>
            <small class="d-block text-muted">Nilai default sistem: Rp <?php echo rupiah($gapok->nilai_default); ?></small>
          </div>
          <div class="col-md-4">
            <div class="input-group">
              <div class="input-group-prepend"><span class="input-group-text">Rp</span></div>
              <input type="text"
                     class="form-control inp-rupiah"
                     name="gapok_nominal"
                     value="<?php echo (float)$pegawai->gaji_pokok > 0 ? number_format((float)$pegawai->gaji_pokok, 0, ',', '.') : ''; ?>"
                     placeholder="Wajib diisi">
            </div>
            <input type="hidden" name="aktif[<?php echo (int) $gapok->id_komponen; ?>]" value="1">
          </div>
          <div class="col-md-4">
            <input type="text"
                   class="form-control"
                   name="catatan[<?php echo (int) $gapok->id_komponen; ?>]"
                   value="<?php echo html_escape($gapok->catatan ?? ''); ?>"
                   placeholder="Catatan (opsional)">
          </div>
        </div>
        <?php if ((float)$pegawai->gaji_pokok > 0): ?>
        <small class="text-success d-block mt-2">
          <i class="fa fa-check-circle"></i> Gaji pokok saat ini: <strong>Rp <?php echo rupiah($pegawai->gaji_pokok); ?></strong>
        </small>
        <?php else: ?>
        <small class="text-danger d-block mt-2">
          <i class="fa fa-exclamation-circle"></i> Gaji pokok belum diset. Wajib diisi agar payroll dapat dihitung.
        </small>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Komponen lainnya -->
    <div class="card card-danger card-outline">
      <div class="card-header">
        <h3 class="card-title"><i class="fa fa-list-alt mr-1"></i> Tunjangan & Potongan</h3>
      </div>
      <div class="card-body p-0">
        <?php if (!empty($komponen_lain)): ?>
        <div class="alert alert-light border m-3 mb-0 py-2" style="font-size:12px;">
          <i class="fa fa-info-circle text-info"></i>
          <strong>Centang</strong> komponen yang aktif untuk pegawai ini.
          Komponen <span class="badge badge-success">WAJIB</span> otomatis aktif dan tidak bisa dinonaktifkan.
        </div>
        <div class="table-responsive">
          <table class="table table-bordered table-striped table-sm mb-0">
            <thead>
              <tr>
                <th style="width:55px;" class="text-center">Aktif</th>
                <th>Komponen</th>
                <th style="width:100px;" class="text-center">Jenis</th>
                <th style="width:120px;" class="text-center">Cara Hitung</th>
                <th style="width:180px;" class="text-right">Nilai Default</th>
                <th style="width:220px;" class="text-right">Overwrite Nilai (FLAT)</th>
                <th>Catatan</th>
              </tr>
            </thead>
            <tbody>
              <?php
                // Kelompokkan: TUNJANGAN dulu, lalu POTONGAN
                $grouped = ['TUNJANGAN' => [], 'POTONGAN' => []];
                foreach ($komponen_lain as $k) { $grouped[$k->jenis][] = $k; }
              ?>
              <?php foreach (['TUNJANGAN', 'POTONGAN'] as $jenis): ?>
              <?php if (!empty($grouped[$jenis])): ?>
              <tr class="table-<?php echo $jenis === 'TUNJANGAN' ? 'success' : 'danger'; ?> bg-light">
                <td colspan="7" class="py-1 font-weight-bold" style="font-size:11px; text-transform:uppercase; letter-spacing:.5px;">
                  <?php echo $jenis === 'TUNJANGAN' ? 'Tunjangan / Penghasilan' : 'Potongan'; ?>
                </td>
              </tr>
              <?php foreach ($grouped[$jenis] as $k):
                $is_wajib  = (int) $k->is_wajib === 1;
                $is_active = (int) ($k->map_active ?? 1) === 1;
                $default_display = ($k->cara_hitung ?? 'FLAT') === 'FORMULA'
                  ? '<em class="text-muted">Hasil rumus</em>'
                  : ($k->tipe_nilai === 'PERSEN'
                    ? rtrim(rtrim(number_format((float)$k->nilai_default, 2, '.', ''), '0'), '.') . ' %'
                    : 'Rp ' . rupiah($k->nilai_default));
              ?>
              <tr class="<?php echo !$is_active ? 'text-muted' : ''; ?>">
                <td class="text-center align-middle">
                  <?php if ($is_wajib): ?>
                    <input type="hidden" name="aktif[<?php echo (int)$k->id_komponen; ?>]" value="1">
                    <span class="badge badge-success" title="Komponen wajib selalu aktif">WAJIB</span>
                  <?php else: ?>
                    <input type="checkbox"
                           class="chk-komponen"
                           name="aktif[<?php echo (int)$k->id_komponen; ?>]"
                           value="1"
                           <?php echo $is_active ? 'checked' : ''; ?>>
                  <?php endif; ?>
                </td>
                <td class="align-middle">
                  <?php echo html_escape($k->nama_komponen); ?>
                  <small class="text-muted d-block"><code><?php echo html_escape($k->kode_komponen); ?></code></small>
                </td>
                <td class="text-center align-middle">
                  <span class="badge <?php echo $k->jenis === 'TUNJANGAN' ? 'badge-success' : 'badge-danger'; ?>">
                    <?php echo $k->jenis; ?>
                  </span>
                </td>
                <td class="text-center align-middle">
                  <?php if (($k->cara_hitung ?? 'FLAT') === 'PER_HARI'): ?>
                    <span class="badge badge-info" title="Nilai × hari hadir">PER HARI</span>
                  <?php elseif (($k->cara_hitung ?? 'FLAT') === 'FORMULA'): ?>
                    <span class="badge badge-warning">FORMULA</span>
                  <?php else: ?>
                    <span class="badge badge-secondary">FLAT</span>
                  <?php endif; ?>
                </td>
                <td class="text-right align-middle"><?php echo $default_display; ?></td>
                <td class="align-middle text-right">
                  <?php if (($k->cara_hitung ?? 'FLAT') === 'FLAT'): ?>
                    <?php if ($k->tipe_nilai === 'PERSEN'): ?>
                      <div class="input-group input-group-sm">
                        <input type="text"
                               class="form-control form-control-sm text-right inp-override"
                               name="override[<?php echo (int) $k->id_komponen; ?>]"
                               value="<?php echo $k->nilai_override !== null ? rtrim(rtrim(number_format((float) $k->nilai_override, 2, '.', ''), '0'), '.') : ''; ?>"
                               placeholder="Contoh: 2.5">
                        <div class="input-group-append"><span class="input-group-text">%</span></div>
                      </div>
                    <?php else: ?>
                      <div class="input-group input-group-sm">
                        <div class="input-group-prepend"><span class="input-group-text">Rp</span></div>
                        <input type="text"
                               class="form-control form-control-sm text-right inp-rupiah inp-override"
                               name="override[<?php echo (int) $k->id_komponen; ?>]"
                               value="<?php echo $k->nilai_override !== null ? number_format((float) $k->nilai_override, 0, ',', '.') : ''; ?>"
                               placeholder="Kosong = default">
                      </div>
                    <?php endif; ?>
                  <?php else: ?>
                    <span class="text-muted">-</span>
                  <?php endif; ?>
                </td>
                <td class="align-middle">
                  <input type="text"
                         class="form-control form-control-sm"
                         name="catatan[<?php echo (int) $k->id_komponen; ?>]"
                         value="<?php echo html_escape($k->catatan ?? ''); ?>"
                         placeholder="Opsional">
                </td>
              </tr>
              <?php endforeach; ?>
              <?php endif; ?>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php else: ?>
        <div class="alert alert-warning m-3"><i class="fa fa-warning mr-1"></i> Belum ada komponen gaji yang tersedia. Tambahkan di <a href="<?php echo site_url('master/komponen'); ?>">Master Komponen</a>.</div>
        <?php endif; ?>
      </div>
    </div>

    <div class="d-flex justify-content-between mb-4">
      <a href="<?php echo site_url('master/mapping_komponen'); ?>" class="btn btn-secondary">
        <i class="fa fa-arrow-left mr-1"></i> Kembali ke Daftar
      </a>
      <div>
        <a href="<?php echo site_url('master/pegawai/detail/' . $pegawai->id_pegawai); ?>" class="btn btn-default mr-2">
          <i class="fa fa-user mr-1"></i> Data Pegawai
        </a>
        <button type="submit" class="btn btn-danger">
          <i class="fa fa-save mr-1"></i> Simpan Mapping
        </button>
      </div>
    </div>

    <?php echo form_close(); ?>
  </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
  var $ = window.jQuery;
  if (!$ || !$.fn) return;

  // Format rupiah saat mengetik di input gapok
  $(document).on('input', '.inp-rupiah', function () {
    var raw = $(this).val().replace(/[^0-9]/g, '');
    if (raw !== '') {
      $(this).val(parseInt(raw, 10).toLocaleString('id-ID'));
    }
  });

  // Saat submit: bersihkan format ribuan supaya value bisa diparse PHP
  $('#form-mapping').on('submit', function () {
    $('.inp-rupiah').each(function () {
      var raw = $(this).val().replace(/\./g, '');
      $(this).val(raw);
    });

    $('.inp-override').each(function () {
      var v = $(this).val();
      if (typeof v !== 'string') return;
      v = v.trim();
      if (v === '') return;
      if (v.indexOf(',') !== -1 && v.indexOf('.') !== -1) {
        v = v.replace(/\./g, '').replace(',', '.');
      } else if (v.indexOf(',') !== -1) {
        v = v.replace(',', '.');
      }
      $(this).val(v);
    });
  });
});
</script>
