<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/komponen'); ?>">Komponen Gaji</a></li>
          <li class="breadcrumb-item active"><?php echo $row ? 'Edit' : 'Tambah'; ?></li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">
    <div class="card card-danger card-outline" style="max-width:640px;">
      <div class="card-header"><h3 class="card-title"><i class="fa fa-list-alt mr-1"></i> Form Komponen Gaji</h3></div>
      <div class="card-body">
        <?php
          $form_action = $row ? site_url('master/komponen/edit/'.$row->id_komponen) : site_url('master/komponen/tambah');
          echo form_open($form_action, ['id'=>'form-komponen']);
        ?>

        <div class="row">
          <div class="col-sm-4">
            <div class="form-group">
              <label>Kode Komponen <span class="text-danger">*</span></label>
              <input type="text" name="kode_komponen" maxlength="20"
                     class="form-control text-uppercase <?php echo form_error('kode_komponen') ? 'is-invalid' : ''; ?>"
                     value="<?php echo html_escape(set_value('kode_komponen', $row->kode_komponen ?? '')); ?>"
                     placeholder="GAPOK / TJ_MAKAN">
              <?php if(form_error('kode_komponen')): ?><div class="invalid-feedback"><?php echo form_error('kode_komponen'); ?></div><?php endif; ?>
            </div>
          </div>
          <div class="col-sm-8">
            <div class="form-group">
              <label>Nama Komponen <span class="text-danger">*</span></label>
              <input type="text" name="nama_komponen" maxlength="100"
                     class="form-control <?php echo form_error('nama_komponen') ? 'is-invalid' : ''; ?>"
                     value="<?php echo html_escape(set_value('nama_komponen', $row->nama_komponen ?? '')); ?>">
              <?php if(form_error('nama_komponen')): ?><div class="invalid-feedback"><?php echo form_error('nama_komponen'); ?></div><?php endif; ?>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-sm-6">
            <div class="form-group">
              <label>Jenis <span class="text-danger">*</span></label>
              <select name="jenis" class="form-control <?php echo form_error('jenis') ? 'is-invalid' : ''; ?>">
                <option value="TUNJANGAN" <?php echo set_select('jenis','TUNJANGAN',($row->jenis??'TUNJANGAN')==='TUNJANGAN'); ?>>Tunjangan / Penghasilan</option>
                <option value="POTONGAN"  <?php echo set_select('jenis','POTONGAN',($row->jenis??'')==='POTONGAN'); ?>>Potongan</option>
              </select>
              <?php if(form_error('jenis')): ?><div class="invalid-feedback"><?php echo form_error('jenis'); ?></div><?php endif; ?>
            </div>
          </div>
          <div class="col-sm-6">
            <div class="form-group" id="group-tipe-nilai">
              <label>Tipe Nilai <span class="text-danger">*</span></label>
              <select name="tipe_nilai" class="form-control <?php echo form_error('tipe_nilai') ? 'is-invalid' : ''; ?>">
                <option value="NOMINAL" <?php echo set_select('tipe_nilai','NOMINAL',($row->tipe_nilai??'NOMINAL')==='NOMINAL'); ?>>Nominal (Rp)</option>
                <option value="PERSEN"  <?php echo set_select('tipe_nilai','PERSEN',($row->tipe_nilai??'')==='PERSEN'); ?>>Persentase (%)</option>
              </select>
              <?php if(form_error('tipe_nilai')): ?><div class="invalid-feedback"><?php echo form_error('tipe_nilai'); ?></div><?php endif; ?>
              <small id="hint-tipe-nilai" class="text-muted d-block mt-1">Mode Per Hari dan Rumus otomatis memakai Nominal.</small>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-sm-4">
            <div class="form-group">
              <label>Nilai Default <span class="text-danger">*</span></label>
              <input type="number" step="0.01" name="nilai_default"
                     class="form-control <?php echo form_error('nilai_default') ? 'is-invalid' : ''; ?>"
                     value="<?php echo set_value('nilai_default', $row->nilai_default ?? '0'); ?>">
              <?php if(form_error('nilai_default')): ?><div class="invalid-feedback"><?php echo form_error('nilai_default'); ?></div><?php endif; ?>
            </div>
          </div>
          <div class="col-sm-4">
            <div class="form-group">
              <label>Urutan Tampil <span class="text-danger">*</span></label>
              <input type="number" name="urutan" min="1"
                     class="form-control <?php echo form_error('urutan') ? 'is-invalid' : ''; ?>"
                     value="<?php echo set_value('urutan', $row->urutan ?? '99'); ?>">
              <?php if(form_error('urutan')): ?><div class="invalid-feedback"><?php echo form_error('urutan'); ?></div><?php endif; ?>
            </div>
          </div>
          <div class="col-sm-4">
            <div class="form-group">
              <label>Aktif di Periode <span class="text-danger">*</span></label>
              <?php $tipe_periode_val = set_value('tipe_periode', $row->tipe_periode ?? 'SEMUA'); ?>
              <select name="tipe_periode" class="form-control <?php echo form_error('tipe_periode') ? 'is-invalid' : ''; ?>">
                <option value="SEMUA"   <?php echo $tipe_periode_val === 'SEMUA'   ? 'selected' : ''; ?>>Semua Periode</option>
                <option value="REGULER" <?php echo $tipe_periode_val === 'REGULER' ? 'selected' : ''; ?>>Reguler saja</option>
                <option value="THR"     <?php echo $tipe_periode_val === 'THR'     ? 'selected' : ''; ?>>THR saja</option>
              </select>
              <?php if(form_error('tipe_periode')): ?><div class="invalid-feedback"><?php echo form_error('tipe_periode'); ?></div><?php endif; ?>
            </div>
          </div>
        </div>
        <!-- CARA HITUNG -->
        <?php
          $cara = set_value('cara_hitung', $row->cara_hitung ?? 'FLAT');
          $formula_reference_components = $formula_reference_components ?? [];
          $formula_current_urutan = $formula_current_urutan ?? (int) set_value('urutan', $row->urutan ?? 99);
          $system_formula_tokens = [
            'GAPOK', 'LEMBUR', 'MASA_KERJA_BULAN',
            'HARI_MASUK', 'HARI_TERLAMBAT', 'HARI_SAKIT', 'HARI_CUTI', 'HARI_IZIN', 'HARI_ALPHA', 'HARI_LIBUR',
            'SUBTOTAL_TUNJANGAN', 'SUBTOTAL_POTONGAN', 'BRUTO_SEMENTARA',
            'IF(', 'MIN(', 'MAX(', 'ROUND(', 'ABS(', '(', ')', '+', '-', '*', '/', '>=', '<=', '>', '<'
          ];
          // GAPOK & LEMBUR harus selalu FLAT — nonaktifkan pilihan PER_HARI
          $is_gapok_or_lembur = in_array(strtoupper($row->kode_komponen ?? ''), ['GAPOK','LEMBUR']);
          $formula_expression = set_value('formula_expression', $row->formula_expression ?? '');
        ?>
        <div class="form-group">
          <label>Cara Hitung <span class="text-danger">*</span></label>
          <div>
            <div class="custom-control custom-radio custom-control-inline">
              <input type="radio" id="ch_flat" name="cara_hitung" class="custom-control-input" value="FLAT"
                     <?php echo $cara === 'FLAT' ? 'checked' : ''; ?>
                     <?php echo $is_gapok_or_lembur ? 'disabled' : ''; ?>>
              <label class="custom-control-label" for="ch_flat">
                <strong>Flat</strong> — nilai penuh, tidak terpengaruh kehadiran
              </label>
            </div>
            <div class="custom-control custom-radio custom-control-inline mt-1">
              <input type="radio" id="ch_per_hari" name="cara_hitung" class="custom-control-input" value="PER_HARI"
                     <?php echo $cara === 'PER_HARI' ? 'checked' : ''; ?>
                     <?php echo $is_gapok_or_lembur ? 'disabled' : ''; ?>>
              <label class="custom-control-label" for="ch_per_hari">
                <strong>Per Hari</strong> — nilai × jumlah hari hadir sesuai status yang dipilih
              </label>
            </div>
            <div class="custom-control custom-radio custom-control-inline mt-1">
              <input type="radio" id="ch_formula" name="cara_hitung" class="custom-control-input" value="FORMULA"
                     <?php echo $cara === 'FORMULA' ? 'checked' : ''; ?>
                     <?php echo $is_gapok_or_lembur ? 'disabled' : ''; ?>>
              <label class="custom-control-label" for="ch_formula">
                <strong>Rumus</strong> — hitung dari variabel payroll seperti <code>GAPOK</code>, <code>HARI_MASUK</code>, atau komponen lain
              </label>
            </div>
            <?php if ($is_gapok_or_lembur): ?>
            <input type="hidden" name="cara_hitung" value="FLAT">
            <small class="text-muted d-block mt-1"><i class="fa fa-info-circle"></i> Komponen ini selalu menggunakan cara hitung Flat.</small>
            <?php endif; ?>
          </div>
        </div>

        <div id="block-formula-builder" style="display:<?php echo $cara === 'FORMULA' ? 'block' : 'none'; ?>;">
          <div class="form-group">
            <label>Rumus Komponen <span class="text-danger">*</span></label>
            <textarea name="formula_expression" id="formula_expression" rows="4"
                      class="form-control font-weight-bold <?php echo form_error('formula_expression') ? 'is-invalid' : ''; ?>"
                      placeholder="Contoh: GAPOK * 0.01"><?php echo html_escape($formula_expression); ?></textarea>
            <?php if(form_error('formula_expression')): ?><div class="invalid-feedback"><?php echo form_error('formula_expression'); ?></div><?php endif; ?>
            <div id="formula_inline_feedback" class="invalid-feedback d-none"></div>
            <small class="text-muted d-block mt-2">
              Rumus harus menghasilkan <strong>nilai akhir nominal rupiah</strong>. Anda bisa gunakan operator <code>+ - * /</code>, tanda kurung,
              fungsi <code>MIN</code>, <code>MAX</code>, <code>ROUND</code>, <code>ABS</code>, <code>IF</code>, serta variabel payroll di bawah.
            </small>
          </div>

          <div class="row">
            <div class="col-sm-7">
              <div class="form-group">
                <label class="mb-1">Variabel Sistem</label>
                <div class="border rounded p-2 bg-light mb-2">
                  <?php foreach ($system_formula_tokens as $token): ?>
                    <button type="button" class="btn btn-xs btn-outline-secondary mb-1 js-insert-formula" data-token="<?php echo html_escape($token); ?>"><?php echo html_escape($token); ?></button>
                  <?php endforeach; ?>
                </div>
                <label class="mb-1">Komponen Tersedia Sesuai Urutan</label>
                <div class="border rounded p-2 bg-light" id="formula-component-tokens"></div>
                <small class="text-muted d-block mt-1">Hanya komponen aktif dengan urutan lebih kecil dari komponen ini yang ditampilkan.</small>
              </div>
            </div>
            <div class="col-sm-5">
              <div class="form-group">
                <label class="mb-1">Template Siap Pakai</label>
                <div class="list-group">
                  <button type="button" class="list-group-item list-group-item-action js-fill-formula" data-formula="GAPOK * 0.01">Persen dari Gapok</button>
                  <button type="button" class="list-group-item list-group-item-action js-fill-formula" data-formula="HARI_MASUK * 20000">Tunjangan harian nominal</button>
                  <button type="button" class="list-group-item list-group-item-action js-fill-formula" data-formula="IF(HARI_ALPHA > 0, HARI_ALPHA * 50000, 0)">Potongan jika alpha</button>
                  <button type="button" class="list-group-item list-group-item-action js-fill-formula" data-formula="ROUND((GAPOK + TJ_POSISI) / 12 * MIN(MASA_KERJA_BULAN, 12), 0)">THR prorata sederhana</button>
                </div>
              </div>
            </div>
          </div>




        </div>

        <!-- STATUS ABSENSI YANG DIHITUNG (hanya muncul jika PER_HARI) -->
        <?php
          $all_statuses = ['MASUK','TERLAMBAT','LEMBUR','SAKIT','CUTI','IZIN','ALPHA','LIBUR'];
          $status_labels = [
            'MASUK'      => 'Hadir (MASUK)',
            'TERLAMBAT'  => 'Terlambat',
            'LEMBUR'     => 'Lembur',
            'SAKIT'      => 'Sakit',
            'CUTI'       => 'Cuti',
            'IZIN'       => 'Izin',
            'ALPHA'      => 'Alpha (Tidak Hadir)',
            'LIBUR'      => 'Libur',
          ];
          $status_colors = [
            'MASUK'      => 'success',
            'TERLAMBAT'  => 'warning',
            'LEMBUR'     => 'info',
            'SAKIT'      => 'primary',
            'CUTI'       => 'secondary',
            'IZIN'       => 'secondary',
            'ALPHA'      => 'danger',
            'LIBUR'      => 'dark',
          ];
          // POST takes priority, then existing_rules from DB
          $checked_rules = $this->input->post('rule_status') ? (array) $this->input->post('rule_status') : ($existing_rules ?? []);
        ?>
        <div id="block-rule-status" style="display:<?php echo $cara === 'PER_HARI' ? 'block' : 'none'; ?>">
          <div class="form-group">
            <label>Status Kehadiran yang Dihitung <span class="text-danger">*</span></label>
            <div class="alert alert-light border py-2 mb-2" style="font-size:12px;">
              <i class="fa fa-info-circle text-info"></i>
              Centang status absensi yang <strong>menyebabkan komponen ini dihitung/terhitung</strong>.
              Nilai akhir = <em>nilai per hari</em> × <em>jumlah hari dengan status yang dicentang</em>.
            </div>
            <div class="row">
              <?php foreach ($all_statuses as $st): ?>
              <div class="col-sm-3 mb-1">
                <div class="custom-control custom-checkbox">
                  <input type="checkbox"
                         class="custom-control-input"
                         id="rule_<?php echo strtolower($st); ?>"
                         name="rule_status[]"
                         value="<?php echo $st; ?>"
                         <?php echo in_array($st, $checked_rules) ? 'checked' : ''; ?>>
                  <label class="custom-control-label" for="rule_<?php echo strtolower($st); ?>">
                    <span class="badge badge-<?php echo $status_colors[$st]; ?>"><?php echo $status_labels[$st]; ?></span>
                  </label>
                </div>
              </div>
              <?php endforeach; ?>
            </div>
          </div>
        </div>

        <div class="d-flex justify-content-between">
          <a href="<?php echo site_url('master/komponen'); ?>" class="btn btn-secondary"><i class="fa fa-arrow-left mr-1"></i> Kembali</a>
          <button type="submit" class="btn btn-danger"><i class="fa fa-save mr-1"></i> Simpan</button>
        </div>
        <?php echo form_close(); ?>

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

  var formulaReferenceComponents = <?php echo json_encode($formula_reference_components, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

  function renderFormulaReferenceTokens() {
    var currentUrutan = parseInt($('input[name="urutan"]').val(), 10) || 0;
    var currentKode = $.trim(($('input[name="kode_komponen"]').val() || '')).toUpperCase();
    var html = '';

    $.each(formulaReferenceComponents, function (_, component) {
      var kode = (component.kode_komponen || '').toUpperCase();
      var urutan = parseInt(component.urutan, 10) || 0;
      if (!kode || kode === currentKode || urutan >= currentUrutan) {
        return;
      }

      html += '<button type="button" class="btn btn-xs btn-outline-info mb-1 mr-1 js-insert-formula" data-token="' + kode + '">' + kode + '</button>';
    });

    if (!html) {
      html = '<small class="text-muted">Belum ada komponen referensi yang valid untuk urutan ini.</small>';
    }

    $('#formula-component-tokens').html(html);
  }

  function setCalcMode(selected, withFocus) {
    var isFlat = selected === 'FLAT';
    var isPerHari = selected === 'PER_HARI';
    var isFormula = selected === 'FORMULA';
    var $tipeNilai = $('select[name="tipe_nilai"]');
    var $nilaiDefault = $('input[name="nilai_default"]');
    var $formulaExpression = $('#formula_expression');
    var $ruleStatus = $('input[name="rule_status[]"]');
    var $formulaButtons = $('.js-insert-formula, .js-fill-formula');
    var $hintTipeNilai = $('#hint-tipe-nilai');

    $('#block-rule-status').stop(true, true)[isPerHari ? 'slideDown' : 'slideUp'](160);
    $('#block-formula-builder').stop(true, true)[isFormula ? 'slideDown' : 'slideUp'](160, function () {
      if (isFormula && withFocus) {
        $('#formula_expression').trigger('focus');
      }
    });

    if (!isFlat) {
      $tipeNilai.val('NOMINAL').prop('disabled', true);
      $hintTipeNilai.removeClass('d-none');
    } else {
      $tipeNilai.prop('disabled', false);
      $hintTipeNilai.addClass('d-none');
    }

    if (isFormula) {
      $nilaiDefault.prop('disabled', true);
      renderFormulaReferenceTokens();
    } else {
      $nilaiDefault.prop('disabled', false);
    }

    $formulaExpression.prop('disabled', !isFormula);
    $formulaButtons.prop('disabled', !isFormula);
    $ruleStatus.prop('disabled', !isPerHari);
  }

  function syncCalcMode(withFocus) {
    var selected = $('input[name="cara_hitung"]:checked').val() || 'FLAT';
    setCalcMode(selected, withFocus === true);
  }

  function clearFormulaInlineError() {
    $('#formula_expression').removeClass('is-invalid');
    $('#formula_inline_feedback').addClass('d-none').text('');
  }

  function showFormulaInlineError(message) {
    $('#formula_expression').addClass('is-invalid');
    $('#formula_inline_feedback').removeClass('d-none').text(message || 'Rumus tidak valid.');
  }

  function insertAtCursor(el, text) {
    var start = el.selectionStart || 0;
    var end = el.selectionEnd || 0;
    var value = el.value || '';
    el.value = value.substring(0, start) + text + value.substring(end);
    el.focus();
    var pos = start + text.length;
    el.setSelectionRange(pos, pos);
  }

  $('input[name="cara_hitung"]').on('change click', function () {
    syncCalcMode(true);
  });
  $(document).on('click', '.js-insert-formula', function () {
    var field = document.getElementById('formula_expression');
    if (!field) return;
    insertAtCursor(field, $(this).data('token'));
  });
  $('.js-fill-formula').on('click', function () {
    $('#formula_expression').val($(this).data('formula')).focus();
  });
  $('#formula_expression').on('input', clearFormulaInlineError);
  $('input[name="urutan"]').on('input change', renderFormulaReferenceTokens);
  $('input[name="kode_komponen"]').on('input change', renderFormulaReferenceTokens);

  renderFormulaReferenceTokens();
  syncCalcMode(false);
});
</script>
      </div>
    </div>
  </div>
</section>
