<?= $this->extend('layout/admin') ?>

<?= $this->section('content') ?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold mb-0">Pengaturan Sistem</h3>
</div>

<?php if(session()->getFlashdata('pesan')): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle me-2"></i> <?= session()->getFlashdata('pesan') ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="row g-4">
    <!-- Kolom Form Konfigurasi -->
    <div class="col-md-7">
        <div class="card border-0 shadow-sm" style="border-radius: 10px;">
            <div class="card-header bg-white py-3 fw-bold">Konfigurasi Umum & API</div>
            <div class="card-body p-4">
                <form action="<?= base_url('admin/pengaturan/simpan') ?>" method="POST">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Nama Instansi</label>
                        <input type="text" class="form-control" name="nama_instansi" value="<?= $pengaturan['nama_instansi'] ?>" required>
                    </div>
                    
                    <hr class="my-4">
                    <h6 class="fw-bold mb-3 text-primary"><i class="bi bi-whatsapp"></i> Konfigurasi WhatsApp Gateway (GoWA)</h6>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">URL Server GoWA</label>
                        <input type="url" class="form-control" name="gowa_url" value="<?= $pengaturan['gowa_url'] ?>" placeholder="Contoh: http://localhost:3000" required>
                        <small class="text-muted">Masukkan alamat dan port tempat GoWA dijalankan.</small>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold">Kredensial Basic Auth (User:Password)</label>
                        <input type="text" class="form-control" name="gowa_auth" value="<?= $pengaturan['gowa_auth'] ?>" placeholder="Contoh: admin:admin" required>
                        <small class="text-muted">Harus sama persis dengan argumen <code>--basic-auth</code> saat menjalankan GoWA.</small>
                    </div>

                    <button type="submit" class="btn btn-dark fw-bold px-4">Simpan Konfigurasi</button>
                </form>
            </div>
        </div>
    </div>

    <!-- Kolom Scanner QR Code -->
    <div class="col-md-5">
        <div class="card border-0 shadow-sm" style="border-radius: 10px;">
            <div class="card-header bg-white py-3 fw-bold">
                Pairing Perangkat (Device: <span class="text-primary">dprd_sbb</span>)
            </div>
            <div class="card-body p-4 text-center">
                
                <!-- Indikator Status -->
                <div id="status-container" class="mb-4">
                    <span class="badge bg-secondary p-2 fs-6 spinner-border-sm"><i class="bi bi-hourglass-split"></i> Mengecek Status WhatsApp...</span>
                </div>

                <p id="qr-instruction" class="text-muted mb-4 d-none">Klik tombol di bawah untuk memunculkan QR Code, lalu scan menggunakan aplikasi WhatsApp Anda (Tautkan Perangkat).</p>
                
                <div id="qr-container" class="mb-4 d-none p-3 border rounded bg-light">
                    <div id="qr-loading" class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <img id="qr-image" src="" alt="QR Code GoWA" class="img-fluid d-none" style="max-width: 250px;">
                    <p id="qr-error" class="text-danger fw-bold d-none mt-2"></p>
                </div>

                <button id="btn-generate-qr" class="btn btn-success fw-bold w-100 py-2 d-none">
                    <i class="bi bi-qr-code-scan me-2"></i> Munculkan QR Code
                </button>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
document.addEventListener("DOMContentLoaded", function() {
    cekStatusWA();
});

function cekStatusWA() {
    const statusBadge = document.getElementById('status-container');
    const instruction = document.getElementById('qr-instruction');
    const btnQr = document.getElementById('btn-generate-qr');

    fetch('<?= base_url('admin/pengaturan/gowa-status') ?>')
        .then(response => response.json())
        .then(res => {
            let isConnected = false;

            // Logika Sapu Jagat: Ubah seluruh respon JSON jadi string besar, lalu cari kata kuncinya.
            if (res.status === 200 && res.data) {
                const rawDataStr = JSON.stringify(res.data).toUpperCase();
                // GoWA biasanya mengembalikan CONNECTED atau LOGGED_IN jika sudah terhubung
                if (rawDataStr.includes('CONNECTED') || rawDataStr.includes('LOGGED_IN')) {
                    isConnected = true;
                }
            }

            if(isConnected) {
                statusBadge.innerHTML = '<span class="badge bg-success p-2 fs-6"><i class="bi bi-whatsapp"></i> WhatsApp Sudah Terhubung</span>';
                instruction.classList.add('d-none');
                btnQr.classList.add('d-none');
            } else {
                // Kembalikan ke tampilan normal jika belum terhubung (tanpa pesan RAW)
                statusBadge.innerHTML = '<span class="badge bg-danger p-2 fs-6"><i class="bi bi-x-circle"></i> WhatsApp Belum Terhubung</span>';
                instruction.classList.remove('d-none');
                btnQr.classList.remove('d-none');
            }
        })
        .catch(err => {
            statusBadge.innerHTML = '<span class="badge bg-warning text-dark p-2 fs-6"><i class="bi bi-exclamation-triangle"></i> Gagal Mengecek Status API Lokal</span>';
        });
}

document.getElementById('btn-generate-qr').addEventListener('click', function() {
    const container = document.getElementById('qr-container');
    const loading = document.getElementById('qr-loading');
    const image = document.getElementById('qr-image');
    const errorTxt = document.getElementById('qr-error');

    container.classList.remove('d-none');
    loading.classList.remove('d-none');
    image.classList.add('d-none');
    errorTxt.classList.add('d-none');

    fetch('<?= base_url('admin/pengaturan/gowa-qr') ?>')
        .then(response => response.json())
        .then(res => {
            loading.classList.add('d-none');
            
            if (res.data && res.data.results && res.data.results.qr_link) {
                image.src = res.data.results.qr_link;
                image.classList.remove('d-none');
            } else {
                // Jika GoWA membalas tanpa link QR, cek apakah ternyata sudah terhubung
                const rawDataStr = res.data ? JSON.stringify(res.data).toUpperCase() : "";
                if(rawDataStr.includes('SUCCESS') || rawDataStr.includes('CONNECTED') || rawDataStr.includes('LOGGED_IN')) {
                   cekStatusWA(); // Otomatis refresh UI status di atas
                   container.classList.add('d-none');
                } else {
                   errorTxt.innerText = "Gagal memuat QR Code. Pastikan server GoWA merespon dengan benar.";
                   errorTxt.classList.remove('d-none');
                }
            }
        })
        .catch(err => {
            loading.classList.add('d-none');
            errorTxt.innerText = 'Terjadi kesalahan saat memproses API GoWA.';
            errorTxt.classList.remove('d-none');
        });
});
</script>
<?= $this->endSection() ?>