<?php
  $pel = $pelayanan['pelayanan'] ?? null;
  $anam = $pelayanan['anamnesis'] ?? null;
  $vital = $pelayanan['vital'] ?? null;
  $cppt = $pelayanan['cppt'] ?? null;
  $diagnosis = $pelayanan['diagnosis'] ?? [];
  $tindakan = $pelayanan['tindakan'] ?? [];
  $terapi = $pelayanan['terapi'] ?? [];
  $resep = $pelayanan['resep'] ?? null;
?>

<div class="content-header d-flex justify-content-between align-items-center">
  <h4><i class="fas fa-notes-medical"></i> Pelayanan Klinik Dokter</h4>
  <a href="<?= site_url('pelayanan'); ?>" class="btn btn-outline-secondary btn-sm">
    <i class="fas fa-arrow-left"></i> Kembali
  </a>
</div>

<?php if ($this->session->flashdata('success')): ?>
  <div class="alert alert-success"><?= $this->session->flashdata('success'); ?></div>
<?php endif; ?>
<?php if ($this->session->flashdata('error')): ?>
  <div class="alert alert-danger"><?= $this->session->flashdata('error'); ?></div>
<?php endif; ?>

<div class="card">
  <div class="card-header">Informasi Pasien</div>
  <div class="card-body">
    <div class="row">
      <div class="col-md-4">
        <p><strong>No RM:</strong> <?= $registrasi->rme_no; ?></p>
        <p><strong>Nama:</strong> <?= $registrasi->nama_lengkap; ?></p>
      </div>
      <div class="col-md-4">
        <p><strong>Tgl Lahir:</strong> <?= $registrasi->tanggal_lahir; ?></p>
        <p><strong>Jenis Kelamin:</strong> <?= $registrasi->jenis_kelamin === 'L' ? 'Laki-laki' : 'Perempuan'; ?></p>
      </div>
      <div class="col-md-4">
        <p><strong>Poli:</strong> <?= $registrasi->nama_poli; ?></p>
        <p><strong>Dokter:</strong> <?= $registrasi->nama_dokter ?: '-'; ?></p>
        <p><strong>Status Resep Farmasi:</strong> <?= $resep ? html_escape($resep->status_resep) : 'Belum Dibuat'; ?></p>
      </div>
    </div>
  </div>
</div>

