<?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>

<nav class="page-breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><?= $Breadcumb ?></li>
        <li class="breadcrumb-item active" aria-current="page">Data <?= $Breadcumb ?></li>
    </ol>
</nav>

<div class="row">
    <div class="col-md-12 grid-margin stretch-card">
        <div class="card">
            <div class="card-body">

                <div class="col-md-2 grid-margin stretch-card">
                    <a class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#tambahModal">Tambah Resep</a>
                </div>

                <h6 class="card-title">Data <?= $Breadcumb ?></h6>

                <div class="table-responsive">
                    <table id="dataTableExample" class="table table-bordered table-hover table-nowrap">
                        <thead class="table-info text-dark">
                            <tr>
                                <th>#</th>
                                <th>Nama Pasien</th>
                                <th>Tanggal Resep</th>
                                <th>Catatan</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $no = 1; ?>
                            <?php if (!empty($resep)): ?>
                                <?php foreach ($resep as $row): ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><?= esc($row['nama_lengkap']) ?></td>
                                        <td><?= date('d-m-Y', strtotime($row['tanggal_resep'])) ?></td>
                                        <td><?= esc($row['catatan']) ?></td>
                                        <td>
                                            <button class="btn btn-info btn-sm" onclick="lihatDetailResep('<?= $row['id_resep'] ?>')">
                                                <i data-feather="eye"></i> Detail
                                            </button>
                                            <button class="btn btn-warning btn-sm" onclick="editResep('<?= $row['id_resep'] ?>')">
                                                <i data-feather="edit"></i>
                                            </button>
                                            <!-- <button class="btn btn-danger btn-sm" onclick="deleteResep('<?= $row['id_resep'] ?>')">
                                                <i data-feather="trash-2"></i>
                                            </button> -->
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" class="text-center text-muted">Tidak ada data resep obat.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

            </div>
        </div>
    </div>
</div>

<!-- Modal Detail Resep Obat -->
<div class="modal fade" id="modalDetailResep" tabindex="-1" aria-labelledby="modalDetailResepLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Detail Resep Obat</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body" style="max-height: 70vh; overflow-y: auto;">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Nama Obat</th>
                            <th>Dosis</th>
                            <th>Jumlah</th>
                            <th>Aturan Pakai</th>
                        </tr>
                    </thead>
                    <tbody id="detailResepBody">
                        <!-- Isi otomatis via AJAX -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Modal Tambah Resep Obat -->
<div class="modal fade" id="tambahModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <form id="formTambahResep">
                <div class="modal-header">
                    <h5 class="modal-title">Tambah Resep Obat</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body" style="max-height: 70vh; overflow-y: auto;">
                    <div class="mb-3">
                        <label for="id_rekam_medis" class="form-label">Pilih Rekam Medis</label>
                        <select name="id_rekam_medis" id="id_rekam_medis" class="form-select select2-rekam" required>
                            <option value="">-- Pilih Rekam Medis --</option>
                            <?php foreach ($rekam_medis as $rm): ?>
                                <option value="<?= $rm['id_rekam_medis'] ?>">
                                    <?= $rm['nama_pasien'] ?> - <?= date('d-m-Y', strtotime($rm['tanggal_kunjungan'])) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="tanggal_resep" class="form-label">Tanggal Resep</label>
                        <input type="date" class="form-control" name="tanggal_resep" id="tanggal_resep" required>
                    </div>

                    <div class="mb-3">
                        <label for="catatan" class="form-label">Catatan Tambahan</label>
                        <textarea class="form-control" name="catatan" id="catatan" rows="2"></textarea>
                    </div>

                    <hr>
                    <h6>Detail Resep Obat</h6>
                    <table class="table table-bordered" id="tabelDetailResep">
                        <thead>
                            <tr>
                                <th>Obat</th>
                                <th>Dosis</th>
                                <th>Jumlah</th>
                                <th>Aturan Pakai</th>
                                <th><button type="button" class="btn btn-success btn-sm" onclick="tambahBarisResep()"><i data-feather="plus"></i></button></th>
                            </tr>
                        </thead>
                        <tbody id="bodyDetailResep">
                            <tr>
                                <td>
                                    <select name="id_obat[]" class="form-select select2-obat" required>
                                        <option value="">-- Pilih Obat --</option>
                                        <?php foreach ($obat as $o): ?>
                                            <option value="<?= $o['id_obat'] ?>"><?= $o['nama_obat'] ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td><input type="text" name="dosis[]" class="form-control" required></td>
                                <td><input type="number" name="jumlah[]" class="form-control" required></td>
                                <td><input type="text" name="aturan_pakai[]" class="form-control" required></td>
                                <td><button type="button" class="btn btn-danger btn-sm" onclick="hapusBarisResep(this)"><i data-feather="trash-2"></i></button></td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Simpan Resep</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal edit resep -->
