<?php if(check_permission('setting', 'can_view')): ?>
<div class="container mt-4">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">Pengaturan</h5>
    </div>

    <div class="row lign-items-stretch">

        <!-- ================== 1. PENGATURAN UMUM ================== -->
        <div class="col-md-6 mb-3">
            <div class="card modern-card shadow-sm border-0 rounded-4 h-100">
                <div class="card-body p-4">

                    <h6 class="mb-0">Umum</h6>
                    <hr>

                    <form action="<?= base_url('setting/save_umum') ?>" method="POST">

                        <div class="mb-3">
                            <label class="form-label">Nama Lembaga</label>
                            <input type="text" name="nama_lembaga" class="form-control" value="<?= $config->nama_lembaga ?>">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Pimpinan Lembaga</label>
                            <input type="text" name="pimpinan_lembaga" class="form-control" value="<?= $config->pimpinan_lembaga ?>">
                        </div>

                        <button type="submit" class="btn btn-success btn-add rounded-3">
                            Simpan
                        </button>

                    </form>

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

        <!-- ================== 2. SETTING CARD ================== -->
        <div class="col-md-6 mb-3">
            <div class="card modern-card shadow-sm border-0 rounded-4 h-100">
                <div class="card-body p-4">

                    <h6 class="mb-0">Setting Card</h6>
                    <hr>
                    <div class="items-card-center">

                        <img id="defaultBg" src="<?= base_url($config->card_background) ?>" hidden>
                        <div id="cardPreview"></div>

                        <small class="text-muted d-block mt-2 mb-4">Preview akan berubah otomatis</small>
                    </div>

                    <form action="<?= base_url('setting/save_card') ?>" method="POST" enctype="multipart/form-data">

                        <div class="mb-3">
                            <label class="form-label">Upload Background Kartu (Ukuran 300 x 480 pixel)</label>
                            <input type="file" name="card_background" id="bgInput" class="form-control" accept="image/*">
                        </div>

                        <button type="submit" class="btn btn-success btn-add rounded-3">
                            Simpan Background
                        </button>

                    </form>

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


        <!-- ================== 3. SETTING WHATSAPP ================== -->
        <div class="col-md-6 mb-3">
            <div class="card modern-card shadow-sm border-0 rounded-4 h-100">
                <div class="card-body p-4">

                    <h6 class="mb-0">Setting Whatsapp</h6>
                    <hr>

                    <form action="<?= base_url('setting/save_whatsapp') ?>" method="POST">

                        <div class="mb-3">
                            <label class="form-label">Mode WhatsApp</label>
                            <select class="form-select" id="waMode" name="wa_mode">
                                <option value="">-- Pilih --</option>
                                <option value="official" <?= ($config->wa_mode == 'official' ) ? 'selected' : '' ?>>Official API</option>
                                <option value="unofficial" <?= ($config->wa_mode == 'unofficial' ) ? 'selected' : '' ?>>Unofficial Gateway</option>
                            </select>
                        </div>

                        <!-- OFFICIAL -->
                        <div id="officialForm" style="display:none;">
                            <div class="mb-3">
                                <label class="form-label">Phone Number</label>
                                <input type="text" name="wa_phone" class="form-control" value="<?= $config->wa_phone; ?>">
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Phone Number ID</label>
                                <input type="text" name="wa_phone_id" class="form-control" value="<?= $config->wa_phone_id; ?>">
                            </div>

                            <div class="mb-3">
                                <label class="form-label">WABA ID</label>
                                <input type="text" name="wa_waba_id" class="form-control" value="<?= $config->wa_waba_id; ?>">
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Access Token</label>
                                <input type="text" name="wa_access_token" class="form-control" value="<?= $config->wa_access_token; ?>">
                            </div>
                        </div>

                        <!-- UNOFFICIAL -->
                        <div id="unofficialForm" style="display:none;">
                            <div class="mb-3">
                                <label class="form-label">Endpoint URL</label>
                                <input type="text" name="wa_endpoint" class="form-control" value="<?= $config->wa_endpoint; ?>">
                            </div>

                            <div class="mb-3">
                                <label class="form-label">API Key</label>
                                <input type="text" name="wa_api_key" class="form-control" value="<?= $config->wa_api_key; ?>">
                            </div>
                            <center>
                                <img id="waStatusImage" src="" style="width:220px; margin-top:15px;"><br>
                                <button type="button" id="scanWhatsappQR" class="btn btn-success btn-add rounded-3 mb-4">
                                    Cek Tautan Whatsapp Gateway
                                </button>
                            </center>
                        </div>

                        <button type="submit" class="btn btn-success btn-add rounded-3">
                            Simpan
                        </button>

                    </form>

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


        <!-- ================== 4. TEMPLATE PESAN ================== -->
        <div class="col-md-6 mb-3">
            <div class="card modern-card shadow-sm border-0 rounded-4 h-100">
                <div class="card-body p-4">

                    <h6 class="mb-0">Setting Template Pesan</h6>
                    <hr>

                    <table class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th width="5%">No</th>
                                <th>Nama</th>
                                <th>Pesan</th>
                                <th width="10%">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($template_pesan as $i => $row): ?>
                            <tr>
                                <td><?= $i+1 ?></td>
                                <td><?= $row->nama_template ?></td>
                                <td><?= $row->isi_template ?></td>
                                <td>
                                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#editModal<?= $row->id ?>">
                                        Edit
                                    </button>
                                </td>
                            </tr>

                            <!-- Modal Edit -->
                            <div class="modal fade" id="editModal<?= $row->id ?>">
                                <div class="modal-dialog modal-dialog-centered">
                                    <div class="modal-content rounded-4">
                                        <div class="modal-header">
                                            <h6 class="modal-title">Edit Pesan</h6>
                                            <button class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>

                                        <form action="<?= base_url('setting/update_template_pesan') ?>" method="POST">
                                            <div class="modal-body">

                                                <input type="hidden" name="id" value="<?= $row->id ?>">

                                                <div class="mb-3">
                                                    <label class="form-label">Nama</label>
                                                    <input type="text" name="nama_template" class="form-control" value="<?= $row->nama_template ?>">
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label">Pesan</label>
                                                    <textarea name="isi_template" class="form-control" rows="12"><?= $row->isi_template ?></textarea>
                                                </div>

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

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

                            <?php endforeach; ?>
                        </tbody>
                    </table>

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

    </div>
