<div class="main-content">
  <div class="container-fluid" style="margin-top: 50px;">

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<h2><i class="bi bi-file-earmark-text"></i> Template 1: Form Dialog Kinerja Individual</h2>

<form id="formKinerja" method="post" action="<?= base_url("dialog_kinerja/save/{$pegawai_id}/1") ?>">
<input type="hidden" name="form_level" value="<?= $level ?>">
<!-- <input type="hidden" name="form_level" value="<?= htmlspecialchars($level ?? '') ?>"> -->
<input type="hidden" name="nama" value="<?= htmlspecialchars($pegawai->nama ?? '') ?>">
  <input type="hidden" name="nip" value="<?= htmlspecialchars($pegawai->nip ?? '') ?>">
  <input type="hidden" name="jabatan" value="<?= htmlspecialchars($pegawai->jabatan ?? '') ?>">
  <input type="hidden" name="unit_kerja" value="<?= htmlspecialchars($pegawai->unor_nama ?? '') ?>">
  <input type="hidden" name="opd" value="<?= htmlspecialchars($pegawai->unor_induk_nama ?? '') ?>">

  <div class="card mb-4 shadow-sm">
    <div class="card-header bg-primary text-white">A. IDENTITAS PEGAWAI</div>
    <div class="card-body">
      <div class="row">
        <div class="col-12">
          <p><strong>Nama:</strong> <?= htmlspecialchars($pegawai->nama ?? '-') ?></p>
          <p><strong>NIP:</strong> <?= htmlspecialchars($pegawai->nip ?? '-') ?></p>
          <p><strong>Jabatan:</strong> <?= htmlspecialchars($pegawai->jabatan ?? '-') ?></p>
        </div>
        <div class="col-12">
          <p><strong>Unit Kerja:</strong> <?= htmlspecialchars($pegawai->unor_nama ?? '-') ?></p>
          <p><strong>OPD:</strong> <?= htmlspecialchars($pegawai->unor_induk_nama ?? '-') ?></p>
        </div>
      </div>
    </div>
  </div>

  <div class="card mb-4 shadow-sm">
    <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
        <span class="fw-bold">B. RENCANA HASIL KERJA</span>
        <div class="d-flex align-items-center">
    <button type="button" class="btn btn-sm btn-light me-2" onclick="checkRHKAtasan()">
        <i class="bi bi-plus-circle"></i> Tambah RHK
    </button>

    <?php 
				/** * Variabel $level didapat dari data row table 'pimpinan_bawahan' 
				 * yang dikirimkan melalui Controller
				 */
				if (isset($level) && $level !== 'staf'): 
				?>
						<button type="button" class="btn btn-sm btn-danger" id="btnHapusRHK" onclick="removeRHKRow()">
								<i class="bi bi-trash"></i> Hapus RHK
						</button>
				<?php endif; ?>
		</div>

    </div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-bordered mb-0" id="rhk-table">
          <thead class="table-light text-center align-middle">
            <tr>
              <th width="50">NO</th>
              <?php if ($level !== 'top_leader'): ?>
                <th width="250" >RHK ATASAN</th>
              <?php endif; ?>
              <th width="300">RENCANA HASIL KERJA</th>
              <th>INDIKATOR, TARGET & INTERVENSI</th>
            </tr>
          </thead>
          <tbody>
						
            <?php 
							// Ambil data RHK yang diintervensikan oleh atasan
							$intervensi_data = $form_data['raw_rhk_intervensi'] ?? [];

							// LOGIKA DINAMIS:
							// Jika user bukan top_leader DAN ada data intervensi, maka jumlah baris mengikuti jumlah data tersebut.
							// Jika tidak, tetap tampilkan default 3 baris.
							if ($level !== 'top_leader' && !empty($intervensi_data)) {
									$initial_count = count($intervensi_data);
							} else {
									$initial_count = 6; 
							}

							for ($i = 1; $i <= $initial_count; $i++): 
							?>
              <tr data-rhk-index="<?= $i ?>">
                <td class="row-no text-center align-middle fw-bold"><?= $i ?></td>
									<?php if ($level !== 'top_leader'): ?>
											<td class="p-2">
													<div class="d-flex h-100 flex-column">
															<?php 
																	// List RHK hasil tarikan dari intervensi atasan (berurutan)
																	$intervensi_data = $form_data['raw_rhk_intervensi'] ?? [];
																	
																	// Ambil data yang sudah tersimpan di database untuk baris ini
																	$val_atasan_raw = $form_data["rhk_atasan_{$i}"] ?? '';
																	$val_atasan_text = '';

																	if (!empty($val_atasan_raw)) {
																			$decoded_atasan = json_decode($val_atasan_raw, true);
																			$val_atasan_text = is_array($decoded_atasan) ? ($decoded_atasan[0] ?? '') : $val_atasan_raw;
																	}

																	// Jika data di database kosong, gunakan data intervensi atasan berdasarkan urutan baris
																	if (empty($val_atasan_text) && isset($intervensi_data[$i-1])) {
																			$val_atasan_text = $intervensi_data[$i-1];
																	}
															?>

															<textarea 
																	name="rhk_atasan_<?= $i ?>" 
																	class="form-control flex-grow-1 auto-height mb-1" 
																	placeholder="Tulis RHK Atasan..."
																	readonly
															><?= htmlspecialchars($val_atasan_text) ?></textarea>
															
															<input type="hidden" name="rhk_atasan_id_<?= $i ?>" value="<?= $i ?>">

															<?php if (isset($intervensi_data[$i-1])): ?>
																	<div class="text-right">
																			<small class="text-muted" style="font-size: 10px;">
																					<i>RHK untuk Indikator ke-<?= $i ?></i>
																			</small>
																	</div>
															<?php endif; ?>
													</div>
											</td>
									<?php endif; ?>
                <td class="p-2">
									<div class="rhk-dynamic-container">
											<?php 
											// 1. Ambil data indikator untuk menentukan jumlah baris yang harus muncul
											$db_indikator_count = json_decode($form_data["rhk_indikator_{$i}"] ?? '[]', true);
											$loop_rhk_count = (count($db_indikator_count) > 0) ? count($db_indikator_count) : 1;

											// 2. Ambil data teks RHK asli dari database dan bongkar jika formatnya JSON
                      $val_rhk_raw = $form_data["rhk_rhk_{$i}"] ?? '';
                      $val_rhk_text = '';
                                            
                      if (!empty($val_rhk_raw)) {
                        $decoded_rhk = json_decode($val_rhk_raw, true);
                      if (is_array($decoded_rhk)) {
                        // Ambil elemen pertama dari array JSON
                        $val_rhk_text = $decoded_rhk[0] ?? '';
                      } else {
                      // Jika bukan JSON, ambil teks aslinya
                      $val_rhk_text = $val_rhk_raw;
                        }
                      }

											// 3. Loop agar jumlah textarea RHK sama dengan jumlah kotak indikator
											for ($j = 0; $j < $loop_rhk_count; $j++): 
											?>
											<div class="rhk-item-wrapper mb-2">
													<textarea name="rhk_rhk_<?= $i ?>[]" 
																		class="form-control auto-height" 
																		style="min-height: 125px;" 
																		placeholder="Tulis Rencana Hasil Kerja..."><?= htmlspecialchars($val_rhk_text) ?></textarea>
													
													<?php if ($loop_rhk_count > 1): ?>
															<small class="text-muted">RHK untuk Indikator ke-<?= $j+1 ?></small>
													<?php endif; ?>
											</div>
											
											<?php if ($j < $loop_rhk_count - 1): ?>
													<hr class="my-3">
											<?php endif; ?>

											<?php endfor; ?>
									</div>
							</td>
                <td class="align-top">
									<div class="indicator-container p-2" id="indicator-container-<?= $i ?>">
											<?php 
											// 1. Ambil & Decode data dari database berdasarkan field_key
											// gunakan $form_data yang merupakan array dari tabel dialog_kinerja_data
											$db_indikator = json_decode($form_data["rhk_indikator_{$i}"] ?? '[]', true);
											$db_target    = json_decode($form_data["rhk_target_{$i}"] ?? '[]', true);
											$db_satuan    = json_decode($form_data["rhk_satuan_{$i}"] ?? '[]', true);

											// 2. Tentukan jumlah kotak yang harus muncul
											// Jika di DB kosong, tampilkan 1 kotak kosong sebagai default awal
											$count_data = count($db_indikator);
											$loop_count = ($count_data > 0) ? $count_data : 1;

											for ($idx = 0; $idx < $loop_count; $idx++): 
													// Ambil data spesifik berdasarkan index array
													$val_indikator = $db_indikator[$idx] ?? '';
													$val_target    = $db_target[$idx] ?? '';
													$val_satuan    = $db_satuan[$idx] ?? '';
													
													// Ambil data bawahan khusus untuk index ini
													$db_bawahan = json_decode($form_data["rhk_bawahan_{$i}_{$idx}"] ?? '[]', true);
											?>
											<div class="indicator-item border p-2 mb-2 bg-light shadow-sm position-relative" style="border-left: 5px solid #198754 !important;">
													<?php if ($idx > 0): ?>
															<button type="button" class="btn-close position-absolute top-0 end-0 m-1" style="font-size: 0.5rem;" onclick="this.parentElement.remove()"></button>
													<?php endif; ?>

													<div class="row g-2">
															<div class="col-12 mb-1">
																	<label class="small fw-bold text-success">Indikator:</label>
																	<input type="text" name="rhk_indikator_<?= $i ?>[]" value="<?= htmlspecialchars($val_indikator) ?>" class="form-control form-control-sm" placeholder="Contoh: Persentase penyelesaian laporan">
															</div>
															<div class="col-6">
																	<label class="small fw-bold text-success">Target:</label>
																	<input type="text" name="rhk_target_<?= $i ?>[]" value="<?= htmlspecialchars($val_target) ?>" class="form-control form-control-sm" placeholder="100">
															</div>
															<div class="col-6">
																	<label class="small fw-bold text-success">Satuan:</label>
																	<input type="text" name="rhk_satuan_<?= $i ?>[]" value="<?= htmlspecialchars($val_satuan) ?>" class="form-control form-control-sm" placeholder="Persen/Dokumen">
															</div>

															<?php if ($level && !empty($daftar_bawahan)): ?>
															<div class="col-12 mt-2">
																	<label class="small fw-bold text-primary">Intervensi Bawahan:</label>
																	<select name="rhk_bawahan_<?= $i ?>_<?= $idx ?>[]" class="form-control select2-multiple" multiple="multiple">
																			<?php foreach ($daftar_bawahan as $b): ?>
																					<?php 
																							$selected = (is_array($db_bawahan) && in_array($b->id_peg, $db_bawahan)) ? 'selected' : '';
																					?>
																					<option value="<?= $b->id_peg ?>" <?= $selected ?>><?= htmlspecialchars($b->nama) ?></option>
																			<?php endforeach; ?>
																	</select>
															</div>
															<?php endif; ?>
													</div>
											</div>
											<?php endfor; ?>
									</div>
									
									<div class="px-2 pb-2">
											<button type="button" class="btn btn-xs btn-outline-primary" onclick="addIndicatorRow(<?= $i ?>)">
													<i class="bi bi-plus"></i> Tambah Indikator
											</button>
									</div>
							</td>
              </tr>
            <?php endfor; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="card mb-4 shadow-sm">
    <div class="card-header bg-info text-white fw-bold">C. EKSPETASI PERILAKU KERJA (BerAKHLAK)</div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-bordered mb-0">
          <thead class="table-light text-center align-middle">
            <tr>
              <th width="50">NO</th>
              <th width="200">ASPEK PERILAKU</th>
              <th>STANDAR PERILAKU</th>
              <th>EKSPETASI KHUSUS</th>
              <?php if ($level && !empty($daftar_bawahan)): ?>
                <th width="250">INTERVENSI BAWAHAN</th>
              <?php endif; ?>
            </tr>
          </thead>
          <tbody>
            <?php
            $akhlak_list = [
                1 => ['Berorientasi Pelayanan', ['- Memahami kebutuhan masyarakat', '- Ramah, cekatan, solutif', '- Melakukan perbaikan tiada henti']],
                2 => ['Akuntabel', ['- Melaksanakan tugas dengan jujur, bertanggung jawab', '- Menggunakan kekayaan negara secara bertanggung jawab', '- Tidak menyalahgunakan kewenangan jabatan']],
                3 => ['Kompeten', ['- Meningkatkan kompetensi diri', '- Membantu orang lain belajar', '- Melaksanakan tugas dengan kualitas terbaik']],
                4 => ['Harmonis', ['- Menghargai setiap orang', '- Suka menolong orang lain', '- Membangun lingkungan kerja yang kondusif']],
                5 => ['Loyal', ['- Memegang teguh ideologi Pancasila, UUD 1945', '- Menjaga nama baik ASN, pimpinan, instansi', '- Menjaga rahasia jabatan dan negara']],
                6 => ['Adaptif', ['- Cepat menyesuaikan diri menghadapi perubahan', '- Terus berinovasi dan mengembangkan kreativitas', '- Bertindak proaktif']],
                7 => ['Kolaboratif', ['- Memberi kesempatan berbagai pihak berkontribusi', '- Terbuka dalam bekerja sama', '- Menggerakkan pemanfaatan sumber daya']]
            ];
            foreach ($akhlak_list as $no => $item):
                $aspek = $item[0];
                $standar = $item[1];
            ?>
              <tr>
                <td rowspan="3" class="text-center align-middle fw-bold"><?= $no ?></td>
                <td rowspan="3" class="align-middle fw-bold px-3"><?= $aspek ?></td>
                <td class="small"><?= htmlspecialchars($standar[0]) ?></td>
                <td><input type="text" name="akhlak_<?= $no ?>_1" class="form-control form-control-sm" value="<?= htmlspecialchars($form_data["akhlak_{$no}_1"] ?? '') ?>"></td>
                <?php if ($level && !empty($daftar_bawahan)): ?>
                  <td rowspan="3" class="align-middle">
                    <select name="akhlak_bawahan_<?= $no ?>[]" class="form-control select2-multiple" multiple="multiple">
                      <?php foreach ($daftar_bawahan as $b): ?>
                        <option value="<?= $b->id_peg ?>" 
                          <?= in_array($b->id_peg, json_decode($form_data["akhlak_bawahan_{$no}"] ?? '[]', true) ?: []) ? 'selected' : '' ?>>
                          <?= htmlspecialchars($b->nama) ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                  </td>
                <?php endif; ?>
              </tr>
              <tr>
                <td class="small"><?= htmlspecialchars($standar[1]) ?></td>
                <td><input type="text" name="akhlak_<?= $no ?>_2" class="form-control form-control-sm" value="<?= htmlspecialchars($form_data["akhlak_{$no}_2"] ?? '') ?>"></td>
              </tr>
              <tr>
                <td class="small"><?= htmlspecialchars($standar[2]) ?></td>
                <td><input type="text" name="akhlak_<?= $no ?>_3" class="form-control form-control-sm" value="<?= htmlspecialchars($form_data["akhlak_{$no}_3"] ?? '') ?>"></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="card mb-4 shadow-sm">
    <div class="card-header bg-warning text-dark d-flex justify-content-between align-items-center fw-bold">
        <span>D. SUMBER DAYA YANG DIBUTUHKAN</span>
        <div>
            <button type="button" class="btn btn-sm btn-dark me-2" onclick="addSumberDayaRow()">+</button>
            <button type="button" class="btn btn-sm btn-danger" onclick="removeSumberDayaRow()">×</button>
        </div>
    </div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-bordered mb-0" id="sumber-daya-table">
          <thead class="table-light text-center">
            <tr>
              <th width="50">NO</th>
              <th>JENIS SUMBER DAYA</th>
              <th>KEBUTUHAN</th>
              <th>KETERSEDIAAN</th>
            </tr>
          </thead>
          <tbody>
            <?php for ($i = 1; $i <= 3; $i++): ?>
              <tr>
                <td class="text-center align-middle fw-bold"><?= $i ?></td>
                <td><input type="text" name="sd_jenis_<?= $i ?>" class="form-control"></td>
                <td><input type="text" name="sd_kebutuhan_<?= $i ?>" class="form-control"></td>
                <td><input type="text" name="sd_ketersediaan_<?= $i ?>" class="form-control"></td>
              </tr>
            <?php endfor; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="card mb-4 shadow-sm">
    <div class="card-header bg-danger text-white fw-bold">E. SKEMA PERTANGGUNGJAWABAN</div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-bordered mb-0">
          <thead class="table-light text-center">
            <tr>
              <th width="150">PERIODE</th>
              <th>JENIS LAPORAN</th>
              <th>WAKTU PELAPORAN</th>
              <th>BUKTI KINERJA</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $periode_list = ['Harian', 'Mingguan', 'Bulanan', 'Triwulanan', 'Semesteran', 'Tahunan'];
            foreach ($periode_list as $idx => $p):
                $i = $idx + 1;
            ?>
            <tr>
              <td class="fw-bold px-3"><?= $p ?></td>
              <td><input type="text" name="lap_jenis_<?= $i ?>" class="form-control"></td>
              <td><input type="text" name="lap_waktu_<?= $i ?>" class="form-control"></td>
              <td><input type="text" name="lap_bukti_<?= $i ?>" class="form-control"></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="d-flex gap-2 mt-3 pb-5">
    <button type="submit" class="btn btn-primary btn-lg px-5 shadow" onclick="clearDraft()">
        <i class="bi bi-save"></i> Simpan Rencana Kinerja
    </button>
  </div>