<form id="formEditResep">
    <input type="hidden" name="id_resep">

    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Resep Obat</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body">
                    <div class="mb-3">
                        <label for="id_rekam_medis" class="form-label">Pilih Rekam Medis</label>
                        <select name="id_rekam_medis" class="form-select select2-rekam-edit" required>
                            <option value="">-- Pilih Rekam Medis --</option>
                            <?php foreach ($rekam_medis as $rm): ?>
                                <option value="<?= $rm['id_rekam_medis'] ?>">
                                    <?= $rm['nama_pasien'] ?> - <?= date('d-m-Y', strtotime($rm['tanggal_kunjungan'])) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="tanggal_resep" class="form-label">Tanggal Resep</label>
                        <input type="date" class="form-control" name="tanggal_resep" required>
                    </div>

                    <div class="mb-3">
                        <label for="catatan" class="form-label">Catatan Tambahan</label>
                        <textarea class="form-control" name="catatan" rows="2"></textarea>
                    </div>

                    <hr>
                    <h6>Detail Resep Obat</h6>
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Obat</th>
                                <th>Dosis</th>
                                <th>Jumlah</th>
                                <th>Aturan Pakai</th>
                                <th><button type="button" class="btn btn-success btn-sm" onclick="tambahBarisResepEdit()"><i data-feather="plus"></i></button></th>
                            </tr>
                        </thead>
                        <tbody id="bodyEditResep"></tbody>
                    </table>
                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary btn-simpan-edit">Simpan Perubahan</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                </div>
            </div>
        </div>
    </div>
</form>

<!-- script untuk detail tambah obat -->
<script>
    $(document).ready(function() {
        $('#tambahModal').on('shown.bs.modal', function() {
            // Inisialisasi Select2 Rekam Medis
            $('.select2-rekam').select2({
                dropdownParent: $('#tambahModal'),
                placeholder: 'Silahkan Pilih Rekam Medis',
                allowClear: true,
                width: '100%'
            });

            // Inisialisasi Select2 Obat pada baris awal
            $('.select2-obat').select2({
                dropdownParent: $('#tambahModal'),
                placeholder: 'Silahkan Pilih Obat',
                allowClear: true,
                width: '100%'
            });
        });
    });

    function tambahBarisResep() {
        const obatOptions = `<?php foreach ($obat as $o): ?><option value="<?= $o['id_obat'] ?>"><?= $o['nama_obat'] ?></option><?php endforeach; ?>`;

        const row = `
        <tr>
            <td><select name="id_obat[]" class="form-select" required><option value="">-- Pilih Obat --</option>${obatOptions}</select></td>
            <td><input type="text" name="dosis[]" class="form-control" required></td>
            <td><input type="number" name="jumlah[]" class="form-control" required></td>
            <td><input type="text" name="aturan_pakai[]" class="form-control" required></td>
            <td><button type="button" class="btn btn-danger btn-sm" onclick="hapusBarisResep(this)"><i data-feather="trash-2"></i></button></td>
        </tr>
    `;
        $('#bodyDetailResep').append(row);
        feather.replace(); // refresh icon
    }

    function hapusBarisResep(btn) {
        $(btn).closest('tr').remove();
    }
</script>

<!-- Script untuk detail resep obat -->
<script>
    function lihatDetailResep(idResep) {
        $.ajax({
            url: '<?= base_url("ResepObat/detail_ajax") ?>',
            method: 'POST',
            data: {
                id_resep: idResep
            },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    let html = '';
                    response.data.forEach(item => {
                        html += `
                        <tr>
                            <td>${item.nama_obat}</td>
                            <td>${item.dosis}</td>
                            <td>${item.jumlah}</td>
                            <td>${item.aturan_pakai}</td>
                        </tr>
                    `;
                    });
                    $('#detailResepBody').html(html);
                    $('#modalDetailResep').modal('show');
                } else {
                    alert(response.message || 'Gagal mengambil data resep.');
                }
            },
            error: function() {
                alert('Terjadi kesalahan saat menghubungi server.');
            }
        });
    }
</script>

<!-- tambah baris untuk edit -->
<script>
    function tambahBarisResepEdit(obatOptions = '') {
        const row = `
        <tr>
            <td>
                <select name="id_obat[]" class="form-select select2-obat-edit" required>
                    <option value="">-- Pilih Obat --</option>
                    ${obatOptions}
                </select>
            </td>
            <td><input type="text" name="dosis[]" class="form-control" required></td>
            <td><input type="number" name="jumlah[]" class="form-control" required></td>
            <td><input type="text" name="aturan_pakai[]" class="form-control" required></td>
            <td><button type="button" class="btn btn-danger btn-sm" onclick="hapusBarisResep(this)"><i data-feather="trash-2"></i></button></td>
        </tr>
    `;

        $('#bodyEditResep').append(row); // ✅ pakai ID yang sesuai

        // Inisialisasi select2 untuk baris baru
        $('.select2-obat-edit').last().select2({
            dropdownParent: $('#editModal'),
            placeholder: 'Silahkan Pilih Obat',
            allowClear: true,
            width: '100%'
        });

        feather.replace();
    }
