<?= $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 Data</a>

                </div>

                <h6 class="card-title">Data <?= $Breadcumb ?></h6>
                <div class="table-responsive">
                    <table id="dataTableExample" class="table table-bordered table-hover table no-wrap">
                        <thead class="table-info text-dark">
                            <tr>
                                <th>#</th>
                                <th>Pasien (Kunjungan)</th>
                                <th>Jumlah Tindakan</th>
                                <th>Tanggal</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $no = 1; ?>
                            <?php if (!empty($tindakan)): ?>
                                <?php foreach ($tindakan as $row): ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><?= esc($row['nama_lengkap']) ?> (Kunjungan #<?= esc($row['id_kunjungan']) ?>)</td>
                                        <td><?= count($row['detail_tindakan']) ?> tindakan</td>
                                        <td><?= date('d-m-Y H:i', strtotime($row['created_at'])) ?></td>
                                        <td>
                                            <button class="btn btn-info btn-sm" onclick='lihatDetail(<?= json_encode($row["detail_tindakan"]) ?>)'>
                                                <i data-feather="eye"></i> Detail
                                            </button>
                                            <button class="btn btn-warning btn-sm" onclick='showEditModal(<?= json_encode($row["detail_tindakan"]) ?>, <?= $row["id_kunjungan"] ?>)'>
                                                <i data-feather="edit"></i> Edit
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="text-center text-muted">Tidak ada data tindakan.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>

                </div>

            </div>

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

<!-- modal detail -->
<div class="modal fade" id="modalDetailTindakan" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Detail Tindakan</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-striped table-responsive" style="table-layout: fixed; width: 100%;">
                    <thead>
                        <tr>
                            <th style="width: 30%;">Nama Tindakan</th>
                            <th style="width: 20%;">Tarif</th>
                            <th style="width: 50%;">Keterangan</th>
                        </tr>
                    </thead>
                    <tbody id="detailTindakanBody"></tbody>
                    <tfoot>
                        <tr>
                            <th>Total</th>
                            <th id="totalTarif" colspan="2" class="text-end text-primary"></th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- modal edit detail tindakan -->
<div class="modal fade" id="modalEditTindakan" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Detail Tindakan</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-striped table-responsive" style="table-layout: fixed; width: 100%;">
                    <thead>
                        <tr>
                            <th style="width: 30%;">Nama Tindakan</th>
                            <th style="width: 50%;">Keterangan</th>
                        </tr>
                    </thead>
                    <tbody id="editTindakanBody"></tbody>

                </table>
                <button id="btnSimpanEdit" class="btn btn-success mt-3">Edit Perubahan</button>
            </div>
        </div>
    </div>
</div>


<!-- Modal Tambah Data -->
<div class="modal fade" id="tambahModal" tabindex="-1" role="dialog" aria-labelledby="tambahModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="tambahModalLabel">Tambah Data <?= $Breadcumb ?></h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="btn-close"></button>
            </div>
            <div class="modal-body">
                <form id="formTambahData">
                    <div class="mb-3">
                        <label for="id_kunjungan">Kunjungan</label>
                        <select class="form-control" id="id_kunjungan" name="id_kunjungan" required>
                            <option value="">-- Pilih Kunjungan --</option>
                            <?php foreach ($kunjungan as $k): ?>
                                <option value="<?= $k['id_kunjungan'] ?>">
                                    <?= esc($k['nama_pasien']) ?> - <?= esc($k['tanggal_kunjungan']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="id_tindakan">Tindakan</label>
                            <select class="form-control" id="id_tindakan">
                                <option value="">-- Pilih Tindakan --</option>
                                <?php foreach ($masterTindakan as $t): ?>
                                    <option value="<?= $t['id_tindakan'] ?>" data-nama="<?= esc($t['nama_tindakan']) ?>" data-tarif="<?= $t['tarif'] ?>">
                                        <?= esc($t['nama_tindakan']) ?> (Rp <?= number_format($t['tarif'], 0, ',', '.') ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label for="keterangan">Keterangan</label>
                            <textarea class="form-control" id="keterangan" rows="1"></textarea>
                        </div>
                    </div>

                    <button type="button" class="btn btn-info mb-3" id="tambahTindakan">Tambah ke Daftar</button>

                    <!-- Tabel daftar tindakan sementara -->
                    <table class="table table-bordered" id="tabelTindakanSementara">
                        <thead class="table-secondary">
                            <tr>
                                <th>Nama Tindakan</th>
                                <th>Tarif</th>
                                <th>Keterangan</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>

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

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

<script>
    const masterTindakan = <?= json_encode($masterTindakan) ?>;
</script>

<!-- script edit detail tindakan -->
<script>
    function showEditModal(data, id_kunjungan) {
        console.log("Data detail_tindakan:", data);
        console.log("Master tindakan:", masterTindakan);

        const tbody = document.getElementById('editTindakanBody');
        tbody.innerHTML = '';

        data.forEach((item, index) => {
            console.log(`Detail ${index} - id_tindakan:`, item.id_tindakan);

            let options = '<option value="">-- Pilih Tindakan --</option>';
            masterTindakan.forEach(mt => {
                const selected = String(mt.id_tindakan) === String(item.id_tindakan) ? 'selected' : '';
                console.log(`  Cek: ${mt.id_tindakan} === ${item.id_tindakan} ? ${selected}`);
                options += `<option value="${mt.id_tindakan}" ${selected}>${mt.nama_tindakan}</option>`;
            });

            tbody.innerHTML += `
            <tr>
                <td>
                    <input type="hidden" name="detail[${index}][id_detail]" value="${item.id_detail}">
                    <select class="form-control tindakan-edit-select" name="detail[${index}][id_tindakan]">
                        ${options}
                    </select>
                </td>
                <td>
                    <textarea class="form-control" name="detail[${index}][keterangan]">${item.keterangan}</textarea>
                </td>
            </tr>
        `;
        });

        // Inisialisasi select2
        setTimeout(() => {
            $('.tindakan-edit-select').select2({
                dropdownParent: $('#modalEditTindakan'),
                placeholder: 'Pilih Tindakan',
                width: '100%',
                allowClear: true
            });
        }, 10);

        // Tampilkan modal
        const modal = new bootstrap.Modal(document.getElementById('modalEditTindakan'));
        modal.show();

        // Aksi tombol simpan
        document.getElementById('btnSimpanEdit').onclick = function() {
            const formData = new FormData();

            document.querySelectorAll('#editTindakanBody tr').forEach((row, i) => {
                formData.append(`detail[${i}][id_detail]`, row.querySelector('[name^="detail"][name$="[id_detail]"]').value);
                formData.append(`detail[${i}][id_tindakan]`, row.querySelector('[name^="detail"][name$="[id_tindakan]"]').value);
                formData.append(`detail[${i}][keterangan]`, row.querySelector('[name^="detail"][name$="[keterangan]"]').value);
            });

            formData.append('id_kunjungan', id_kunjungan);

            fetch('<?= base_url("tindakan/updateDetail") ?>', {
                    method: 'POST',
                    body: formData
                })
                .then(res => res.json())
                .then(res => {
                    if (res.status === 'ok') {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: res.message || 'Data berhasil diperbarui',
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal',
                            text: res.message || 'Gagal memperbarui data',
                        });
                    }
                });
        };
    }
</script>


<!-- script detail tindakan -->
<script>
    function lihatDetail(data) {
        const tbody = document.getElementById('detailTindakanBody');
        const totalEl = document.getElementById('totalTarif');
        tbody.innerHTML = '';
        let total = 0;

        data.forEach(item => {
            const tarif = parseFloat(item.tarif);
            total += tarif;

            tbody.innerHTML += `
            <tr>
        <td style="word-wrap: break-word; white-space: normal;">${item.nama_tindakan}</td>
        <td>Rp ${tarif.toLocaleString('id-ID')}</td>
        <td style="word-wrap: break-word; white-space: normal;">${item.keterangan}</td>
    </tr>`;
        });

        totalEl.textContent = 'Rp ' + total.toLocaleString('id-ID');

        const modal = new bootstrap.Modal(document.getElementById('modalDetailTindakan'));
        modal.show();
    }
</script>

<!-- script select untuk tindakan -->
<script>
    $(document).ready(function() {
        // Inisialisasi awal untuk #id_tindakan
        $('#id_tindakan').select2({
            dropdownParent: $('#tambahModal'),
            placeholder: "Silahkan Pilih Tindakan",
            allowClear: true
        });

        // Jika modal dibuka, re-inisialisasi jika perlu
        $('#tambahModal').on('shown.bs.modal', function() {
            if (!$('#id_tindakan').hasClass("select2-hidden-accessible")) {
                $('#id_tindakan').select2({
                    dropdownParent: $('#tambahModal'),
                    placeholder: "Silahkan Pilih Tindakan",
                    allowClear: true
                });
            }
        });
    });
</script>

<!-- untuk script tindakan multi -->
<script>
    let daftarTindakan = [];

    document.getElementById('tambahTindakan').addEventListener('click', function() {
        const idTindakan = document.getElementById('id_tindakan').value;
        const tindakanSelect = document.getElementById('id_tindakan');
        const namaTindakan = tindakanSelect.options[tindakanSelect.selectedIndex].dataset.nama;
        const tarif = tindakanSelect.options[tindakanSelect.selectedIndex].dataset.tarif;
        const keterangan = document.getElementById('keterangan').value;

        if (!idTindakan) return alert('Pilih tindakan terlebih dahulu');

        daftarTindakan.push({
            id_tindakan: idTindakan,
            nama: namaTindakan,
            tarif: tarif,
            keterangan: keterangan
        });
        renderTabel();

        // Reset field
        document.getElementById('id_tindakan').value = '';
        document.getElementById('keterangan').value = '';
    });

    function renderTabel() {
        const tbody = document.querySelector('#tabelTindakanSementara tbody');
        tbody.innerHTML = '';
        daftarTindakan.forEach((item, index) => {
            const row = `<tr>
            <td>${item.nama}</td>
            <td>Rp ${parseInt(item.tarif).toLocaleString()}</td>
            <td>${item.keterangan}</td>
            <td><button type="button" class="btn btn-danger btn-sm" onclick="hapusTindakan(${index})">Hapus</button></td>
        </tr>`;
            tbody.innerHTML += row;
        });
    }

    function hapusTindakan(index) {
        daftarTindakan.splice(index, 1);
        renderTabel();
    }

    document.getElementById('formTambahData').addEventListener('submit', function(e) {
        e.preventDefault();

        const idKunjungan = document.getElementById('id_kunjungan').value;
        if (!idKunjungan) return alert('Pilih kunjungan terlebih dahulu');
        if (daftarTindakan.length === 0) return alert('Belum ada tindakan yang ditambahkan');

        fetch('<?= base_url('tindakan/tambahData') ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id_kunjungan: idKunjungan,
                    tindakan: daftarTindakan.map(t => ({
                        id_tindakan: t.id_tindakan,
                        keterangan: t.keterangan
                    }))
                })
            })
            .then(res => res.json())
            .then(response => {
                if (response.status === 'success') {
                    Swal.fire({
                        title: 'Berhasil!',
                        text: response.message,
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            // Tutup modal & reload halaman
                            $('#tambahModal').modal('hide');
                            location.reload();
                        }
                    });
                } else {
                    Swal.fire({
                        title: 'Gagal!',
                        text: response.message,
                        icon: 'error',
                        confirmButtonText: 'Tutup'
                    });
                }
            })
            .catch(err => {
                console.error(err);
                Swal.fire('Kesalahan!', 'Terjadi kesalahan saat menyimpan data.', 'error');
            });
    });
