<div class="pageContent">
    <table class="tableStyle table-hover table-striped table-condensed" style="font-size:9pt">
        <thead style="background-color: #57A700; color: white; font-weight: bold;">
            <tr>
                <td>No.</td>
                <td>No.Lab</td>
                <td>Case ID</td>
                <td>No.MR</td>
                <td>Nama</td>
                <td>Tanggal</td>
                <td>Penjamin</td>
                <td>Unit</td>
                <td>Dokter</td>
                <td style="width: 4%;">#</td>
            </tr>
        </thead>
        <tbody id="dataPasien" style="font-size:8pt"></tbody>
    </table>
</div>

<!-- Modal Update Penjamin -->
<div class="modal fade" id="modalPenjamin" tabindex="-1" aria-labelledby="modalPenjaminLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="modalPenjaminLabel">Update Penjamin</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="caseIdPenjamin">

        <div class="form-group">
          <label for="penjaminBaru">Pilih Penjamin</label>
          <select id="penjaminBaru" class="form-control">
            <option value="">-- Pilih Penjamin --</option>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
          <button type="button" class="btn btn-success" id="btnSimpanPenjamin">Simpan Perubahan</button>
      </div>
    </div>
  </div>
</div>

<script>
    dataPasien();

    function dataPasien() {
        $(".loadingPasien").show();
        $.ajax({
            url: "<?= base_url('worklist/getPasien'); ?>",
            async: true,
            dataType: "json",
            success: function(data) {
                $(".loadingPasien").hide();
                if (data.jumlahData > 0) {
                    list(data);
                } else {
                    Swal.fire({
                        title: 'Oooops!',
                        text: "Data hari ini masih kosong !",
                        icon: 'warning'
                    });
                    $('#dataPasien').empty()
                }
            }
        })
    }

    function cariPasien() {
        var nomr = document.getElementById("nomr").value
        var caseid = document.getElementById("caseid").value
        var tanggal = document.getElementById("tgl").value

        if (nomr == '' && caseid == '' && tanggal == '') {
            Swal.fire({
                title: 'Perhatian!',
                text: "Pencarian harus diisi !",
                icon: 'warning'
            });
        } else {
            $(".loadingPasien").show()
            $.ajax({
                url: '<?= base_url('worklist/pencarian'); ?>',
                method: 'POST',
                data: {
                    nomr: nomr,
                    caseid: caseid,
                    tanggal: tanggal
                },
                async: true,
                dataType: 'json',
                success: function(data) {
                    $(".loadingPasien").hide()
                    list(data);
                }
            })
        }
    }

    function list(data) {
        var html = '';
        var i;
        var no = 1;
        for (i = 0; i < data.jumlahData; i++) {
            if (data.body[i].HasilLab == 1) {
                var tr = '<tr style="background-color: rgb(255, 251, 123);">'
            } else {
                var tr = '<tr>'
            }
            html += tr +
                '<td>' + no++ + '.</td>' +
                '<td>' + data.body[i].LabNo + '</td>' +
                '<td>' + data.body[i].caseid + '</td>' +
                '<td>' + data.body[i].MR + '</td>' +
                '<td>' + data.body[i].PatientName + '</td>' +
                '<td>' + data.body[i].ReceiptDate + ' ' + data.body[i].ReceiptTime + '</td>' +
                '<td><a href="#" class="text-primary edit-penjamin" data-caseid="' + data.body[i].caseid + '" data-penjamin="' + data.body[i].Penjamin + '">' + data.body[i].Penjamin + '</a></td>' +
                '<td>' + data.body[i].Ruangan + ' - ' + data.body[i].Room + '</td>' +
                '<td>' + data.body[i].FirstName + '</td>' +
                '<td><button data-nolab="' + data.body[i].LabNo + '" onclick="getForm(this)" class="btn btn-xs btn-success"><i class="fa fa-fw fa-folder-open"></i></button></td>' +
                '</tr>';
        }
        $('#dataPasien').html(html);
    }

    $('#dataPasien').on('click', '.selectCase', function() {
        var getParameter = $(this).val();
        window.location.href = "<?= base_url('anamnesav2/periksa/'); ?>" + getParameter
    });

    $('#dataPasien').on('click', '.selectCaseDetail', function() {
        var getParameter = $(this).val();
        window.location.href = "<?= base_url('anamnesav2/detail/'); ?>" + getParameter
    });

    function openTR(data) {
        var caseid = data.getAttribute("data-cases")
        window.location.href = "<?= base_url('anamnesav2/periksa/'); ?>" + caseid
    }

    function openTRDetail(data) {
        var caseid = data.getAttribute("data-cases")
        window.location.href = "<?= base_url('anamnesav2/detail/'); ?>" + caseid
    }

    function reset() {
        dataPasien()
        var nomr = document.getElementById("nomr").value = ''
        var caseid = document.getElementById("caseid").value = ''
        var tanggal = document.getElementById("tgl").value = ''
    }

    $(document).on('click', '.edit-penjamin', function(e) {
    e.preventDefault();

    var caseId = $(this).data('caseid');
    var penjaminCode = $(this).data('penjamin'); // misal berisi CompanyCode

    $('#caseIdPenjamin').val(caseId);

    // kosongkan dulu select
    $('#penjaminBaru').html('<option value="">Memuat data...</option>');

    // ambil daftar company dari server
    $.ajax({
        url: "<?= base_url('Worklist/get_company'); ?>",
        type: "GET",
        dataType: "json",
        success: function(res) {
            $('#penjaminBaru').empty().append('<option value="">-- Pilih Penjamin --</option>');
            if (res.status && res.data.length > 0) {
                $.each(res.data, function(i, row) {
                    var selected = (row.CompanyName == penjaminCode) ? 'selected' : '';
                    $('#penjaminBaru').append('<option value="'+row.CompanyName+'" '+selected+'>'+row.CompanyName+'</option>');
                });
            } else {
                $('#penjaminBaru').append('<option value="">(Tidak ada data)</option>');
            }
        },
        error: function() {
            alert("Gagal memuat daftar penjamin.");
        }
    });


    // tampilkan modal
    $('#modalPenjamin').modal('show');
});

// tombol simpan
 // ============== EVENT SIMPAN PENJAMIN ==============
    $(document).on('click', '#btnSimpanPenjamin', function() {
        var caseId = $('#caseIdPenjamin').val();
        var penjaminCode = $('#penjaminBaru').val();

        if (penjaminCode === '') {
            alert('Silakan pilih penjamin!');
            return;
        }

        $.ajax({
            url: "<?= base_url('Worklist/updatecompany'); ?>",
            type: "POST",
            dataType: "json",
            data: {
                caseid: caseId,
                penjamin: penjaminCode
            },
            success: function(res) {
                if (res.status === true) {
                    alert('Penjamin berhasil diperbarui!');
                    $('#modalPenjamin').modal('hide');
                    // misal reload tabel:
                    dataPasien(); 
                } else {
                    alert('Gagal update: ' + res.message);
                }
            },
            error: function(xhr, status, error) {
                console.error(xhr.responseText);
                alert('Terjadi kesalahan koneksi ke server.');
            }
        });
    });
</script>
