<?php
    require_once('conf/conf.php');
    
    // Proses penyimpanan data
    if($_SERVER['REQUEST_METHOD'] == "POST") {
        $no_rawat = $_POST['no_rawat'];
        $kd_dokter = $_POST['kd_dokter'];
        $diagnosa_awal = $_POST['diagnosa_awal'];
        $alasan = $_POST['alasan'];
        $keluhan_utama = $_POST['keluhan_utama'];
        $pemeriksaan_fisik = $_POST['pemeriksaan_fisik'];
        $jalannya_penyakit = $_POST['jalannya_penyakit'];
        $pemeriksaan_penunjang = $_POST['pemeriksaan_penunjang'];
        $diagnosa_utama = $_POST['diagnosa_utama'];
        $kd_diagnosa_utama = $_POST['kd_diagnosa_utama'];
        $diagnosa_sekunder = $_POST['diagnosa_sekunder'];
        $kd_diagnosa_sekunder = $_POST['kd_diagnosa_sekunder'];
        $prosedur_utama = $_POST['prosedur_utama'];
        $kd_prosedur_utama = $_POST['kd_prosedur_utama'];
        $cara_keluar = $_POST['cara_keluar'];
        $ket_keluar = $_POST['ket_keluar'];
        $alergi = $_POST['alergi'];
        $diet = $_POST['diet'];
        $edukasi = $_POST['edukasi'];
        $hasil_laborat = $_POST['hasil_laborat'];
        $tindakan_dan_operasi = $_POST['tindakan_dan_operasi'];
        $obat_di_rs = $_POST['obat_di_rs'];
        $lab_belum = $_POST['lab_belum'];
        $obat_pulang = $_POST['obat_pulang'];
        $dilanjutkan = $_POST['dilanjutkan'];
        $kontrol = $_POST['kontrol'];

        // Format tanggal kontrol
        $kontrol = date('Y-m-d H:i:s', strtotime($kontrol));

        $query = "INSERT INTO resume_pasien_ranap 
                 (no_rawat, kd_dokter, diagnosa_awal, alasan, keluhan_utama, pemeriksaan_fisik,
                  jalannya_penyakit, pemeriksaan_penunjang, diagnosa_utama, kd_diagnosa_utama,
                  diagnosa_sekunder, kd_diagnosa_sekunder, prosedur_utama, kd_prosedur_utama,
                  cara_keluar, ket_keluar, alergi, diet, edukasi, hasil_laborat, tindakan_dan_operasi, obat_di_rs, lab_belum, obat_pulang, dilanjutkan, kontrol) 
                 VALUES 
                 ('$no_rawat', '$kd_dokter', '$diagnosa_awal', '$alasan', '$keluhan_utama',
                  '$pemeriksaan_fisik', '$jalannya_penyakit', '$pemeriksaan_penunjang',
                  '$diagnosa_utama', '$kd_diagnosa_utama', '$diagnosa_sekunder', '$kd_diagnosa_sekunder',
                  '$prosedur_utama', '$kd_prosedur_utama', '$cara_keluar', '$ket_keluar',
                  '$alergi', '$diet', '$edukasi', '$hasil_laborat', '$tindakan_dan_operasi', '$obat_di_rs', '$lab_belum', '$obat_pulang', '$dilanjutkan', '$kontrol')";

        if(bukaquery($query)) {
            echo "<script>
                    alert('Data resume berhasil disimpan');
                    
                    window.history.back()
                  </script>";
        } else {
            echo "<script>
                    alert('Gagal menyimpan data resume');
                  </script>";
        }
    }

    // Ambil parameter no_rawat yang dienkripsi
    $norawat = isset($_GET['iyem']) ? encrypt_decrypt(urldecode($_GET['iyem']),"d") : "";
    if($norawat!=""){
        $norawat = json_decode($norawat, true);
        $norawat = $norawat['norawat'];
    }

    // Query untuk mengambil data pasien
    $query_pasien = bukaquery("SELECT reg_periksa.no_rkm_medis, pasien.nm_pasien, reg_periksa.kd_dokter, dokter.nm_dokter
                              FROM reg_periksa 
                              INNER JOIN pasien ON reg_periksa.no_rkm_medis=pasien.no_rkm_medis 
                              INNER JOIN dokter ON reg_periksa.kd_dokter=dokter.kd_dokter
                              WHERE reg_periksa.no_rawat='$norawat'");
    
    if($result_pasien = mysqli_fetch_array($query_pasien)) {
        $no_rkm_medis = $result_pasien['no_rkm_medis'];
        $nama_pasien = $result_pasien['nm_pasien'];
        $kd_dokter = $result_pasien['kd_dokter'];
        $nm_dokter = $result_pasien['nm_dokter'];
    }

    // Tambahkan di bagian awal file untuk debugging
    if (isset($norawat)) {
        echo "<!-- Debug: norawat = $norawat -->";
    }
?>

<link href="plugins/bootstrap-select/css/bootstrap-select.min.css" rel="stylesheet" />
<script src="plugins/bootstrap-select/js/bootstrap-select.min.js"></script>

<div class="block-header">
    <h2><center><strong>INPUT RESUME MEDIS RAWAT INAP</strong></center></h2>
</div>

<div class="row clearfix">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        <div class="card">
            <div class="header">
                <h2>Data Pasien</h2>
            </div>
            <div class="body">
                <form id="form_resume_ranap" method="post" action="">
                    <input type="hidden" name="no_rawat" value="<?php echo $norawat; ?>">
                    
                    <!-- Data Pasien -->
                    <div class="row clearfix">
                        <div class="col-sm-4">
                            <div class="form-group">
                                <label>No. Rekam Medis</label>
                                <div class="form-line">
                                    <input type="text" class="form-control" value="<?php echo $no_rkm_medis; ?>" readonly>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <div class="form-group">
                                <label>Nama Pasien</label>
                                <div class="form-line">
                                    <input type="text" class="form-control" value="<?php echo $nama_pasien; ?>" readonly>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <div class="form-group">
                                <label>DPJP</label>
                                <select name="kd_dokter" class="form-control selectpicker" data-live-search="true" required>
                                    <option value="<?php echo $kd_dokter; ?>"><?php echo $nm_dokter; ?></option>
                                    <?php
                                    $query_dokter = bukaquery("SELECT kd_dokter, nm_dokter FROM dokter WHERE status='1' ORDER BY nm_dokter");
                                    while($row_dokter = mysqli_fetch_array($query_dokter)) {
                                        if($row_dokter['kd_dokter'] != $kd_dokter) {
                                            echo "<option value='".$row_dokter['kd_dokter']."'>".$row_dokter['nm_dokter']."</option>";
                                        }
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Riwayat Perawatan -->
                    <h4 class="card-inside-title">Riwayat Perawatan</h4>
                    <div class="row clearfix">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Diagnosa Awal</label>
                                <div class="form-line">
                                    <textarea rows="4" class="form-control no-resize" name="diagnosa_awal" required></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Keluhan Utama</label>
                                <div class="form-line">
                                    <textarea rows="4" class="form-control no-resize" name="keluhan_utama" required></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Alasan Masuk Dirawat</label>
                                <div class="form-line">
                                    <textarea rows="4" class="form-control no-resize" name="alasan" required></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Riwayat Penyakit Dahulu</label>
                                <div class="form-line">
                                    <textarea rows="4" class="form-control no-resize" name="riwayat_penyakit"></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-12" style="margin-bottom: 20px;">
                            <div class="row">
                                <div class="col-sm-3">
                                    <button type="button" class="btn btn-primary waves-effect btn-block" onclick="ambilAssesmentRanap()">
                                        <i class="material-icons">content_copy</i>
                                        <span>AMBIL ASESMEN RAWAT INAP</span>
                                    </button>
                                </div>
                                <div class="col-sm-3">
                                    <button type="button" class="btn btn-primary waves-effect btn-block" onclick="ambilAssesmentIGD()">
                                        <i class="material-icons">content_copy</i>
                                        <span>AMBIL ASESMEN AWAL IGD</span>
                                    </button>
                                </div>
                                <div class="col-sm-3">
                                    <button type="button" class="btn btn-primary waves-effect btn-block" onclick="ambilCPPTAwal()">
                                        <i class="material-icons">content_copy</i>
                                        <span>AMBIL CPPT AWAL</span>
                                    </button>
                                </div>
                                <div class="col-sm-3">
                                    <button type="button" class="btn btn-primary waves-effect btn-block" onclick="ambilCPPTAkhir()">
                                        <i class="material-icons">content_copy</i>
                                        <span>AMBIL CPPT TERAKHIR</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Pemeriksaan Fisik dan Penunjang -->
                    <h4 class="card-inside-title">Pemeriksaan</h4>
                    <div class="row clearfix">
                        <!-- Kolom Kiri -->
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Pemeriksaan Fisik</label>
                                <div class="form-line">
                                    <textarea rows="4" class="form-control no-resize" name="pemeriksaan_fisik" required></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Pemeriksaan Penunjang</label>
                                <div class="form-line">
                                    <textarea rows="4" class="form-control no-resize" name="pemeriksaan_penunjang"></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Hasil Laborat</label>
                                <div class="input-group">
                                <div class="form-line">
                                    <textarea rows="4" class="form-control no-resize" name="hasil_laborat"></textarea>
                                    </div>
                                    <span class="input-group-addon">
                                        <button type="button" class="btn btn-primary btn-xs waves-effect" onclick="salinHasilLab()">
                                            <i class="material-icons" style="font-size: 16px;">content_copy</i>
                                        </button>
                                    </span>
                                </div>
                            </div>
                        </div>

                        <!-- Kolom Kanan -->
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Jalannya Penyakit</label>
                                <div class="form-line">
                                    <textarea rows="4" class="form-control no-resize" name="jalannya_penyakit" required></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Tindakan/Operasi</label>
                                <div class="form-line">
                                    <textarea rows="4" class="form-control no-resize" name="tindakan_dan_operasi"></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Obat Selama Rawat</label>
                                <div class="input-group">
                                <div class="form-line">
                                    <textarea rows="4" class="form-control no-resize" name="obat_di_rs"></textarea>
                                </div>
                                    <span class="input-group-addon">
                                        <button type="button" class="btn btn-primary btn-xs waves-effect" onclick="salinObatRawat()">
                                            <i class="material-icons" style="font-size: 16px;">content_copy</i>
                            </button>
                                    </span>
</div>
                            </div>
                        </div>
                        <div class="col-sm-12" style="margin-bottom: 20px;">
                            <div class="row">
                                <div class="col-sm-3">
                                    <button type="button" class="btn btn-primary waves-effect btn-block" onclick="bukaFormTemplate()">
                                        <i class="material-icons">content_copy</i>
                                        <span>AMBIL TEMPLATE</span>
                                    </button>
                                </div>
                                <!-- <div class="col-sm-3">
                                    <button type="button" class="btn btn-success waves-effect btn-block" onclick="jadikanTemplate()">
                                        <i class="material-icons">save</i>
                                        <span>JADIKAN TEMPLATE</span>
                                    </button>
                                </div> -->
                            </div>
                        </div>           
                    </div>

                    <!-- Diagnosa & Prosedur -->
                    <h4 class="card-inside-title">Diagnosa & Prosedur</h4>
                    <div class="row clearfix">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Diagnosa Utama</label>
                                <div class="form-line">
                                    <input type="text" class="form-control" name="diagnosa_utama" required>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Kode ICD Diagnosa Utama</label>
                                <div class="form-line">
                                    <input type="text" class="form-control" name="kd_diagnosa_utama" required>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Diagnosa Sekunder -->
                    <div class="row clearfix">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Diagnosa Sekunder 1</label>
                                <div class="form-line">
                                    <input type="text" class="form-control" name="diagnosa_sekunder">
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Kode ICD Diagnosa Sekunder 1</label>
                                <div class="form-line">
                                    <input type="text" class="form-control" name="kd_diagnosa_sekunder">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Prosedur -->
                    <div class="row clearfix">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Prosedur Utama</label>
                                <div class="form-line">
                                    <input type="text" class="form-control" name="prosedur_utama">
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Kode ICD Prosedur Utama</label>
                                <div class="form-line">
                                    <input type="text" class="form-control" name="kd_prosedur_utama">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Kondisi Pulang -->
                    <h4 class="card-inside-title">Kondisi Pulang</h4>
                    <div class="row clearfix">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Cara Keluar</label>
                                <select name="cara_keluar" class="form-control selectpicker" required>
                                    <option value="">-- Pilih Cara Keluar --</option>
                                    <option value="Atas Izin Dokter">Atas Izin Dokter</option>
                                    <option value="Pindah RS">Pindah RS</option>
                                    <option value="Pulang Atas Permintaan Sendiri">Pulang Atas Permintaan Sendiri</option>
                                    <option value="Lainnya">Lainnya</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Keadaan Pulang</label>
                                <select name="keadaan" class="form-control selectpicker" required>
                                    <option value="">-- Pilih Keadaan Pulang --</option>
                                    <option value="Membaik">Membaik</option>
                                    <option value="Sembuh">Sembuh</option>
                                    <option value="Keadaan Khusus">Keadaan Khusus</option>
                                    <option value="Meninggal">Meninggal</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-sm-12">
                            <div class="form-group">
                                <label>Keterangan Pulang</label>
                                <div class="form-line">
                                    <input type="text" class="form-control" name="ket_keluar">
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Lab Belum Selesai</label>
                                <div class="form-line">
                                    <textarea rows="2" class="form-control no-resize" name="lab_belum"></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Obat Pulang</label>
                                <div class="input-group">
                                    <div class="form-line">
                                        <textarea rows="2" class="form-control no-resize" name="obat_pulang"></textarea>
                                    </div>
                                    <span class="input-group-addon">
                                        <button type="button" class="btn btn-primary btn-xs waves-effect" onclick="salinObatPulang()">
                                            <i class="material-icons" style="font-size: 16px;">content_copy</i>
                                        </button>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Kondisi Akhir & Anjuran -->
                    <h4 class="card-inside-title">Kondisi Akhir & Anjuran</h4>
                    <div class="row clearfix">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Alergi</label>
                                <div class="form-line">
                                    <textarea rows="2" class="form-control no-resize" name="alergi"></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Diet</label>
                                <div class="form-line">
                                    <textarea rows="2" class="form-control no-resize" name="diet"></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-12">
                            <div class="form-group">
                                <label>Edukasi</label>
                                <div class="form-line">
                                    <textarea rows="4" class="form-control no-resize" name="edukasi"></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Dilanjutkan</label>
                                <select name="dilanjutkan" class="form-control selectpicker" required>
                                    <option value="">-- Pilih Tindak Lanjut --</option>
                                    <option value="Kembali Ke RS">Kembali Ke RS</option>
                                    <option value="RS Lain">RS Lain</option>
                                    <option value="Dokter Luar">Dokter Luar</option>
                                    <option value="Puskesmas">Puskesmas</option>
                                    <option value="Lainnya">Lainnya</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>Kontrol Kembali</label>
                                <div class="form-line">
                                    <input type="datetime-local" class="form-control" name="kontrol" value="<?php echo date('Y-m-d\TH:i:s'); ?>">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row clearfix">
                        <div class="col-sm-12">
                            <button type="submit" class="btn btn-primary waves-effect">
                                <i class="material-icons">save</i>
                                <span>SIMPAN</span>
                            </button>
                            <button type="button" class="btn btn-danger waves-effect" onclick="window.history.back()">
                                <i class="material-icons">close</i>
                                <span>TUTUP</span>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Modal Template -->
<div class="modal fade" id="modalTemplate" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Template Resume</h4>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-striped table-hover" id="tabelTemplate">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Keluhan Utama</th>
                                <th>Diagnosa Awal</th>
                                <th>Diagnosa Utama</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            // Ambil kd_dokter dari session
                            $kd_dokter = encrypt_decrypt($_SESSION["ses_dokter"],"d");
                            
                            // Query untuk mengambil template milik dokter yang login
                            $sql = "SELECT * FROM template_resume_pasien_ranap 
                                   WHERE kd_dokter = '$kd_dokter' 
                                   ORDER BY diagnosa_awal ASC";
                            $hasil = bukaquery($sql);
                            $no = 1;
                            while($row = mysqli_fetch_array($hasil)) {
                                // Escape data untuk keamanan
                                $data = array_map(function($value) {
                                    return str_replace('"', '&quot;', $value);
                                }, $row);
                            ?>
                            <tr>
                                <td><?php echo $no++; ?></td>
                                <td><?php echo $data['keluhan_utama']; ?></td>
                                <td><?php echo $data['diagnosa_awal']; ?></td>
                                <td><?php echo $data['diagnosa_utama']; ?></td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-primary btn-xs waves-effect" 
                                            onclick='pilihTemplate(<?php echo json_encode($data); ?>)'>
                                        <i class="material-icons">content_copy</i>
                                    </button>
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger waves-effect" data-dismiss="modal">TUTUP</button>
            </div>
        </div>
    </div>
</div>

<!-- Tambahkan CSS untuk memperbaiki tampilan selectpicker -->
<style>
    .bootstrap-select {
        width: 100% !important;
    }
    .bootstrap-select .dropdown-toggle {
        border: 1px solid #ddd !important;
        padding: 8px 12px;
    }
    .bootstrap-select.btn-group .dropdown-toggle .filter-option {
        text-align: left;
        font-size: 14px;
    }
    .bootstrap-select.btn-group .dropdown-menu {
        max-height: 300px !important;
    }
    .bootstrap-select.btn-group .dropdown-menu li a {
        padding: 8px 12px;
    }
    .card-inside-title {
        margin: 20px 0 10px 0;
        color: #555;
        font-weight: bold;
        border-bottom: 1px solid #eee;
        padding-bottom: 10px;
    }
    .form-group textarea.form-control {
        resize: none;
        min-height: 100px;
    }
    .form-group label {
        font-weight: bold;
        margin-bottom: 8px;
        color: #555;
    }
    .form-line {
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 0 5px;
    }
    .form-line textarea {
        border: none;
    }
    .form-line:focus-within {
        border-color: #2196F3;
    }
    .input-group-addon {
        padding: 0;
        border: none;
        background: none;
    }
    .input-group-addon button {
        margin: 0;
        height: 30px;
        width: 30px;
        padding: 0;
    }
    .input-group-addon button i {
        line-height: 30px;
    }
    .input-group .form-line {
        width: calc(100% - 35px);
        float: left;
    }
    .modal-lg {
        width: 90%;
        max-width: 1200px;
    }
    .table > thead > tr > th {
        background: #2196F3;
        color: white;
        vertical-align: middle;
        text-align: center;
    }
    .table > tbody > tr > td {
        vertical-align: middle;
    }
    .btn-xs {
        padding: 1px 5px;
    }
    .btn-xs i {
        font-size: 16px;
    }
    .table-responsive {
        overflow-x: auto;
        max-width: 100%;
        margin-bottom: 15px;
        overflow-y: hidden;
        -ms-overflow-style: -ms-autohiding-scrollbar;
    }
    
    .table > thead > tr > th {
        white-space: nowrap;
        min-width: 100px;
    }
    
    .table > tbody > tr > td {
        white-space: normal;
        max-width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    /* Sembunyikan kolom yang tidak perlu ditampilkan */
    #tabelTemplate th:nth-child(6),
    #tabelTemplate th:nth-child(7),
    #tabelTemplate th:nth-child(8),
    #tabelTemplate th:nth-child(9),
    #tabelTemplate th:nth-child(10),
    #tabelTemplate th:nth-child(11),
    #tabelTemplate th:nth-child(12),
    #tabelTemplate th:nth-child(13),
    #tabelTemplate th:nth-child(14),
    #tabelTemplate th:nth-child(15),
    #tabelTemplate th:nth-child(16),
    #tabelTemplate th:nth-child(17),
    #tabelTemplate th:nth-child(18),
    #tabelTemplate th:nth-child(19),
    #tabelTemplate th:nth-child(20),
    #tabelTemplate td:nth-child(6),
    #tabelTemplate td:nth-child(7),
    #tabelTemplate td:nth-child(8),
    #tabelTemplate td:nth-child(9),
    #tabelTemplate td:nth-child(10),
    #tabelTemplate td:nth-child(11),
    #tabelTemplate td:nth-child(12),
    #tabelTemplate td:nth-child(13),
    #tabelTemplate td:nth-child(14),
    #tabelTemplate td:nth-child(15),
    #tabelTemplate td:nth-child(16),
    #tabelTemplate td:nth-child(17),
    #tabelTemplate td:nth-child(18),
    #tabelTemplate td:nth-child(19),
    #tabelTemplate td:nth-child(20),
    #tabelTemplate td:nth-child(21) {
        display: none;
    }

    /* Sembunyikan kolom biaya */
    .biaya, 
    .tarif,
    .total,
    [class*="biaya"],
    [class*="tarif"],
    [class*="total"] {
        display: none !important;
    }
</style>

<!-- Tambahkan script untuk inisialisasi selectpicker -->
<script>
$(document).ready(function() {
    // Inisialisasi selectpicker
    $('.selectpicker').selectpicker({
        size: 7,
        liveSearch: true,
        showSubtext: true,
        width: '100%'
    });

    // Tambahkan validasi untuk selectpicker
    $.validator.setDefaults({ ignore: ":hidden:not(.selectpicker)" });
});
</script>

<!-- Tambahkan script untuk validasi -->
<script type="text/javascript">
    $(document).ready(function() {
        $('#form_resume_ranap').validate({
            rules: {
                kd_dokter: {
                    required: true
                },
                diagnosa_awal: {
                    required: true
                },
                alasan: {
                    required: true
                },
                keluhan_utama: {
                    required: true
                },
                pemeriksaan_fisik: {
                    required: true
                },
                jalannya_penyakit: {
                    required: true
                },
                diagnosa_utama: {
                    required: true
                },
                kd_diagnosa_utama: {
                    required: true
                },
                cara_keluar: {
                    required: true
                }
            },
            highlight: function (input) {
                $(input).parents('.form-line').addClass('error');
            },
            unhighlight: function (input) {
                $(input).parents('.form-line').removeClass('error');
            },
            errorPlacement: function (error, element) {
                $(element).parents('.form-group').append(error);
            },
            messages: {
                pemeriksaan_fisik: {
                    required: "Pemeriksaan fisik harus diisi"
                },
                jalannya_penyakit: {
                    required: "Jalannya penyakit harus diisi"
                }
            }
        });
    });
</script>

<!-- Add this JavaScript after existing scripts -->
<script type="text/javascript">
function salinRiwayatSebelumnya() {
    $.ajax({
        url: 'ajax/get_riwayat_sebelumnya.php',
        type: 'POST',
        data: {
            no_rkm_medis: '<?php echo $no_rkm_medis; ?>'
        },
        success: function(response) {
            if (response.success) {
                $('textarea[name="diagnosa_awal"]').val(response.diagnosa_awal);
                $('textarea[name="keluhan_utama"]').val(response.keluhan_utama);
                $('textarea[name="alasan"]').val(response.alasan);
                $('textarea[name="riwayat_penyakit"]').val(response.riwayat_penyakit);
            } else {
                alert('Tidak ada data riwayat sebelumnya');
            }
        },
        error: function() {
            alert('Terjadi kesalahan saat mengambil data');
        }
    });
}

function salinDariCPPT() {
    $.ajax({
        url: 'ajax/get_cppt.php',
        type: 'POST',
        data: {
            no_rawat: '<?php echo $norawat; ?>'
        },
        success: function(response) {
            if (response.success) {
                $('textarea[name="diagnosa_awal"]').val(response.diagnosa);
                $('textarea[name="keluhan_utama"]').val(response.keluhan);
                $('textarea[name="alasan"]').val(response.alasan);
            } else {
                alert('Tidak ada data CPPT');
            }
        },
        error: function() {
            alert('Terjadi kesalahan saat mengambil data CPPT');
        }
    });
}

function salinDariSoapie() {
    $.ajax({
        url: 'ajax/get_soapie.php',
        type: 'POST',
        data: {
            no_rawat: '<?php echo $norawat; ?>'
        },
        success: function(response) {
            if (response.success) {
                $('textarea[name="diagnosa_awal"]').val(response.diagnosa);
                $('textarea[name="keluhan_utama"]').val(response.subjek);
                $('textarea[name="alasan"]').val(response.objek);
            } else {
                alert('Tidak ada data SOAPIE');
            }
        },
        error: function() {
            alert('Terjadi kesalahan saat mengambil data SOAPIE');
        }
    });
}

function salinPemeriksaanFisik() {
    $.ajax({
        url: 'ajax/get_pemeriksaan_fisik.php',
        type: 'POST',
        data: {
            no_rawat: '<?php echo $norawat; ?>'
        },
        success: function(response) {
            if (response.success) {
                $('textarea[name="pemeriksaan_fisik"]').val(response.pemeriksaan_fisik);
            } else {
                alert('Tidak ada data pemeriksaan fisik');
            }
        }
    });
}

function salinHasilLab() {
    $.ajax({
        url: 'ajax/get_hasil_lab.php',
        type: 'POST',
        data: {
            no_rawat: '<?php echo $norawat; ?>'
        },
        success: function(response) {
            if (response.success) {
                $('textarea[name="hasil_laborat"]').val(response.hasil_lab);
            } else {
                alert('Tidak ada data hasil laboratorium');
            }
        }
    });
}

function salinObatRawat() {
    $.ajax({
        url: 'ajax/get_obat_rawat.php',
        type: 'POST',
        data: {
            no_rawat: '<?php echo $norawat; ?>'
        },
        success: function(response) {
            if (response.success) {
                $('textarea[name="obat_di_rs"]').val(response.obat_rawat);
            } else {
                alert('Tidak ada data pemberian obat');
            }
        }
    });
}

function salinObatPulang() {
    $.ajax({
        url: 'ajax/get_obat_pulang.php',
        type: 'POST',
        data: {
            no_rawat: '<?php echo $norawat; ?>'
        },
        success: function(response) {
            if (response.success) {
                $('textarea[name="obat_pulang"]').val(response.obat_pulang);
            } else {
                alert('Tidak ada data obat pulang');
            }
        },
        error: function() {
            alert('Terjadi kesalahan saat mengambil data obat pulang');
        }
    });
}

function ambilAssesmentRanap() {
    <?php
    $sql = "SELECT * FROM penilaian_medis_ranap WHERE no_rawat='$norawat'";
    $hasil = bukaquery($sql);
    $data = mysqli_fetch_array($hasil);
    
    if ($data) {
    ?>
        // Isi form dengan data secara horizontal
        document.querySelector('textarea[name="keluhan_utama"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['keluhan_utama'] ?? ''); ?>';
        document.querySelector('textarea[name="diagnosa_awal"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['diagnosis'] ?? ''); ?>';
        document.querySelector('textarea[name="pemeriksaan_fisik"]').value = 
            'Keadaan Umum: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['keadaan'] ?? ''); ?> | ' +
            'GCS: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['gcs'] ?? ''); ?> | ' +
            'Kesadaran: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['kesadaran'] ?? ''); ?> | ' +
            'TD: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['td'] ?? ''); ?> | ' +
            'Nadi: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['nadi'] ?? ''); ?> | ' +
            'RR: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['rr'] ?? ''); ?> | ' +
            'Suhu: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['suhu'] ?? ''); ?> | ' +
            'SPO: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['spo'] ?? ''); ?> | ' +
            'BB: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['bb'] ?? ''); ?> | ' +
            'TB: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['tb'] ?? ''); ?> | ' +
            'Pemeriksaan Lainnya: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['ket_fisik'] ?? ''); ?>';
        document.querySelector('textarea[name="pemeriksaan_penunjang"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['rad'] ?? ''); ?>';
        document.querySelector('textarea[name="hasil_laborat"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['lab'] ?? ''); ?>';
        document.querySelector('input[name="diagnosa_utama"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['diagnosis'] ?? ''); ?>';
        document.querySelector('textarea[name="obat_di_rs"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['tata'] ?? ''); ?>';
        document.querySelector('textarea[name="alergi"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['alergi'] ?? ''); ?>';
        // Tambahkan riwayat penyakit terdahulu dalam tabel namanya rpd
        document.querySelector('textarea[name="riwayat_penyakit"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['rpd'] ?? ''); ?>';
    <?php
    } else {
    ?>
        alert('Mohon Maaf, Pasien Belum dilakukan asesmen awal medis RANAP!');
    <?php
    }
    ?>
}

function ambilAssesmentIGD() {
    <?php
    $sql = "SELECT * FROM penilaian_medis_igd WHERE no_rawat='$norawat'";
    $hasil = bukaquery($sql);
    $data = mysqli_fetch_array($hasil);
    
    if ($data) {
    ?>
        // Isi form dengan data secara horizontal
        document.querySelector('textarea[name="keluhan_utama"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['keluhan_utama'] ?? ''); ?>';
        document.querySelector('textarea[name="diagnosa_awal"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['diagnosis'] ?? ''); ?>';
        document.querySelector('textarea[name="pemeriksaan_fisik"]').value = 
            'Keadaan Umum: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['keadaan'] ?? ''); ?> | ' +
            'GCS: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['gcs'] ?? ''); ?> | ' +
            'Kesadaran: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['kesadaran'] ?? ''); ?> | ' +
            'TD: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['td'] ?? ''); ?> | ' +
            'Nadi: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['nadi'] ?? ''); ?> | ' +
            'RR: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['rr'] ?? ''); ?> | ' +
            'Suhu: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['suhu'] ?? ''); ?> | ' +
            'SPO: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['spo'] ?? ''); ?> | ' +
            'BB: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['bb'] ?? ''); ?> | ' +
            'TB: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['tb'] ?? ''); ?> | ' +
            'Pemeriksaan Lainnya: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['ket_fisik'] ?? ''); ?>';
        document.querySelector('textarea[name="pemeriksaan_penunjang"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['rad'] ?? ''); ?>';
        document.querySelector('textarea[name="hasil_laborat"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['lab'] ?? ''); ?>';
        document.querySelector('input[name="diagnosa_utama"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['diagnosis'] ?? ''); ?>';
        document.querySelector('textarea[name="obat_di_rs"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['tata'] ?? ''); ?>';
        document.querySelector('textarea[name="alergi"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['alergi'] ?? ''); ?>';
        // Tambahkan riwayat penyakit terdahulu dalam tabel namanya rpd
        document.querySelector('textarea[name="riwayat_penyakit"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['rpd'] ?? ''); ?>';
    <?php
    } else {
    ?>
        alert('Mohon Maaf, Pasien Belum dilakukan asesmen awal medis RANAP!');
    <?php
    }
    ?>
}

function ambilCPPTAwal() {
    <?php
    // Ambil data CPPT awal (yang pertama)
    $sql = "SELECT COUNT(*) as total FROM pemeriksaan_ranap 
            WHERE no_rawat='$norawat' AND nip='$kd_dokter' 
            ORDER BY tgl_perawatan ASC";
    $hasil = bukaquery($sql);
    $count = mysqli_fetch_array($hasil);
    
    if ($count['total'] == 0) {
    ?>
        alert('Mohon Maaf, Pasien Belum dilakukan CPPT RANAP!');
    <?php
    } else {
        // Ambil data CPPT pertama
        $sql = "SELECT keluhan, gcs, kesadaran, tensi, nadi, respirasi, 
                suhu_tubuh, spo2, berat, tinggi, penilaian, rtl, alergi 
                FROM pemeriksaan_ranap 
                WHERE no_rawat='$norawat' AND nip='$kd_dokter' 
                ORDER BY tgl_perawatan ASC LIMIT 1";
        $hasil = bukaquery($sql);
        $data = mysqli_fetch_array($hasil);
        
        if ($data) {
        ?>
            // Isi form dengan data
            document.querySelector('textarea[name="keluhan_utama"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['keluhan'] ?? ''); ?>';
            document.querySelector('textarea[name="pemeriksaan_fisik"]').value = 
                'GCS: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['gcs'] ?? ''); ?> | ' +
                'Kesadaran: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['kesadaran'] ?? ''); ?> | ' +
                'TD: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['tensi'] ?? ''); ?> | ' +
                'Nadi: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['nadi'] ?? ''); ?> | ' +
                'RR: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['respirasi'] ?? ''); ?> | ' +
                'Suhu: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['suhu_tubuh'] ?? ''); ?> | ' +
                'SPO: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['spo2'] ?? ''); ?> | ' +
                'BB: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['berat'] ?? ''); ?> | ' +
                'TB: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['tinggi'] ?? ''); ?>';
            document.querySelector('input[name="diagnosa_utama"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['penilaian'] ?? ''); ?>';
            document.querySelector('textarea[name="obat_di_rs"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['rtl'] ?? ''); ?>';
            document.querySelector('textarea[name="alergi"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['alergi'] ?? ''); ?>';
        <?php
        } else {
        ?>
            alert('Data CPPT awal tidak ditemukan');
        <?php
        }
    }
    ?>
}

function ambilCPPTAkhir() {
    <?php
    // Ambil data CPPT terakhir
    $sql = "SELECT COUNT(*) as total FROM pemeriksaan_ranap 
            WHERE no_rawat='$norawat' AND nip='$kd_dokter' 
            ORDER BY tgl_perawatan DESC";
    $hasil = bukaquery($sql);
    $count = mysqli_fetch_array($hasil);
    
    if ($count['total'] == 0) {
    ?>
        alert('Mohon Maaf, Pasien Belum dilakukan CPPT RANAP!');
    <?php
    } else {
        // Ambil data CPPT terakhir
        $sql = "SELECT keluhan, gcs, kesadaran, tensi, nadi, respirasi, 
                suhu_tubuh, spo2, berat, tinggi, penilaian, rtl, alergi 
                FROM pemeriksaan_ranap 
                WHERE no_rawat='$norawat' AND nip='$kd_dokter' 
                ORDER BY tgl_perawatan DESC";
        $hasil = bukaquery($sql);
        $data = mysqli_fetch_array($hasil);
        
        if ($data) {
        ?>
            // Isi form dengan data
            document.querySelector('textarea[name="keluhan_utama"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['keluhan'] ?? ''); ?>';
            document.querySelector('textarea[name="pemeriksaan_fisik"]').value = 
                'GCS: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['gcs'] ?? ''); ?> | ' +
                'Kesadaran: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['kesadaran'] ?? ''); ?> | ' +
                'TD: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['tensi'] ?? ''); ?> | ' +
                'Nadi: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['nadi'] ?? ''); ?> | ' +
                'RR: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['respirasi'] ?? ''); ?> | ' +
                'Suhu: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['suhu_tubuh'] ?? ''); ?> | ' +
                'SPO: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['spo2'] ?? ''); ?> | ' +
                'BB: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['berat'] ?? ''); ?> | ' +
                'TB: <?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['tinggi'] ?? ''); ?>';
            document.querySelector('input[name="diagnosa_utama"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['penilaian'] ?? ''); ?>';
            document.querySelector('textarea[name="obat_di_rs"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['rtl'] ?? ''); ?>';
            document.querySelector('textarea[name="alergi"]').value = '<?php echo str_replace(["'","\n","\r"], ["\'","\\n",""], $data['alergi'] ?? ''); ?>';
        <?php
        } else {
        ?>
            alert('Data CPPT terakhir tidak ditemukan');
        <?php
        }
    }
    ?>
}

function bukaFormTemplate() {
    $('#modalTemplate').modal('show');
}

// Fungsi untuk menerima data dari popup
function pilihTemplate(data) {
    try {
        // Set diagnosa awal
        $('textarea[name="diagnosa_awal"]').val(data.diagnosa_awal || '');
        
        // Set field lainnya
        $('textarea[name="keluhan_utama"]').val(data.keluhan_utama || '');
        $('input[name="diagnosa_utama"]').val(data.diagnosa_utama || '');
        $('textarea[name="alasan"]').val(data.alasan || '');
        $('textarea[name="pemeriksaan_fisik"]').val(data.pemeriksaan_fisik || '');
        $('textarea[name="jalannya_penyakit"]').val(data.jalannya_penyakit || '');
        $('textarea[name="pemeriksaan_penunjang"]').val(data.pemeriksaan_penunjang || '');
        $('textarea[name="hasil_laborat"]').val(data.hasil_laborat || '');
        $('textarea[name="tindakan_dan_operasi"]').val(data.tindakan_dan_operasi || '');
        $('textarea[name="obat_di_rs"]').val(data.obat_di_rs || '');
        $('input[name="kd_diagnosa_utama"]').val(data.kd_diagnosa_utama || '');
        $('input[name="diagnosa_sekunder"]').val(data.diagnosa_sekunder || '');
        $('input[name="kd_diagnosa_sekunder"]').val(data.kd_diagnosa_sekunder || '');
        $('textarea[name="alergi"]').val(data.alergi || '');
        $('textarea[name="diet"]').val(data.diet || '');
        $('textarea[name="lab_belum"]').val(data.lab_belum || '');
        $('textarea[name="edukasi"]').val(data.edukasi || '');

        // Update selectpicker jika ada
        if(data.cara_keluar) {
            $('select[name="cara_keluar"]').val(data.cara_keluar).selectpicker('refresh');
        }
        if(data.keadaan) {
            $('select[name="keadaan"]').val(data.keadaan).selectpicker('refresh');
        }
        if(data.dilanjutkan) {
            $('select[name="dilanjutkan"]').val(data.dilanjutkan).selectpicker('refresh');
        }

        $('#modalTemplate').modal('hide');
    } catch(e) {
        console.error('Error saat mengisi form:', e);
        alert('Terjadi kesalahan saat mengisi form');
    }
}
</script> 