</script>

<!-- untuk script untuk select2 -->
<script>
    $(document).ready(function() {
        // Ketika modal ditampilkan
        $('#tambahModal').on('shown.bs.modal', function() {
            // Inisialisasi Select2
            $(' #id_kunjungan').select2({
                dropdownParent: $('#tambahModal'), // Memastikan dropdown muncul di dalam modal
                placeholder: "Silahkan Pilih",
                allowClear: true
            });
        });

        // Inisialisasi Select2 untuk modal edit
        $('#editModal').on('shown.bs.modal', function() {
            // Inisialisasi Select2
            $(' #edit_id_kunjungan').select2({
                dropdownParent: $('#editModal'), // Memastikan dropdown muncul di dalam modal
                placeholder: "Silahkan Pilih",
                allowClear: true
            });
        });
    });
</script>


<!-- Ambil Data untuk nilai Update -->
<script>
    // Fungsi untuk memuat data ke modal edit
    function updateData(id_tindakan) {

        $.ajax({
            url: "<?= base_url('MasterTindakan/getData') ?>/" + id_tindakan, // URL untuk mendapatkan data berdasarkan ID
            type: "GET",
            dataType: "json",
            success: function(response) {
                if (response) {
                    $('#id_tindakan').val(response.id_tindakan);
                    $('#edit_nama_tindakan').val(response.nama_tindakan);
                    $('#edit_deskripsi').val(response.deskripsi);

                    // Format tarif jadi Rupiah saat tampil
                    let tarifFormatted = new Intl.NumberFormat('id-ID').format(response.tarif);
                    $('#edit_tarif').val(tarifFormatted);
                    $('#editModal').modal('show'); // Tampilkan modal
                } else {
                    alert('Data tidak ditemukan!');
                }
            },
            error: function(xhr, status, error) {
                alert('Terjadi kesalahan. Silakan coba lagi.');
            }
        });
    }