</script>

<!-- script mengambil data obat untuk edit -->
<script>
    function editResep(id) {
        $.ajax({
            url: "<?= base_url('ResepObat/getDetailResep') ?>/" + id,
            method: "GET",
            dataType: "json",
            success: function(response) {
                if (response.status === 'success') {
                    const data = response.resep;
                    const detail = response.detail;

                    $('#formEditResep input[name="id_resep"]').val(data.id_resep);
                    $('#formEditResep select[name="id_rekam_medis"]').val(data.id_rekam_medis).trigger('change');
                    $('#formEditResep input[name="tanggal_resep"]').val(data.tanggal_resep);
                    $('#formEditResep textarea[name="catatan"]').val(data.catatan);

                    // Kosongkan tabel
                    $('#bodyEditResep').empty();

                    detail.forEach(d => {
                        const row = `
                    <tr>
                        <td >
                            <select name="id_obat[]" class="form-select select2-obat-edit" required>
                                <option value="">-- Pilih Obat --</option>
                                <?php foreach ($obat as $o): ?>
                                <option value="<?= $o['id_obat'] ?>"><?= $o['nama_obat'] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td><input type="text" name="dosis[]" class="form-control" value="${d.dosis}" required></td>
                        <td><input type="number" name="jumlah[]" class="form-control" value="${d.jumlah}" required></td>
                        <td><input type="text" name="aturan_pakai[]" class="form-control" value="${d.aturan_pakai}" required></td>
                        <td><button type="button" class="btn btn-danger btn-sm" onclick="hapusBarisResep(this)"><i data-feather="trash-2"></i></button></td>
                    </tr>`;
                        $('#bodyEditResep').append(row);
                    });

                    // Set selected obat setelah row dimasukkan
                    $('#bodyEditResep tr').each((index, tr) => {
                        $(tr).find('select[name="id_obat[]"]').val(detail[index].id_obat).trigger('change');
                    });

                    feather.replace();
                    $('#editModal').modal('show');
                } else {
                    Swal.fire('Gagal', response.message, 'error');
                }
            }
        });
    }
</script>

<!-- script mengirim data obat ke kontroler -->
<script>
    $('#formEditResep').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: "<?= base_url('ResepObat/updateData') ?>",
            method: "POST",
            data: $(this).serialize(),
            dataType: "json",
            beforeSend: function() {
                $('.btn-simpan-edit').attr('disabled', true).text('Menyimpan...');
            },
            success: function(response) {
                $('.btn-simpan-edit').attr('disabled', false).text('Simpan Perubahan');
                if (response.status === 'success') {
                    Swal.fire('Berhasil', response.message, 'success').then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire('Gagal', response.message, 'error');
                }
            }
        });
    });
</script>

<!-- script  tambah obat ke kontroler -->
<script>
    $(document).ready(function() {
        $('#formTambahResep').on('submit', function(e) {
            e.preventDefault();

            $.ajax({
                url: "<?= base_url('ResepObat/tambahData') ?>",
                method: "POST",
                data: $(this).serialize(),
                dataType: "json",
                beforeSend: function() {
                    $('.btn-primary').attr('disabled', true).text('Menyimpan...');
                },
                success: function(response) {
                    $('.btn-primary').attr('disabled', false).text('Simpan Resep');

                    if (response.status === 'success') {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil',
                            text: response.message,
                        }).then(() => {
                            location.reload(); // Atau bisa ditutup dan diupdate manual
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal',
                            text: response.message,
                        });
                    }
                },
                error: function(xhr, status, error) {
                    $('.btn-primary').attr('disabled', false).text('Simpan Resep');
                    Swal.fire({
                        icon: 'error',
                        title: 'Error Server',
                        text: 'Terjadi kesalahan. Coba lagi.',
                    });
                }
            });
        });
    });
</script>

<script>
    $(document).ready(function() {
        // Inisialisasi Select2 saat editModal ditampilkan
        $('#editModal').on('shown.bs.modal', function() {
            $('.select2-rekam-edit').select2({
                dropdownParent: $('#editModal'),
                placeholder: 'Pilih Rekam Medis',
                allowClear: true,
                width: '100%'
            });

            $('.select2-obat-edit').select2({
                dropdownParent: $('#editModal'),
                placeholder: 'Pilih Obat',
                allowClear: true,
                width: '100%'
            });
        });
    });
</script>


<?= $this->endSection(); ?>