</form>

<div class="modal fade" id="modalRHKKosong" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header border-0">
        <h5 class="modal-title">Perhatian</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body text-center py-4">
        <i class="bi bi-exclamation-triangle text-warning" style="font-size: 3rem;"></i>
        <p class="mt-3 fs-5">RHK Atasan tidak ada</p>
        <small class="text-muted">Pastikan atasan Anda sudah mengisi RHK terlebih dahulu.</small>
      </div>
      <div class="modal-footer border-0 justify-content-center">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
      </div>
    </div>
  </div>
</div>

<script>
// Penambahan fitur LocalStorage agar baris tidak hilang saat reload
const STORAGE_KEY = 'rhk_row_count_<?= $pegawai_id ?>';

function addRHKRow() {
    const table = document.querySelector('#rhk-table tbody');
    const rowCount = table.rows.length + 1;
    const row = document.createElement('tr');
    row.setAttribute('data-rhk-index', rowCount);

    let cols = `<td class="row-no text-center align-middle fw-bold">${rowCount}</td>`;
    
    <?php if ($level !== 'top_leader'): ?>
        cols += `<td class="p-2">
            <div class="d-flex h-100">
                <textarea name="rhk_atasan_${rowCount}" class="form-control flex-grow-1 auto-height" rows="2" placeholder="Tulis RHK Atasan..."></textarea>
                <input type="hidden" name="rhk_atasan_id_${rowCount}" value="${rowCount}">
            </div>
        </td>`;
    <?php endif; ?>
    
    cols += `<td class="p-2"><div class="d-flex h-100"><textarea name="rhk_rhk_${rowCount}" class="form-control flex-grow-1 auto-height" rows="2" placeholder="Tulis Rencana Hasil Kerja..."></textarea></div></td>`;
    cols += `<td class="align-top">
                <div class="indicator-container p-2" id="indicator-container-${rowCount}">
                    <div class="indicator-item border p-2 mb-2 bg-light shadow-sm">
                        <div class="row g-2">
                            <div class="col-12 mb-1">
                                <label class="small fw-bold text-success">Indikator:</label>
                                <input type="text" name="rhk_indikator_${rowCount}[]" class="form-control form-control-sm">
                            </div>
                            <div class="col-6">
                                <label class="small fw-bold text-success">Target:</label>
                                <input type="text" name="rhk_target_${rowCount}[]" class="form-control form-control-sm">
                            </div>
                            <div class="col-6">
                                <label class="small fw-bold text-success">Satuan:</label>
                                <input type="text" name="rhk_satuan_${rowCount}[]" class="form-control form-control-sm">
                            </div>
                            <?php if ($level && !empty($daftar_bawahan)): ?>
                            <div class="col-12 mt-2">
                                <label class="small fw-bold text-primary">Intervensi Bawahan:</label>
                                <select name="rhk_bawahan_${rowCount}_0[]" class="form-control select2-multiple" multiple="multiple">
                                    <?php foreach ($daftar_bawahan as $b): ?>
                                        <option value="<?= $b->id_peg ?>"><?= htmlspecialchars($b->nama) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="px-2 pb-2">
                  <button type="button" class="btn btn-xs btn-outline-primary" onclick="addIndicatorRow(${rowCount})">
                      <i class="bi bi-plus"></i> Tambah Indikator
                  </button>
                </div>
            </td>`;
    
    row.innerHTML = cols;
    table.appendChild(row);
    initSelect2();
    saveToDraft(); // Simpan perubahan ke draft
}