</script>


<!-- Untuk delete -->
<script>
    function deleteData(id_tindakan) {
        // Konfirmasi untuk menghapus data
        Swal.fire({
            title: 'Apakah Anda yakin ingin menghapus data ini?',
            text: "Data yang dihapus tidak dapat dikembalikan.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Iya, Hapus!',
            cancelButtonText: 'Batal',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: "<?= base_url('MasterTindakan/deleteData') ?>", // Ganti dengan URL endpoint controller Anda
                    type: "POST", // Menggunakan POST karena ini adalah penghapusan data
                    data: {
                        id_tindakan: id_tindakan, // Mengirimkan ID ke server
                        // Anda bisa menambahkan parameter lain jika diperlukan
                    },
                    dataType: "json", // Menentukan format data yang diterima (JSON)
                    success: function(response) {
                        // Jika berhasil menambahkan data
                        if (response.status === 'success') {
                            Swal.fire({
                                title: 'Berhasil!',
                                text: response.message,
                                icon: 'success',
                                confirmButtonText: 'OK'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    // Menutup modal form
                                    $('#tambahModal').modal('hide');

                                    // Menyegarkan tabel data tanpa reload
                                    location.reload(); // Atau panggil fungsi khusus untuk refresh tabel
                                }
                            });
                        } else if (response.status === 'error') {
                            // Jika terjadi kesalahan
                            Swal.fire({
                                title: 'Gagal!',
                                text: response.message,
                                icon: 'error',
                                confirmButtonText: 'Tutup'
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        // Jika terjadi error pada request
                        Swal.fire({
                            title: 'Kesalahan!',
                            text: 'Terjadi kesalahan dalam proses. Silakan coba lagi.',
                            icon: 'error',
                            confirmButtonText: 'Tutup'
                        });
                    }
                });
            }
        });
    }
