
<div class="bg-white rounded-lg shadow-sm border border-gray-200">
    <div class="px-6 py-4 border-b border-gray-200">
        <h3 class="text-sm font-semibold text-gray-900 uppercase tracking-wide">Two-Factor Authentication (2FA)</h3>
        <p class="text-xs text-gray-500 mt-1">Secure your admin account with Google Authenticator or any TOTP-compatible app.</p>
    </div>
    <div class="p-6" id="twoFactorSection">
        <?php if ($twoFactorEnabled): ?>
            
            <div class="flex items-center gap-3 mb-5">
                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-700">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><path d="M20 6L9 17l-5-5"/></svg>
                    Enabled
                </span>
                <span class="text-sm text-gray-600">Two-factor authentication is active on your account.</span>
            </div>

            <div id="disableSection">
                <button type="button" onclick="show2FADisable()"
                        class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-red-600 bg-red-50 border border-red-200 rounded-lg hover:bg-red-100 transition-colors">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
                    Disable 2FA
                </button>
            </div>

            <div id="disableForm" class="hidden mt-4 p-4 bg-red-50 border border-red-200 rounded-lg">
                <p class="text-sm text-red-800 mb-3">Enter your current authenticator code to confirm disabling 2FA:</p>
                <div class="flex gap-3 items-end">
                    <div>
                        <input type="text" id="disableCode" maxlength="6" pattern="\d{6}" inputmode="numeric"
                               placeholder="000000"
                               class="w-36 px-3 py-2 border border-red-300 rounded-lg text-center text-lg font-mono tracking-widest focus:ring-2 focus:ring-red-500 focus:border-red-500 outline-none">
                    </div>
                    <button type="button" onclick="disable2FA()"
                            class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors">
                        Confirm
                    </button>
                    <button type="button" onclick="cancel2FADisable()"
                            class="px-4 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                        Cancel
                    </button>
                </div>
                <p id="disableError" class="mt-2 text-sm text-red-600 hidden"></p>
            </div>

        <?php else: ?>
            
            <div class="flex items-center gap-3 mb-5">
                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold bg-gray-100 text-gray-600">Disabled</span>
                <span class="text-sm text-gray-600">Add an extra layer of security to your admin account.</span>
            </div>

            <button type="button" id="setup2FABtn" onclick="setup2FA()"
                    class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-primary-600 rounded-lg hover:bg-primary-700 transition-colors">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                Enable 2FA
            </button>

            <div id="setupSection" class="hidden mt-5">
                <div class="p-5 bg-gray-50 border border-gray-200 rounded-lg">
                    <div class="flex flex-col sm:flex-row gap-6">
                        
                        <div class="flex-shrink-0">
                            <p class="text-xs font-medium text-gray-700 mb-2">1. Scan this QR code</p>
                            <div id="qrContainer" class="bg-white p-3 rounded-lg border border-gray-200 inline-block"></div>
                        </div>

                        
                        <div class="flex-1 min-w-0">
                            <p class="text-xs font-medium text-gray-700 mb-2">Or enter this key manually:</p>
                            <div class="flex items-center gap-2 mb-5">
                                <code id="secretKey" class="px-3 py-1.5 bg-white border border-gray-300 rounded text-sm font-mono text-gray-800 select-all"></code>
                                <button type="button" onclick="copySecret()" title="Copy"
                                        class="p-1.5 text-gray-400 hover:text-gray-600 transition-colors">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
                                </button>
                            </div>

                            <p class="text-xs font-medium text-gray-700 mb-2">2. Enter the 6-digit code from your app</p>
                            <div class="flex gap-3 items-end">
                                <input type="text" id="verifyCode" maxlength="6" pattern="\d{6}" inputmode="numeric"
                                       placeholder="000000"
                                       class="w-36 px-3 py-2 border border-gray-300 rounded-lg text-center text-lg font-mono tracking-widest focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none">
                                <button type="button" onclick="enable2FA()" id="enableBtn"
                                        class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-lg hover:bg-green-700 transition-colors">
                                    Verify & Enable
                                </button>
                            </div>
                            <p id="setupError" class="mt-2 text-sm text-red-600 hidden"></p>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script>
