<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/pegawai'); ?>">Data Pegawai</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">
    <?php
      $form_action = $row
        ? site_url('master/pegawai/edit/' . $row->id_pegawai)
        : site_url('master/pegawai/tambah');
      echo form_open($form_action, ['id' => 'form-pegawai']);
    ?>

    <!-- IDENTITAS DASAR -->
    <div class="card card-danger card-outline">
      <div class="card-header">
        <h3 class="card-title"><i class="fa fa-id-card mr-1"></i> Identitas Dasar</h3>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-3">
            <div class="form-group">
              <label>NIP <span class="text-danger">*</span></label>
              <input type="text" name="nip" maxlength="20"
                     class="form-control <?php echo form_error('nip') ? 'is-invalid' : ''; ?>"
                     value="<?php echo html_escape(set_value('nip', $row->nip ?? '')); ?>"
                     placeholder="Nomor Induk Pegawai">
              <?php if (form_error('nip')): ?><div class="invalid-feedback"><?php echo form_error('nip'); ?></div><?php endif; ?>
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>NIK</label>
              <input type="text" name="nik" maxlength="16"
                     class="form-control" placeholder="16 digit NIK KTP"
                     value="<?php echo html_escape(set_value('nik', $row->nik ?? '')); ?>">
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-group">
              <label>Nama Lengkap <span class="text-danger">*</span></label>
              <input type="text" name="nama_lengkap" maxlength="150"
                     class="form-control <?php echo form_error('nama_lengkap') ? 'is-invalid' : ''; ?>"
                     value="<?php echo html_escape(set_value('nama_lengkap', $row->nama_lengkap ?? '')); ?>"
                     placeholder="Nama sesuai KTP">
              <?php if (form_error('nama_lengkap')): ?><div class="invalid-feedback"><?php echo form_error('nama_lengkap'); ?></div><?php endif; ?>
            </div>
          </div>
          <div class="col-md-2">
            <div class="form-group">
              <label>Jenis Kelamin <span class="text-danger">*</span></label>
              <select name="jenis_kelamin" class="form-control <?php echo form_error('jenis_kelamin') ? 'is-invalid' : ''; ?>">
                <option value="L" <?php echo set_select('jenis_kelamin', 'L', ($row->jenis_kelamin ?? 'L') === 'L'); ?>>Laki-laki</option>
                <option value="P" <?php echo set_select('jenis_kelamin', 'P', ($row->jenis_kelamin ?? '') === 'P'); ?>>Perempuan</option>
              </select>
              <?php if (form_error('jenis_kelamin')): ?><div class="invalid-feedback"><?php echo form_error('jenis_kelamin'); ?></div><?php endif; ?>
            </div>
          </div>
        </div>

        <div class="row">
          <div class="col-md-4">
            <div class="form-group">
              <label>Tempat Lahir</label>
              <input type="text" name="tempat_lahir" maxlength="100"
                     class="form-control"
                     value="<?php echo html_escape(set_value('tempat_lahir', $row->tempat_lahir ?? '')); ?>"
                     placeholder="Kota lahir">
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>Tanggal Lahir</label>
              <input type="date" name="tanggal_lahir" class="form-control"
                     value="<?php echo set_value('tanggal_lahir', $row->tanggal_lahir ?? ''); ?>">
            </div>
          </div>
          <div class="col-md-5">
            <div class="form-group">
              <label>Alamat</label>
              <textarea name="alamat" class="form-control" rows="2"
                        placeholder="Alamat lengkap sesuai KTP"><?php echo html_escape(set_value('alamat', $row->alamat ?? '')); ?></textarea>
            </div>
          </div>
        </div>

        <div class="row">
          <div class="col-md-4">
            <div class="form-group">
              <label>No. Telepon</label>
              <input type="text" name="no_telepon" maxlength="20"
                     class="form-control"
                     value="<?php echo html_escape(set_value('no_telepon', $row->no_telepon ?? '')); ?>"
                     placeholder="08xx-xxxx-xxxx">
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-group">
              <label>Email</label>
              <input type="email" name="email" maxlength="100"
                     class="form-control"
                     value="<?php echo html_escape(set_value('email', $row->email ?? '')); ?>"
                     placeholder="email@perusahaan.com">
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-group">
              <label>Tanggal Masuk <span class="text-danger">*</span></label>
              <input type="date" name="tanggal_masuk"
                     class="form-control <?php echo form_error('tanggal_masuk') ? 'is-invalid' : ''; ?>"
                     value="<?php echo set_value('tanggal_masuk', $row->tanggal_masuk ?? ''); ?>">
              <?php if (form_error('tanggal_masuk')): ?><div class="invalid-feedback"><?php echo form_error('tanggal_masuk'); ?></div><?php endif; ?>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ORGANISASI & PENGGAJIAN -->
    <div class="card card-danger card-outline">
      <div class="card-header">
        <h3 class="card-title"><i class="fa fa-sitemap mr-1"></i> Organisasi & Penggajian</h3>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-4">
            <div class="form-group">
              <label>Divisi <span class="text-danger">*</span></label>
              <select name="id_divisi" id="id_divisi"
                      class="form-control <?php echo form_error('id_divisi') ? 'is-invalid' : ''; ?>">
                <option value="">-- Pilih Divisi --</option>
                <?php foreach ($list_divisi as $d): ?>
                  <option value="<?php echo $d->id_divisi; ?>"
                    <?php echo set_select('id_divisi', $d->id_divisi, ($row && $row->id_divisi == $d->id_divisi)); ?>>
                    <?php echo html_escape($d->nama_divisi); ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <?php if (form_error('id_divisi')): ?><div class="invalid-feedback"><?php echo form_error('id_divisi'); ?></div><?php endif; ?>
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-group">
              <label>Jabatan <span class="text-danger">*</span></label>
              <select name="id_jabatan" id="id_jabatan"
                      data-selected="<?php echo (int) set_value('id_jabatan', $row->id_jabatan ?? 0); ?>"
                      class="form-control <?php echo form_error('id_jabatan') ? 'is-invalid' : ''; ?>">
                <option value="">-- Pilih Jabatan --</option>
                <?php foreach ($list_jabatan as $j): ?>
                  <option value="<?php echo $j->id_jabatan; ?>"
                    <?php echo set_select('id_jabatan', $j->id_jabatan, ($row && $row->id_jabatan == $j->id_jabatan)); ?>>
                    <?php echo html_escape($j->nama_jabatan); ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <?php if (form_error('id_jabatan')): ?><div class="invalid-feedback"><?php echo form_error('id_jabatan'); ?></div><?php endif; ?>
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-group">
              <label>Status PTKP <span class="text-danger">*</span></label>
              <select name="ptkp_status"
                      class="form-control <?php echo form_error('ptkp_status') ? 'is-invalid' : ''; ?>">
                <?php foreach ($ptkp_options as $opt): ?>
                  <option value="<?php echo $opt; ?>"
                    <?php echo set_select('ptkp_status', $opt, ($row->ptkp_status ?? 'TK0') === $opt); ?>>
                    <?php echo $opt; ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <?php if (form_error('ptkp_status')): ?><div class="invalid-feedback"><?php echo form_error('ptkp_status'); ?></div><?php endif; ?>
            </div>
          </div>
        </div>

        <?php if ($row): ?>
        <div class="alert alert-info py-2 mb-0" style="font-size:12px;">
          <i class="fa fa-info-circle"></i>
          Gaji pokok dan komponen tunjangan/potongan diatur di halaman
          <a href="<?php echo site_url('master/mapping_komponen/pegawai/' . $row->id_pegawai); ?>" class="font-weight-bold">Mapping Komponen Gaji</a>.
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- DATA PENUNJANG -->
    <div class="card card-danger card-outline">
      <div class="card-header">
        <h3 class="card-title"><i class="fa fa-file-text-o mr-1"></i> Data Penunjang (BPJS, Rekening, Pajak)</h3>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-4">
            <div class="form-group">
              <label>NPWP</label>
              <input type="text" name="npwp" maxlength="20" class="form-control"
                     value="<?php echo html_escape(set_value('npwp', $row->npwp ?? '')); ?>" placeholder="XX.XXX.XXX.X-XXX.XXX">
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-group">
              <label>No. BPJS Kesehatan</label>
              <input type="text" name="no_bpjs_kesehatan" maxlength="30" class="form-control"
                     value="<?php echo html_escape(set_value('no_bpjs_kesehatan', $row->no_bpjs_kesehatan ?? '')); ?>">
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-group">
              <label>No. BPJS Ketenagakerjaan</label>
              <input type="text" name="no_bpjs_ketenagakerjaan" maxlength="30" class="form-control"
                     value="<?php echo html_escape(set_value('no_bpjs_ketenagakerjaan', $row->no_bpjs_ketenagakerjaan ?? '')); ?>">
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-md-4">
            <div class="form-group">
              <label>Nama Bank</label>
              <input type="text" name="nama_bank" maxlength="50" class="form-control"
                     value="<?php echo html_escape(set_value('nama_bank', $row->nama_bank ?? '')); ?>" placeholder="BCA / BRI / Mandiri...">
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-group">
              <label>No. Rekening</label>
              <input type="text" name="no_rekening" maxlength="30" class="form-control"
                     value="<?php echo html_escape(set_value('no_rekening', $row->no_rekening ?? '')); ?>">
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="d-flex justify-content-between mb-4">
      <a href="<?php echo site_url('master/pegawai'); ?>" 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> <?php echo $row ? 'Simpan Perubahan' : 'Tambah Pegawai'; ?>
      </button>
    </div>

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

