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

<!-- Untuk Css -->
<?= $this->section('css') ?>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>
    <style>
        * { box-sizing: border-box; }
        body { font-family: 'Inter', sans-serif; background: #f8fafc; color: #334155; }
        .nav-active { background:#0099b8; color:#fff !important; border-radius:6px; }
        .ctrl-textarea { padding:10px 12px; border-radius:10px; border:1px solid #e2e8f0; font-size:13px; font-family:'Inter',sans-serif; outline:none; color:#1e293b; background:#fff; width:100%; resize:vertical; min-height:90px; }
        .ctrl-textarea:focus { border-color:#0099b8; box-shadow:0 0 0 3px rgba(0,153,184,.1); }
        .ctrl-select, .ctrl-file { padding:8px 12px; border-radius:10px; border:1px solid #e2e8f0; font-size:13px; font-family:'Inter',sans-serif; outline:none; color:#1e293b; background:#fff; width:100%; }
        .ctrl-select:focus, .ctrl-file:focus { border-color:#0099b8; }
        .btn-dl { width:100%; padding:13px; border-radius:12px; border:none; font-size:13px; font-weight:700; cursor:pointer; font-family:'Inter',sans-serif; color:#fff; background:#15803d; display:flex; align-items:center; justify-content:center; gap:8px; text-decoration:none; transition:background .12s; }
        .btn-dl:hover { background:#166534; }
        .card { background:#fff; border:1px solid #e2e8f0; border-radius:20px; padding:28px; box-shadow:0 2px 12px rgba(0,0,0,.04); }
        
        /* Container Preview QR yang presisi dan Full */
        #qrCanvas { 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            width: 100%; 
            aspect-ratio: 1 / 1; 
            background: #f8fafc; 
            border: 2px dashed #cbd5e1; 
            border-radius: 16px; 
            padding: 12px;
            overflow: hidden;
        }
        #qrCanvas canvas { 
            width: 100% !important; 
            height: 100% !important; 
            object-fit: contain; 
            border-radius: 8px; 
        }
        
        .tab-btn { flex:1; padding:9px; border-radius:9px; border:1.5px solid #e2e8f0; font-size:11px; font-weight:700; cursor:pointer; font-family:'Inter',sans-serif; color:#475569; background:#fff; transition:all .12s; }
        .tab-btn.sel { background:#0099b8; color:#fff; border-color:#0099b8; }
        .tab-btn:not(.sel):hover { background:#f1f5f9; }
    </style>
<?= $this->endSection(); ?>


<!-- Untuk Main -->
<?= $this->section('conten');?>
	<section style="background:linear-gradient(135deg,#1e1b4b 0%,#4c1d95 50%,#0099b8 100%)">
    <div class="max-w-3xl mx-auto px-6 py-10 text-white">
        <p class="text-xs text-purple-200 uppercase tracking-widest font-medium mb-1">
            <a href="<?= base_url('tools')?>" class="hover:underline">Alat Digital</a> › QR Code Generator
        </p>
        <h1 class="text-2xl font-bold mb-1">📱 QR Code Generator + Logo</h1>
        <p class="text-sm text-purple-100">Buat QR Code kustom dengan logo di tengah — gratis, cepat, dan aman diproses di browser.</p>
    </div>
</section>

<main class="max-w-3xl mx-auto px-4 py-8 space-y-5">

    <div class="bg-white border border-slate-200 rounded-xl px-4 py-3 flex items-center gap-3 shadow-sm flex-wrap">
        <a href="<?= base_url('tools')?>" class="bg-slate-50 hover:bg-slate-100 border border-slate-200 text-slate-700 text-[11px] font-bold py-1 px-3 rounded-lg transition">⬅ Kembali ke Alat Digital</a>
        <div class="h-4 w-px bg-slate-200"></div>
        <span class="text-xs font-bold text-slate-700">📱 QR Code Generator</span>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px" class="items-start">

        <!-- FORM INPUT -->
        <div class="card space-y-4">
            <!-- TYPE TABS -->
            <div>
                <div style="font-size:12px;font-weight:700;color:#475569;margin-bottom:8px">Jenis Konten</div>
                <div style="display:flex;gap:6px;flex-wrap:wrap">
                    <button class="tab-btn sel" onclick="setType('url', event)">🔗 URL</button>
                    <button class="tab-btn" onclick="setType('text', event)">📝 Teks</button>
                    <button class="tab-btn" onclick="setType('wa', event)">💬 WhatsApp</button>
                    <button class="tab-btn" onclick="setType('tel', event)">📞 Telepon</button>
                </div>
            </div>

            <!-- INPUT AREA -->
            <div>
                <label style="font-size:12px;font-weight:700;color:#475569;display:block;margin-bottom:6px" id="inputLabel">URL / Alamat Web</label>
                <textarea id="qrText" class="ctrl-textarea" placeholder="https://pena-ilmu.com" oninput="liveQR()"></textarea>
                <div id="inputHint" style="font-size:10px;color:#94a3b8;margin-top:4px">Contoh: https://pena-ilmu.com</div>
            </div>

            <!-- UPLOAD LOGO -->
            <div>
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
                    <label style="font-size:12px;font-weight:700;color:#475569;">Logo di Tengah (Opsional)</label>
                    <button id="removeLogoBtn" onclick="removeLogo()" style="display:none;font-size:10px;color:#b91c1c;background:none;border:none;cursor:pointer;font-weight:600">✕ Hapus Logo</button>
                </div>
                <input type="file" id="logoInput" class="ctrl-file" accept="image/*" onchange="handleLogoUpload(this)">
            </div>

            <!-- SIZE -->
            <!-- <div>
                <label style="font-size:12px;font-weight:700;color:#475569;display:block;margin-bottom:6px">Resolusi Ekspor</label>
                <select id="qrSize" class="ctrl-select" onchange="liveQR()">
                    <option value="300">300 × 300 px — Standar</option>
                    <option value="500" selected>500 × 500 px — Tinggi (Rekomendasi)</option>
                    <option value="800">800 × 800 px — Sangat Tinggi / Cetak</option>
                </select>
            </div> -->

            <!-- COLORS -->
            <div>
                <!-- <label style="font-size:12px;font-weight:700;color:#475569;display:block;margin-bottom:8px">Warna QR</label> -->
                <div style="display:flex;gap:12px;align-items:center">
                    <div style="display:flex;align-items:center;gap:6px">
                        <input type="color" id="qrColorDark" value="#000000" onchange="liveQR()"
                            style="width:34px;height:32px;border-radius:8px;border:1px solid #e2e8f0;cursor:pointer;padding:2px" disabled >
                        <div>
                            <div style="font-size:10px;font-weight:600;color:#475569">QR</div>
                            <div style="font-size:9px;color:#94a3b8" id="darkHex">#00fff0000</div>
                        </div>
                    </div>
                    <div style="display:flex;align-items:center;gap:6px">
                        <input type="color" id="qrColorLight" value="#ffffff" onchange="liveQR()"
                            style="width:34px;height:32px;border-radius:8px;border:1px solid #e2e8f0;cursor:pointer;padding:2px" disabled >
                        <div>
                            <div style="font-size:10px;font-weight:600;color:#475569">Latar</div>
                            <div style="font-size:9px;color:#94a3b8" id="lightHex">#ffffff</div>
                        </div>
                    </div>
                    <!-- <button onclick="resetColors()" style="margin-left:auto;font-size:10px;color:#0099b8;background:none;border:none;cursor:pointer;font-weight:600">↺ Reset</button> -->
                </div>
            </div>
        </div>

        <!-- PREVIEW BOX -->
        <div class="card space-y-4">
            <div style="font-size:12px;font-weight:700;color:#475569">Preview QR Code</div>
            
            <div id="qrCanvas">
                <div id="placeholder" style="text-align:center;color:#94a3b8;padding:20px">
                    <div style="font-size:40px;margin-bottom:8px">📱</div>
                    <div style="font-size:12px">QR Code akan tampil penuh di sini...</div>
                </div>
                <canvas id="qrCanvasElement" style="display:none;"></canvas>
            </div>

            <div id="qrErrMsg" style="display:none;background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:10px 12px;font-size:11px;color:#b91c1c"></div>
            
            <a id="qrDlBtn" style="display:none" class="btn-dl" onclick="downloadQR()">
                <i class="fa-solid fa-download fa-xs"></i> Download PNG
            </a>
            
            <div id="qrTips" style="font-size:10px;color:#94a3b8;text-align:center;line-height:1.6">
                💡 Logo akan disesuaikan otomatis di tengah .
            </div>
        </div>

    </div>
</main>
<?= $this->endSection(); ?>


<!-- Untuk Js -->

<?= $this->section('myscript') ?>

	<script>
const types = {
    url:  { label:'URL / Alamat Web', hint:'Contoh: https://pena-ilmu.com', placeholder:'https://pena-ilmu.com' },
    text: { label:'Teks Bebas', hint:'Masukkan teks apapun yang ingin dikodekan.', placeholder:'Ketik teks di sini...' },
    wa:   { label:'Nomor WhatsApp', hint:'Format: 628xxxxxxxxxx (tanpa + atau 0 di depan)', placeholder:'628123456789' },
    tel:  { label:'Nomor Telepon', hint:'Format: +62812xxxxx atau 0812xxxxx', placeholder:'+62812345678' }
};

let currentType = 'url';
let uploadedLogoImg = null;

function setType(t, ev) {
    currentType = t;
    const cfg = types[t];
    document.getElementById('inputLabel').innerText = cfg.label;
    document.getElementById('inputHint').innerText = cfg.hint;
    document.getElementById('qrText').placeholder = cfg.placeholder;
    document.getElementById('qrText').value = '';
    
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('sel'));
    if(ev && ev.target) ev.target.classList.add('sel');
    
    clearQR();
}

function handleLogoUpload(input) {
    const file = input.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
            const img = new Image();
            img.onload = function () {
                uploadedLogoImg = img;
                document.getElementById('removeLogoBtn').style.display = 'block';
                liveQR();
            };
            img.src = e.target.result;
        };
        reader.readAsDataURL(file);
    }
}

function removeLogo() {
    uploadedLogoImg = null;
    document.getElementById('logoInput').value = '';
    document.getElementById('removeLogoBtn').style.display = 'none';
    liveQR();
}

function buildContent() {
    const raw = document.getElementById('qrText').value.trim();
    if(!raw) return '';
    if(currentType === 'wa') return 'https://wa.me/' + raw.replace(/\D/g,'');
    if(currentType === 'tel') return 'tel:' + raw;
    return raw;
}

function clearQR() {
    document.getElementById('placeholder').style.display = 'block';
    document.getElementById('qrCanvasElement').style.display = 'none';
    document.getElementById('qrDlBtn').style.display = 'none';
    document.getElementById('qrErrMsg').style.display = 'none';
}

function liveQR() {
    const content = buildContent();
    document.getElementById('darkHex').innerText = document.getElementById('qrColorDark').value;
    document.getElementById('lightHex').innerText = document.getElementById('qrColorLight').value;
    
    if(!content) { clearQR(); return; }
    
    const size = 500;
    const dark = document.getElementById('qrColorDark').value;
    const light = document.getElementById('qrColorLight').value;
    const canvas = document.getElementById('qrCanvasElement');
    
    document.getElementById('qrErrMsg').style.display = 'none';
    
    try {
        // Generate QR Code Dasar
        const qr = new QRious({
            element: canvas,
            value: content,
            size: size,
            background: light,
            foreground: dark,
            level: 'H', // Error correction level H (maksimal untuk mentoleransi penempelan logo)
            padding: Math.round(size * 0.05)
        });

        // Jika Pengguna Menambahkan Logo, Gambar di Atas Canvas
        if (uploadedLogoImg) {
            const ctx = canvas.getContext('2d');
            
            // Ukuran ideal logo adalah 22% dari ukuran total QR agar tidak mengganggu pemindaian
            const logoSize = size * 0.22;
            const x = (size - logoSize) / 2;
            const y = (size - logoSize) / 2;
            const borderRadius = logoSize * 0.15;

            // Gambar Background Putih/Latar untuk logo agar kontras dan tidak bertabrakan dengan garis QR
            ctx.fillStyle = light;
            ctx.beginPath();
            if (ctx.roundRect) {
                ctx.roundRect(x - 4, y - 4, logoSize + 8, logoSize + 8, borderRadius);
            } else {
                ctx.rect(x - 4, y - 4, logoSize + 8, logoSize + 8);
            }
            ctx.fill();

            // Tempelkan Logo di Tengah
            ctx.drawImage(uploadedLogoImg, x, y, logoSize, logoSize);
        }

        document.getElementById('placeholder').style.display = 'none';
        canvas.style.display = 'block';
        document.getElementById('qrDlBtn').style.display = 'flex';
    } catch(e) {
        clearQR();
        document.getElementById('qrErrMsg').style.display = 'block';
        document.getElementById('qrErrMsg').innerText = '⚠️ Teks terlalu panjang untuk QR Code. Coba persingkat konten.';
    }
}

function downloadQR() {
    const canvas = document.getElementById('qrCanvasElement');
    if(!canvas || canvas.style.display === 'none') return;
    const src = canvas.toDataURL('image/png');
    const a = document.createElement('a');
    a.href = src;
    a.download = 'qrcode-pena-ilmu.png';
    a.click();
}

function resetColors() {
    document.getElementById('qrColorDark').value = '#000000';
    document.getElementById('qrColorLight').value = '#ffffff';
    liveQR();
}
</script>
<?= $this->endSection(); ?>