</script>

<!-- untuk tombol status produk -->
<script>
    function changeStatus(id_mastertindakan, is_active) {
        Swal.fire({
            title: "Konfirmasi",
            text: "Apakah Anda yakin ingin mengubah status Produk ini?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Ya, Ubah!",
            cancelButtonText: "Batal",
        }).then((result) => {
            if (result.isConfirmed) {
                // Kirim permintaan AJAX ke server
                $.ajax({
                    url: '<?= base_url('mastertindakan/changeStatus') ?>', // Sesuaikan dengan route aplikasi Anda
                    type: 'POST',
                    data: {
                        id_mastertindakan: id_mastertindakan,
                        is_active: is_active
                    },
                    success: function(response) {
                        if (response.status === 'success') {
                            Swal.fire({
                                title: "Berhasil!",
                                text: response.message,
                                icon: "success",
                                confirmButtonText: "OK"
                            }).then(() => {
                                location.reload(); // Reload halaman setelah berhasil
                            });
                        } else if (response.status === 'error') {
                            Swal.fire({
                                title: "Gagal!",
                                text: response.message,
                                icon: "error",
                                confirmButtonText: "OK"
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            title: "Kesalahan!",
                            text: "Terjadi kesalahan pada server. Silakan coba lagi nanti.",
                            icon: "error",
                            confirmButtonText: "OK"
                        });
                    }
                });
            }
        });
    }
</script>


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