let _2faSecret = '';

function setup2FA() {
    var btn = document.getElementById('setup2FABtn');
    btn.disabled = true;
    btn.textContent = 'Loading...';

    fetch('/admin/settings/2fa-setup', { method: 'POST', headers: { 'X-CSRF-TOKEN': '<?= Router::csrfToken() ?>' } })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            _2faSecret = data.secret;
            document.getElementById('secretKey').textContent = data.secret;
            document.getElementById('setupSection').classList.remove('hidden');
            btn.classList.add('hidden');

            document.getElementById('qrContainer').innerHTML = '';
            new QRCode(document.getElementById('qrContainer'), {
                text: data.qrUri,
                width: 180,
                height: 180,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.M
            });

            setTimeout(function() {
                document.getElementById('verifyCode').focus();
            }, 100);
        })
        .catch(function() {
            btn.disabled = false;
            btn.textContent = 'Enable 2FA';
            alert('Failed to generate 2FA secret. Please try again.');
        });
}

function copySecret() {
    var text = document.getElementById('secretKey').textContent;
    navigator.clipboard.writeText(text).then(function() {
        var btn = event.currentTarget;
        btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 6L9 17l-5-5"/></svg>';
        setTimeout(function() {
            btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>';
        }, 2000);
    });
}

function enable2FA() {
    var code = document.getElementById('verifyCode').value.replace(/\D/g, '');
    if (code.length !== 6) {
        showError('setupError', 'Please enter a 6-digit code.');
        return;
    }

    var btn = document.getElementById('enableBtn');
    btn.disabled = true;
    btn.textContent = 'Verifying...';

    fetch('/admin/settings/2fa-enable', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': '<?= Router::csrfToken() ?>' },
        body: 'secret=' + encodeURIComponent(_2faSecret) + '&code=' + encodeURIComponent(code)
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.success) {
            location.reload();
        } else {
            showError('setupError', data.error || 'Invalid code.');
            btn.disabled = false;
            btn.textContent = 'Verify & Enable';
            document.getElementById('verifyCode').value = '';
            document.getElementById('verifyCode').focus();
        }
    })
    .catch(function() {
        btn.disabled = false;
        btn.textContent = 'Verify & Enable';
        showError('setupError', 'Request failed. Please try again.');
    });
}

function show2FADisable() {
    document.getElementById('disableForm').classList.remove('hidden');
    document.getElementById('disableSection').querySelector('button').classList.add('hidden');
    document.getElementById('disableCode').focus();
}

function cancel2FADisable() {
    document.getElementById('disableForm').classList.add('hidden');
    document.getElementById('disableSection').querySelector('button').classList.remove('hidden');
    document.getElementById('disableCode').value = '';
    hideError('disableError');
}

function disable2FA() {
    var code = document.getElementById('disableCode').value.replace(/\D/g, '');
    if (code.length !== 6) {
        showError('disableError', 'Please enter a 6-digit code.');
        return;
    }

    fetch('/admin/settings/2fa-disable', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': '<?= Router::csrfToken() ?>' },
        body: 'code=' + encodeURIComponent(code)
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.success) {
            location.reload();
        } else {
            showError('disableError', data.error || 'Invalid code.');
            document.getElementById('disableCode').value = '';
            document.getElementById('disableCode').focus();
        }
    })
    .catch(function() {
        showError('disableError', 'Request failed. Please try again.');
    });
}

function showError(id, msg) {
    var el = document.getElementById(id);
    el.textContent = msg;
    el.classList.remove('hidden');
}

function hideError(id) {
    document.getElementById(id).classList.add('hidden');
}

document.querySelectorAll('input[inputmode="numeric"]').forEach(function(el) {
    el.addEventListener('input', function() { this.value = this.value.replace(/\D/g, ''); });
});
</script>