<form method="post">
  <div class="card">
    <div class="card-header">Anamnesis</div>
    <div class="card-body">
      <div class="form-group">
        <label>Keluhan Utama</label>
        <textarea name="keluhan_utama" class="form-control" rows="2"><?= html_escape($anam->keluhan_utama ?? ''); ?></textarea>
      </div>
      <div class="form-group">
        <label>Riwayat Penyakit Sekarang</label>
        <textarea name="riwayat_penyakit_sekarang" class="form-control" rows="2"><?= html_escape($anam->riwayat_penyakit_sekarang ?? ''); ?></textarea>
      </div>
      <div class="form-group">
        <label>Riwayat Penyakit Dahulu</label>
        <textarea name="riwayat_penyakit_dahulu" class="form-control" rows="2"><?= html_escape($anam->riwayat_penyakit_dahulu ?? ''); ?></textarea>
      </div>
      <div class="form-group">
        <label>Riwayat Alergi</label>
        <textarea name="riwayat_alergi" class="form-control" rows="2"><?= html_escape($anam->riwayat_alergi ?? ''); ?></textarea>
      </div>
      <div class="form-group">
        <label>Riwayat Pengobatan</label>
        <textarea name="riwayat_pengobatan" class="form-control" rows="2"><?= html_escape($anam->riwayat_pengobatan ?? ''); ?></textarea>
      </div>
      <div class="form-group">
        <label>Riwayat Keluarga</label>
        <textarea name="riwayat_keluarga" class="form-control" rows="2"><?= html_escape($anam->riwayat_keluarga ?? ''); ?></textarea>
      </div>
      <div class="form-group">
        <label>Riwayat Sosial</label>
        <textarea name="riwayat_sosial" class="form-control" rows="2"><?= html_escape($anam->riwayat_sosial ?? ''); ?></textarea>
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-header">Pemeriksaan Fisik / Vital Sign</div>
    <div class="card-body">
      <div class="form-row">
        <div class="form-group col-md-3">
          <label>Tekanan Darah</label>
          <input type="text" name="tekanan_darah" class="form-control" value="<?= html_escape($vital->tekanan_darah ?? ''); ?>" placeholder="120/80">
        </div>
        <div class="form-group col-md-3">
          <label>Nadi (x/menit)</label>
          <input type="number" name="nadi" class="form-control" value="<?= html_escape($vital->nadi ?? ''); ?>">
        </div>
        <div class="form-group col-md-3">
          <label>Respirasi (x/menit)</label>
          <input type="number" name="respirasi" class="form-control" value="<?= html_escape($vital->respirasi ?? ''); ?>">
        </div>
        <div class="form-group col-md-3">
          <label>Suhu (C)</label>
          <input type="text" name="suhu" class="form-control" value="<?= html_escape($vital->suhu ?? ''); ?>">
        </div>
      </div>
      <div class="form-row">
        <div class="form-group col-md-3">
          <label>Tinggi (cm)</label>
          <input type="text" name="tinggi" class="form-control" value="<?= html_escape($vital->tinggi ?? ''); ?>">
        </div>
        <div class="form-group col-md-3">
          <label>Berat (kg)</label>
          <input type="text" name="berat" class="form-control" value="<?= html_escape($vital->berat ?? ''); ?>">
        </div>
        <div class="form-group col-md-3">
          <label>Lingkar Perut (cm)</label>
          <input type="text" name="lingkar_perut" class="form-control" value="<?= html_escape($vital->lingkar_perut ?? ''); ?>">
        </div>
        <div class="form-group col-md-3">
          <label>SpO2 (%)</label>
          <input type="text" name="spo2" class="form-control" value="<?= html_escape($vital->spo2 ?? ''); ?>">
        </div>
      </div>
      <div class="form-group">
        <label>IMT</label>
        <input type="text" name="imt" class="form-control" value="<?= html_escape($vital->imt ?? ''); ?>">
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <span>Diagnosis ICD-10</span>
      <button type="button" class="btn btn-sm btn-outline-primary" onclick="addRow('diagnosis-table')">
        <i class="fas fa-plus"></i> Tambah
      </button>
    </div>
    <div class="card-body table-responsive">
      <table class="table table-bordered" id="diagnosis-table">
        <thead>
          <tr>
            <th>Kode</th>
            <th>Nama Diagnosis</th>
            <th>Tipe</th>
            <th>Catatan</th>
            <th width="80">Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!empty($diagnosis)): ?>
            <?php foreach ($diagnosis as $row): ?>
              <tr>
                <td><input type="text" name="diagnosis_kode[]" class="form-control" value="<?= html_escape($row->kode_icd10); ?>"></td>
                <td><input type="text" name="diagnosis_nama[]" class="form-control" value="<?= html_escape($row->nama_diagnosis); ?>"></td>
                <td>
                  <select name="diagnosis_tipe[]" class="form-control">
                    <option value="UTAMA" <?= $row->tipe === 'UTAMA' ? 'selected' : ''; ?>>UTAMA</option>
                    <option value="SEKUNDER" <?= $row->tipe === 'SEKUNDER' ? 'selected' : ''; ?>>SEKUNDER</option>
                  </select>
                </td>
                <td><input type="text" name="diagnosis_catatan[]" class="form-control" value="<?= html_escape($row->catatan); ?>"></td>
                <td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeRow(this)">Hapus</button></td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr>
              <td><input type="text" name="diagnosis_kode[]" class="form-control"></td>
              <td><input type="text" name="diagnosis_nama[]" class="form-control"></td>
              <td>
                <select name="diagnosis_tipe[]" class="form-control">
                  <option value="UTAMA">UTAMA</option>
                  <option value="SEKUNDER">SEKUNDER</option>
                </select>
              </td>
              <td><input type="text" name="diagnosis_catatan[]" class="form-control"></td>
              <td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeRow(this)">Hapus</button></td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <span>Tindakan ICD-9-CM</span>
      <button type="button" class="btn btn-sm btn-outline-primary" onclick="addRow('tindakan-table')">
        <i class="fas fa-plus"></i> Tambah
      </button>
    </div>
    <div class="card-body table-responsive">
      <table class="table table-bordered" id="tindakan-table">
        <thead>
          <tr>
            <th>Kode</th>
            <th>Nama Tindakan</th>
            <th>Catatan</th>
            <th width="80">Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!empty($tindakan)): ?>
            <?php foreach ($tindakan as $row): ?>
              <tr>
                <td><input type="text" name="tindakan_kode[]" class="form-control" value="<?= html_escape($row->kode_icd9); ?>"></td>
                <td><input type="text" name="tindakan_nama[]" class="form-control" value="<?= html_escape($row->nama_tindakan); ?>"></td>
                <td><input type="text" name="tindakan_catatan[]" class="form-control" value="<?= html_escape($row->catatan); ?>"></td>
                <td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeRow(this)">Hapus</button></td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr>
              <td><input type="text" name="tindakan_kode[]" class="form-control"></td>
              <td><input type="text" name="tindakan_nama[]" class="form-control"></td>
              <td><input type="text" name="tindakan_catatan[]" class="form-control"></td>
              <td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeRow(this)">Hapus</button></td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <span>Terapi (Resep Obat)</span>
      <button type="button" class="btn btn-sm btn-outline-primary" onclick="addRow('terapi-table')">
        <i class="fas fa-plus"></i> Tambah
      </button>
    </div>
    <div class="card-body table-responsive">
      <table class="table table-bordered" id="terapi-table">
        <thead>
          <tr>
            <th>Master Obat</th>
            <th>Nama Obat</th>
            <th>Dosis</th>
            <th>Frekuensi</th>
            <th>Rute</th>
            <th>Durasi</th>
            <th>Jumlah</th>
            <th>Satuan</th>
            <th>Catatan</th>
            <th width="80">Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!empty($terapi)): ?>
            <?php foreach ($terapi as $row): ?>
              <tr>
                <td>
                  <select name="terapi_obat_id[]" class="form-control terapi-obat-select" onchange="syncObatRow(this)">
                    <option value="">Pilih master obat</option>
                    <?php foreach ($list_obat as $obat): ?>
                      <option
                        value="<?= $obat->obat_id; ?>"
                        data-nama="<?= html_escape($obat->nama_obat); ?>"
                        data-satuan="<?= html_escape($obat->satuan_kecil); ?>"
                        <?= ($row->obat_id ?? '') === $obat->obat_id ? 'selected' : ''; ?>
                      >
                        <?= html_escape($obat->kode_obat . ' - ' . $obat->nama_obat); ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </td>
                <td><input type="text" name="terapi_nama[]" class="form-control terapi-nama" value="<?= html_escape($row->nama_obat); ?>"></td>
                <td><input type="text" name="terapi_dosis[]" class="form-control" value="<?= html_escape($row->dosis); ?>"></td>
                <td><input type="text" name="terapi_frekuensi[]" class="form-control" value="<?= html_escape($row->frekuensi); ?>"></td>
                <td><input type="text" name="terapi_rute[]" class="form-control" value="<?= html_escape($row->rute); ?>"></td>
                <td><input type="text" name="terapi_durasi[]" class="form-control" value="<?= html_escape($row->durasi); ?>"></td>
                <td><input type="text" name="terapi_jumlah[]" class="form-control" value="<?= html_escape($row->jumlah); ?>"></td>
                <td><input type="text" name="terapi_satuan[]" class="form-control terapi-satuan" value="<?= html_escape($row->satuan ?? ''); ?>"></td>
                <td><input type="text" name="terapi_catatan[]" class="form-control" value="<?= html_escape($row->catatan); ?>"></td>
                <td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeRow(this)">Hapus</button></td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr>
              <td>
                <select name="terapi_obat_id[]" class="form-control terapi-obat-select" onchange="syncObatRow(this)">
                  <option value="">Pilih master obat</option>
                  <?php foreach ($list_obat as $obat): ?>
                    <option value="<?= $obat->obat_id; ?>" data-nama="<?= html_escape($obat->nama_obat); ?>" data-satuan="<?= html_escape($obat->satuan_kecil); ?>">
                      <?= html_escape($obat->kode_obat . ' - ' . $obat->nama_obat); ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </td>
              <td><input type="text" name="terapi_nama[]" class="form-control terapi-nama"></td>
              <td><input type="text" name="terapi_dosis[]" class="form-control"></td>
              <td><input type="text" name="terapi_frekuensi[]" class="form-control"></td>
              <td><input type="text" name="terapi_rute[]" class="form-control"></td>
              <td><input type="text" name="terapi_durasi[]" class="form-control"></td>
              <td><input type="text" name="terapi_jumlah[]" class="form-control"></td>
              <td><input type="text" name="terapi_satuan[]" class="form-control terapi-satuan"></td>
              <td><input type="text" name="terapi_catatan[]" class="form-control"></td>
              <td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeRow(this)">Hapus</button></td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="card">
    <div class="card-header">Instruksi / Resume (CPPT)</div>
    <div class="card-body">
      <div class="form-group">
        <label>Subjektif</label>
        <textarea name="cppt_subjektif" class="form-control" rows="2"><?= html_escape($cppt->subjektif ?? ''); ?></textarea>
      </div>
      <div class="form-group">
        <label>Objektif</label>
        <textarea name="cppt_objektif" class="form-control" rows="2"><?= html_escape($cppt->objektif ?? ''); ?></textarea>
      </div>
      <div class="form-group">
        <label>Asesmen</label>
        <textarea name="cppt_asesmen" class="form-control" rows="2"><?= html_escape($cppt->asesmen ?? ''); ?></textarea>
      </div>
      <div class="form-group">
        <label>Plan</label>
        <textarea name="cppt_plan" class="form-control" rows="2"><?= html_escape($cppt->plan ?? ''); ?></textarea>
      </div>
      <div class="form-group">
        <label>Instruksi / Resume</label>
        <textarea name="cppt_instruksi" class="form-control" rows="3"><?= html_escape($cppt->instruksi ?? ''); ?></textarea>
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-body d-flex justify-content-between align-items-center">
      <div class="form-inline">
        <label class="mr-2">Tanggal Pelayanan</label>
        <input type="date" name="tanggal_pelayanan" class="form-control mr-3" value="<?= html_escape($pel->tanggal_pelayanan ?? $registrasi->tanggal_registrasi); ?>">
        <label class="mr-2">Status</label>
        <select name="status_pelayanan" class="form-control">
          <option value="DRAFT" <?= ($pel->status_pelayanan ?? 'DRAFT') === 'DRAFT' ? 'selected' : ''; ?>>DRAFT</option>
          <option value="SELESAI" <?= ($pel->status_pelayanan ?? '') === 'SELESAI' ? 'selected' : ''; ?>>SELESAI</option>
        </select>
      </div>
      <button type="submit" class="btn btn-success">
        <i class="fas fa-save"></i> Simpan
      </button>
    </div>
  </div>
</form>

<script>
  function syncObatRow(selectEl) {
    const row = selectEl.closest('tr');
    if (!row) return;
    const option = selectEl.options[selectEl.selectedIndex];
    const nama = row.querySelector('.terapi-nama');
    const satuan = row.querySelector('.terapi-satuan');
    if (option && option.value) {
      if (nama && !nama.value) {
        nama.value = option.getAttribute('data-nama') || '';
      }
      if (satuan && !satuan.value) {
        satuan.value = option.getAttribute('data-satuan') || '';
      }
    }
  }

  function removeRow(btn) {
    const row = btn.closest('tr');
    if (row && row.parentNode.children.length > 1) {
      row.parentNode.removeChild(row);
    }
  }

  function addRow(tableId) {
    const table = document.getElementById(tableId);
    if (!table) return;
    const body = table.querySelector('tbody');
    const firstRow = body.querySelector('tr');
    if (!firstRow) return;
    const clone = firstRow.cloneNode(true);
    clone.querySelectorAll('input, select').forEach(el => {
      if (el.tagName === 'SELECT') {
        el.selectedIndex = 0;
      } else {
        el.value = '';
      }
    });
    body.appendChild(clone);
  }
</script>