<script>
document.addEventListener('DOMContentLoaded', function () {
  var elDivisi = document.getElementById('id_divisi');
  var elJabatan = document.getElementById('id_jabatan');
  if (!elDivisi || !elJabatan) {
    return;
  }

  function renderOptions(list, selectedId) {
    var html = '<option value="">-- Pilih Jabatan --</option>';
    if (Array.isArray(list) && list.length > 0) {
      list.forEach(function (item) {
        var selected = String(item.id_jabatan) === String(selectedId) ? ' selected' : '';
        html += '<option value="' + item.id_jabatan + '"' + selected + '>' + item.nama_jabatan + '</option>';
      });
    } else {
      html += '<option value="" disabled>(Tidak ada jabatan aktif pada divisi ini)</option>';
    }
    elJabatan.innerHTML = html;
  }

  function loadJabatanByDivisi(idDivisi, selectedId) {
    selectedId = selectedId || '';
    if (!idDivisi) {
      elJabatan.innerHTML = '<option value="">-- Pilih Jabatan --</option>';
      return;
    }

    elJabatan.innerHTML = '<option value="">Memuat...</option>';
    var url = '<?php echo site_url('master/jabatan/ajax_by_divisi'); ?>/' + encodeURIComponent(idDivisi);

    fetch(url, {
      method: 'GET',
      headers: { 'Accept': 'application/json' },
      credentials: 'same-origin'
    })
      .then(function (response) {
        if (!response.ok) throw new Error('HTTP ' + response.status);
        return response.json();
      })
      .then(function (data) {
        renderOptions(data, selectedId);
      })
      .catch(function () {
        elJabatan.innerHTML = '<option value="">-- Gagal memuat jabatan --</option>';
      });
  }

  var initialDivisi = elDivisi.value;
  var initialJabatan = elJabatan.getAttribute('data-selected') || '';
  if (initialDivisi) {
    loadJabatanByDivisi(initialDivisi, initialJabatan);
  }

  elDivisi.addEventListener('change', function () {
    loadJabatanByDivisi(this.value, '');
  });
});
</script>