function removeRHKRow() {
    const table = document.querySelector('#rhk-table tbody');
    if (table.rows.length > 1) {
        if(confirm("Hapus baris terakhir Rencana Hasil Kerja?")) {
            table.deleteRow(-1);
            saveToDraft(); // Update jumlah baris di draft
        }
    }
}

// Fungsi Simpan ke LocalStorage
function saveToDraft() {
    const currentRows = document.querySelectorAll('#rhk-table tbody tr').length;
    localStorage.setItem(STORAGE_KEY, currentRows);
}

// Fungsi Hapus Draft setelah simpan permanen
function clearDraft() {
    localStorage.removeItem(STORAGE_KEY);
}

function addIndicatorRow(rhkIndex) {
    const container = document.getElementById(`indicator-container-${rhkIndex}`);
    const indicatorCount = container.getElementsByClassName('indicator-item').length;
    const div = document.createElement('div');
    div.className = 'indicator-item border p-2 mb-2 bg-white position-relative shadow-sm';
    
    let bawahanHtml = '';
    <?php if ($level && !empty($daftar_bawahan)): ?>
    bawahanHtml = `
        <div class="col-12 mt-2">
            <label class="small fw-bold text-primary">Intervensi Bawahan:</label>
            <select name="rhk_bawahan_${rhkIndex}_${indicatorCount}[]" class="form-control select2-multiple" multiple="multiple">
                <?php foreach ($daftar_bawahan as $b): ?>
                    <option value="<?= $b->id_peg ?>"><?= htmlspecialchars($b->nama) ?></option>
                <?php endforeach; ?>
            </select>
        </div>`;
    <?php endif; ?>

    div.innerHTML = `
        <button type="button" class="btn-close position-absolute top-0 end-0 m-1" style="font-size: 0.5rem;" onclick="this.parentElement.remove()"></button>
        <div class="row g-2">
            <div class="col-12 mb-1">
                <label class="small fw-bold text-success">Indikator:</label>
                <input type="text" name="rhk_indikator_${rhkIndex}[]" class="form-control form-control-sm">
            </div>
            <div class="col-6">
                <label class="small fw-bold text-success">Target:</label>
                <input type="text" name="rhk_target_${rhkIndex}[]" class="form-control form-control-sm">
            </div>
            <div class="col-6">
                <label class="small fw-bold text-success">Satuan:</label>
                <input type="text" name="rhk_satuan_${rhkIndex}[]" class="form-control form-control-sm">
            </div>
            ${bawahanHtml}
        </div>
    `;
    container.appendChild(div);
    initSelect2();
}