</div>


<!-- JS untuk dynamic show/hide -->
<script>
function showWaMode(mode) {
    document.getElementById("officialForm").style.display   = (mode === "official") ? "block" : "none";
    document.getElementById("unofficialForm").style.display = (mode === "unofficial") ? "block" : "none";
}

// Saat dropdown berubah
document.getElementById("waMode").addEventListener("change", function() {
    showWaMode(this.value);
});

// Saat halaman pertama kali load → pakai value dari dropdown (sudah diset PHP)
document.addEventListener("DOMContentLoaded", function() {
    let initial = document.getElementById("waMode").value;
    showWaMode(initial);
});


// =====================================================
// 1. LOAD BACKGROUND DEFAULT SAAT PAGE AWAL TERBUKA
// =====================================================
window.addEventListener("DOMContentLoaded", function () {

    let defaultBgElement = document.getElementById("defaultBg");
    let preview = document.getElementById("cardPreview");

    if (!defaultBgElement) {
        console.error("defaultBg tidak ditemukan!");
        return;
    }
    if (!preview) {
        console.error("cardPreview tidak ditemukan!");
        return;
    }

    let defaultBg = defaultBgElement.src;
    if (defaultBg && defaultBg !== "") {
        validateAndLoadCard(defaultBg);
    }
});


// =====================================================
// 2. EVENT: USER UPLOAD GAMBAR BACKGROUND BARU
// =====================================================
document.getElementById("bgInput").addEventListener("change", function (e) {
    let file = e.target.files[0];
    if (!file) return;

    let reader = new FileReader();
    reader.onload = function (evt) {
        validateAndLoadCard(evt.target.result);
    };
    reader.readAsDataURL(file);
});