function addSumberDayaRow() {
    const table = document.getElementById('sumber-daya-table').getElementsByTagName('tbody')[0];
    const rowCount = table.rows.length + 1;
    const row = table.insertRow();
    row.innerHTML = `
        <td class="text-center align-middle fw-bold">${rowCount}</td>
        <td><input type="text" name="sd_jenis_${rowCount}" class="form-control"></td>
        <td><input type="text" name="sd_kebutuhan_${rowCount}" class="form-control"></td>
        <td><input type="text" name="sd_ketersediaan_${rowCount}" class="form-control"></td>
    `;
}

function removeSumberDayaRow() {
    const table = document.getElementById('sumber-daya-table').getElementsByTagName('tbody')[0];
    if (table.rows.length > 1) {
        table.deleteRow(-1);
    }
}

function initSelect2() {
    $('.select2-multiple').each(function() {
        if (!$(this).hasClass("select2-hidden-accessible")) {
            $(this).select2({
                placeholder: "Pilih bawahan...",
                allowClear: true,
                width: '100%'
            });
        }
    });
}

$(document).ready(function() {
    initSelect2();

    // LOGIKA AUTO-RESTORE SAAT RELOAD
    const savedRows = localStorage.getItem(STORAGE_KEY);
    const phpInitialRows = <?= $initial_count ?>;

    if (savedRows && parseInt(savedRows) > phpInitialRows) {
        const rowsToRestore = parseInt(savedRows) - phpInitialRows;
        for (let i = 0; i < rowsToRestore; i++) {
            addRHKRow(); // Memanggil fungsi tambah baris hingga sesuai jumlah tersimpan
        }
    }
});

function checkRHKAtasan() {
    // Contoh Logika: Cek apakah data RHK Atasan tersedia
    // Anda bisa mengganti kondisi ini sesuai dengan data dari backend/DOM Anda
    let rhkAtasanTersedia = true; // Set ke false untuk simulasi tidak ada data

    if (!rhkAtasanTersedia) {
        // Tampilkan modal jika tidak ada data
        var myModal = new bootstrap.Modal(document.getElementById('modalRHKKosong'));
        myModal.show();
    } else {
        // Jalankan fungsi tambah baris yang asli jika data ada
        addRHKRow();
    }
}
</script>

<style>
    .btn-xs { padding: 0.2rem 0.4rem; font-size: 0.7rem; }
    #rhk-table td { height: 1px; } 
    .auto-height { 
        min-height: 100px; 
        resize: vertical; 
        border: 1px solid #dee2e6;
    }
    .indicator-item { 
        border-radius: 8px; 
        border-left: 5px solid #198754 !important; 
    }
    textarea.form-control:focus {
        background-color: #fff9e6;
        border-color: #ffc107;
        box-shadow: none;
    }
</style>

  </div>
</div>