// =====================================================
// 3. VALIDASI RASIO GAMBAR (PORTRAIT / LANDSCAPE)
// =====================================================
function validateAndLoadCard(imgSrc) {
    let img = new Image();

    img.onload = function () {
        let width = img.width;
        let height = img.height;

        let ratio = width / height;
        console.log("Rasio gambar:", ratio);

        let isPortrait = ratio < 0.9;     // 2:3 atau sejenis
        let isLandscape = ratio > 1.2;    // 3:2 atau sejenis

        if (!isPortrait && !isLandscape) {
            alert("⚠️ Gambar tidak sesuai rasio ID Card!\nGunakan potret (2:3) atau landscape (3:2).");
            return;
        }

        loadCardPreviewFromImage(imgSrc, isPortrait);
    };

    img.onerror = function () {
        console.error("Gambar tidak bisa diload:", imgSrc);
    };

    img.src = imgSrc;
}


// =====================================================
// 4. LOAD PREVIEW + GANTI TEMPLATE
// =====================================================
function loadCardPreviewFromImage(imgSrc, isPortrait) {
    let preview = document.getElementById("cardPreview");
    if (!preview) {
        console.error("Element #cardPreview tidak ditemukan!");
        return;
    }

    // Set background image
    preview.style.backgroundImage = `url('${imgSrc}')`;

    // Reset semua class
    preview.className = "";

    // Tambahkan class sesuai orientasi
    if (isPortrait) {
        preview.classList.add("id-card-potret");
        preview.innerHTML = portraitTemplate();
    } else {
        preview.classList.add("id-card-lemscape");
        preview.innerHTML = landscapeTemplate();
    }

    console.log("Template loaded:", isPortrait ? "Potret" : "Landscape");
}



function portraitTemplate() {
    return `
        <div class="card-inner">

            <div class="card-logo">
                <img src="assets/img/logo.png">
            </div>

            <div class="card-title">Kartu Tanda Wali Santri</div>

            <div class="photo-wrapper">
                <img src="assets/img/foto.jpg">
            </div>

            <div class="card-info">
                <div class="nama">Nama Santri</div>
                <div class="nis">NIS: 00000000</div>
                <div class="kelas">Tahun Masuk: -</div>
                <div class="alamat">Alamat lengkap tampil di sini...</div>
            </div>

            <div class="qr-wrapper">
                <img src="assets/img/qr.png" width="100%">
            </div>

        </div>
    `;
}

function landscapeTemplate() {
    return `
        <div class="card-inner">

            <div class="card-logo">
                <img src="assets/img/logo.png">
            </div>

            <div class="card-title">Kartu Tanda Wali Santri</div>

            <div class="landscape-content">

                <div class="photo-wrapper">
                    <img src="assets/img/foto.jpg">
                </div>

                <div class="card-info">
                    <div class="nama">Nama Santri</div>
                    <div class="nis">NIS: 00000000</div>
                    <div class="kelas">Tahun Masuk: -</div>
                    <div class="alamat">Alamat lengkap tampil di sini...</div>
                </div>

                <div class="qr-wrapper">
                    <img src="assets/img/qr.png" width="100%">
                </div>

            </div>

        </div>
    `;
}



// -----------------------------
// Perintah untuk cek status whatsapp
// -----------------------------

document.getElementById("scanWhatsappQR").addEventListener("click", function () {
    let counter = 0;
    let imgTag = document.getElementById("waStatusImage");

    function checkStatusLoop() {
        fetch(`<?= base_url('setting/cek_whatsapp_status') ?>`)
            .then(res => res.json())
            .then(data => {

                console.log("Status:", data.status);

                imgTag.src = data.img;   // tampilkan gambar ke <img>

                if (data.status === "CONNECTED") {
                    console.log("Whatsapp sudah terhubung, stop loop");
                    return; // STOP AUTOMATIS
                }

                counter++;
                if (counter < 50) {
                    setTimeout(checkStatusLoop, 2000);
                } else {
                    console.log("Loop selesai 50x");
                }
            })
            .catch(err => console.error(err));
    }

    checkStatusLoop();
});

</script>


<?php endif; ?>