<script setup lang="ts">
import { Head, useForm, router } from '@inertiajs/vue3';
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { 
    Printer, Shield, RefreshCw, Download, Trash2, 
    CheckCircle2, XCircle, AlertTriangle, FileText, 
    Database, Activity, Server, AlertCircle, Key, Info
} from 'lucide-vue-next';
import { getPrintSettings, savePrintSettings, printHtmlViaQz } from '@/lib/printService';

interface Certificate {
    id: number;
    name: string;
    public_certificate: string;
    fingerprint: string;
    algorithm: string;
    created_at: string;
    expires_at: string | null;
    last_used_at: string | null;
}

interface LogEntry {
    id: number;
    user_name: string;
    ip_address: string;
    action: string;
    result: string;
    details: string | null;
    created_at: string;
}

interface Config {
    key_size: number;
    validity_days: number;
    signature_algorithm: string;
    dn: {
        country: string;
        state: string;
        locality: string;
        organization: string;
        organizational_unit: string;
        common_name: string;
        email: string;
    };
}

const props = defineProps<{
    certificate: Certificate | null;
    status: string; // active, expired, invalid, not_generated
    isOpenSslAvailable: boolean;
    recentLogs: LogEntry[];
    paginatedLogs: any;
    config: Config;
}>();

// State for Modal
const showGenerateModal = ref(false);
const showDeleteModal = ref(false);
const showLogsModal = ref(false);
const showWarningRegenerate = ref(false);

// State for QZ Tray integration
const qzLoaded = ref(false);
const qzInstance = ref<any>(null);
const isWsConnected = ref(false);
const printersList = ref<string[]>([]);
const selectedPrinter = ref('');
const connectionLog = ref<string[]>([]);
const testStatus = ref<'idle' | 'testing' | 'success' | 'failed'>('idle');
const isPrinting = ref(false);
const zoomScale = ref(100);

const saveZoomScale = () => {
    const settings = getPrintSettings();
    settings.zoomScale = zoomScale.value;
    savePrintSettings(settings);
};

// Toast state
const showToast = ref(false);
const toastMessage = ref('');
const toastType = ref<'success' | 'error'>('success');

const triggerToast = (msg: string, type: 'success' | 'error' = 'success') => {
    toastMessage.value = msg;
    toastType.value = type;
    showToast.value = true;
    setTimeout(() => {
        showToast.value = false;
    }, 5000);
};

// Form for Generation / Regeneration
const certForm = useForm({
    name: props.certificate?.name || 'CafePOS QZ Client',
    country: props.config.dn.country,
    state: props.config.dn.state,
    locality: props.config.dn.locality,
    organization: props.config.dn.organization,
    organizational_unit: props.config.dn.organizational_unit,
    common_name: props.config.dn.common_name,
    email: props.config.dn.email,
});

// Format dates
const formatDate = (dateStr: string | null) => {
    if (!dateStr) return 'Never';
    return new Date(dateStr).toLocaleString('id-ID', {
        dateStyle: 'medium',
        timeStyle: 'short'
    });
};

// Initialize QZ Tray parameters
const initializeQz = () => {
    if (!qzInstance.value || !props.certificate) return;

    // Load CSRF token
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

    // Set signature algorithm to match backend
    if (props.config?.signature_algorithm) {
        qzInstance.value.security.setSignatureAlgorithm(props.config.signature_algorithm.toUpperCase());
    }

    // Config QZ Certificate Promise
    qzInstance.value.security.setCertificatePromise((resolve: any) => {
        resolve(props.certificate?.public_certificate);
    });

    // Config QZ Signature Promise (signing on server)
    qzInstance.value.security.setSignaturePromise((toSign: string) => {
        return (resolve: any, reject: any) => {
            fetch(route('qz-tray.sign'), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken,
                    'Accept': 'application/json',
                },
                body: JSON.stringify({ payload: toSign })
            })
            .then(async (res) => {
                if (!res.ok) {
                    const errData = await res.json();
                    throw new Error(errData.message || 'Signature endpoint failed.');
                }
                return res.json();
            })
            .then((data) => {
                if (data.success) {
                    resolve(data.signature);
                } else {
                    reject(data.message || 'Signing failed');
                }
            })
            .catch((err) => {
                reject(err.message || err);
            });
        };
    });
};

// Toggle QZ Connection
const toggleQzConnection = async () => {
    if (!qzInstance.value) return;

    connectionLog.value = [];
    testStatus.value = 'testing';
    
    if (qzInstance.value.websocket.isActive()) {
        connectionLog.value.push("Disconnecting from WebSocket...");
        try {
            await qzInstance.value.websocket.disconnect();
            isWsConnected.value = false;
            printersList.value = [];
            connectionLog.value.push("WebSocket disconnected.");
            testStatus.value = 'idle';
        } catch (e: any) {
            connectionLog.value.push(`Disconnect error: ${e.message || e}`);
            testStatus.value = 'failed';
        }
        return;
    }

    connectionLog.value.push("Checking QZ Tray WebSocket...");
    try {
        await qzInstance.value.websocket.connect();
        isWsConnected.value = true;
        connectionLog.value.push("WebSocket connected to QZ Tray.");
        
        if (props.certificate) {
            connectionLog.value.push("Certificate loaded in frontend. Verifying signature API...");
            // Call any signed command to trigger verification
            const defaultPrinter = await qzInstance.value.printers.getDefault();
            connectionLog.value.push(`Signature valid. Default printer: ${defaultPrinter || 'None'}`);
        } else {
            connectionLog.value.push("Warning: No public certificate active. Client will prompt for security.");
        }
        
        await loadPrinters();
        testStatus.value = 'success';
    } catch (e: any) {
        connectionLog.value.push(`Connection failed: ${e.message || e}`);
        connectionLog.value.push("Please check if QZ Tray is installed and running.");
        testStatus.value = 'failed';
        isWsConnected.value = false;
    }
};

// Load Local Printers
const loadPrinters = async () => {
    if (!qzInstance.value || !qzInstance.value.websocket.isActive()) return;
    try {
        const list = await qzInstance.value.printers.find();
        printersList.value = list;
        if (list.length > 0) {
            selectedPrinter.value = list[0];
        }
    } catch (e) {
        console.error("Failed to load printers", e);
    }
};

// Print Test Receipt
const printTestReceipt = async () => {
    if (!selectedPrinter.value) return;
    
    isPrinting.value = true;
    try {
        // Default print test to 80% unless user specified a custom non-100 scale
        const zoom = (zoomScale.value && zoomScale.value !== 100) ? zoomScale.value : 80;
        const testHtml = `
            <div style="font-size: 11px; width: 280px; padding: 4px; color: #000; background: #fff; text-align: left;">
                <div style="font-weight: bold; font-size: 14px; margin-bottom: 2px;">CAFEPOS</div>
                <div style="font-size: 9px; text-transform: uppercase;">Enterprise Print System</div>
                <div style="margin: 6px 0;">================================</div>
                
                <div style="margin-bottom: 6px;">
                    <div style="display: flex; justify-content: space-between;">
                        <span>DATE:</span>
                        <span>${new Date().toLocaleString()}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between;">
                        <span>SESS:</span>
                        <span>MOCK-TEST-9920</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; font-weight: bold;">
                        <span>ZOOM SCALE:</span>
                        <span>${zoom}%</span>
                    </div>
                </div>

                <div style="margin-bottom: 6px;">
                    <div style="display: flex; justify-content: space-between; font-weight: bold;">
                        <span>ITEM</span>
                        <span>QTY &nbsp; PRICE</span>
                    </div>
                    <div style="margin: 2px 0;">--------------------------------</div>
                    <div style="display: flex; justify-content: space-between;">
                        <span>Printer Connection Test</span>
                        <span>1x &nbsp;&nbsp; $0.00</span>
                    </div>
                    <div style="display: flex; justify-content: space-between;">
                        <span>Signature Autopass</span>
                        <span>1x &nbsp;&nbsp; $0.00</span>
                    </div>
                </div>

                <div style="margin: 4px 0;">--------------------------------</div>
                <div style="display: flex; justify-content: space-between; font-weight: bold; font-size: 12px;">
                    <span>TOTAL PAID:</span>
                    <span>$0.00</span>
                </div>
                <div style="margin: 6px 0;">================================</div>
                
                <div style="font-size: 9px; font-weight: bold;">
                    STATUS: SIGNED SECURELY
                </div>
                <div style="font-size: 8px; color: #555; margin-top: 4px; word-break: break-all;">
                    FPR: ${props.certificate?.fingerprint || 'N/A'}
                </div>
            </div>
        `;

        await printHtmlViaQz(selectedPrinter.value, testHtml, zoom);
        triggerToast(`Test receipt sent (${zoom}% scale) successfully!`, "success");
    } catch (e: any) {
        triggerToast(`Print failed: ${e.message || e}`, "error");
    } finally {
        isPrinting.value = false;
    }
};

// Generate action
const submitGenerate = () => {
    const isRegen = !!props.certificate;
    const url = isRegen ? route('settings.qz-tray.regenerate') : route('settings.qz-tray.generate');
    
    certForm.post(url, {
        onSuccess: () => {
            showGenerateModal.value = false;
            showWarningRegenerate.value = false;
            initializeQz();
            triggerToast(isRegen ? "Certificate regenerated successfully." : "Certificate generated successfully.", "success");
        },
        onError: (errors) => {
            const firstErr = Object.values(errors)[0] as string;
            triggerToast(firstErr || "Failed to generate certificate", "error");
        }
    });
};

// Delete action
const submitDelete = () => {
    router.delete(route('settings.qz-tray.destroy'), {
        onSuccess: () => {
            showDeleteModal.value = false;
            printersList.value = [];
            isWsConnected.value = false;
            triggerToast("QZ Tray certificate deleted successfully.", "success");
        },
        onError: () => {
            triggerToast("Failed to delete certificate.", "error");
        }
    });
};

onMounted(async () => {
    // Load saved zoom scale from localStorage
    zoomScale.value = getPrintSettings().zoomScale ?? 100;

    if (typeof window !== 'undefined') {
        try {
            const module = await import('qz-tray');
            qzInstance.value = module.default;
            qzLoaded.value = true;
            initializeQz();

            // Auto-detect running QZ Tray
            if (qzInstance.value.websocket.isActive()) {
                isWsConnected.value = true;
                await loadPrinters();
            }
        } catch (e) {
            console.error("Failed to load qz-tray", e);
        }
    }
});

onBeforeUnmount(async () => {
    if (qzInstance.value && qzInstance.value.websocket.isActive()) {
        try {
            await qzInstance.value.websocket.disconnect();
        } catch (e) {
            // silent close
        }
    }
});
</script>

<template>
    <AdminLayout>
        <Head title="QZ Tray Settings" />

        <!-- Toast Notifications -->
        <Transition
            enter-active-class="transform ease-out duration-300 transition"
            enter-from-class="translate-y-2 opacity-0 sm:translate-y-0 sm:translate-x-2"
            enter-to-class="translate-y-0 opacity-100 sm:translate-x-0"
            leave-active-class="transition ease-in duration-200"
            leave-from-class="opacity-100"
            leave-to-class="opacity-0"
        >
            <div 
                v-if="showToast" 
                :class="[
                    'fixed top-4 right-4 z-50 max-w-md w-full border rounded-xl shadow-xl p-4 flex items-start gap-3',
                    toastType === 'success' 
                        ? 'bg-white dark:bg-slate-900 border-emerald-200 dark:border-emerald-950/30' 
                        : 'bg-white dark:bg-slate-900 border-rose-200 dark:border-rose-950/30'
                ]"
            >
                <CheckCircle2 v-if="toastType === 'success'" class="h-5 w-5 text-emerald-600 dark:text-emerald-400 flex-shrink-0 mt-0.5" />
                <XCircle v-else class="h-5 w-5 text-rose-600 dark:text-rose-400 flex-shrink-0 mt-0.5" />
                <div class="flex-1 min-w-0">
                    <p class="text-sm font-semibold text-slate-950 dark:text-slate-50">
                        {{ toastType === 'success' ? 'Success' : 'Error' }}
                    </p>
                    <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5">{{ toastMessage }}</p>
                </div>
            </div>
        </Transition>

        <div class="w-full space-y-6">
            <!-- Header -->
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div>
                    <h1 class="text-2xl font-bold tracking-tight text-slate-900 dark:text-slate-100 flex items-center gap-2">
                        <Printer class="h-6 w-6 text-blue-600" />
                        QZ Tray Integration
                    </h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Configure self-signed certificates to authorize silent printing operations from your POS terminals.
                    </p>
                </div>
                <div class="flex gap-2">
                    <button
                        @click="showLogsModal = true"
                        class="inline-flex items-center gap-1.5 px-3 py-2 bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 text-slate-700 dark:text-slate-200 rounded-lg text-sm font-semibold transition-colors cursor-pointer"
                    >
                        <Activity class="h-4 w-4" />
                        <span>View All Logs</span>
                    </button>
                </div>
            </div>

            <!-- OpenSSL extension guard -->
            <div v-if="!isOpenSslAvailable" class="bg-rose-50 dark:bg-rose-950/20 border border-rose-200 dark:border-rose-900/40 rounded-xl p-5 flex items-start gap-4">
                <AlertTriangle class="h-6 w-6 text-rose-600 dark:text-rose-400 flex-shrink-0 mt-0.5" />
                <div>
                    <h3 class="text-sm font-bold text-rose-800 dark:text-rose-300">OpenSSL PHP Extension Missing</h3>
                    <p class="text-xs text-rose-700 dark:text-rose-400 mt-1 leading-relaxed">
                        The `openssl` extension is not loaded on this PHP server. Certificate generation requires OpenSSL. Please enable it in your server's `php.ini` file.
                    </p>
                </div>
            </div>

            <!-- Grid Content -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Column 1 & 2: Certificate Config -->
                <div class="lg:col-span-2 space-y-6">
                    <!-- Certificate Info Card -->
                    <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm space-y-6">
                        <div class="flex items-center justify-between border-b border-slate-100 dark:border-slate-900 pb-4">
                            <h2 class="text-base font-semibold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                                <Shield class="h-5 w-5 text-blue-600" />
                                Certificate Details
                            </h2>
                            <span 
                                :class="[
                                    'inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold uppercase tracking-wide',
                                    status === 'active' ? 'bg-emerald-50 dark:bg-emerald-950/30 text-emerald-700 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-900/30' : '',
                                    status === 'expired' ? 'bg-rose-50 dark:bg-rose-950/30 text-rose-700 dark:text-rose-400 border border-rose-200 dark:border-rose-900/30' : '',
                                    status === 'invalid' ? 'bg-amber-50 dark:bg-amber-950/30 text-amber-700 dark:text-amber-400 border border-amber-200 dark:border-amber-900/30' : '',
                                    status === 'not_generated' ? 'bg-slate-100 dark:bg-slate-900 text-slate-500 dark:text-slate-400 border border-slate-200 dark:border-slate-850' : '',
                                ]"
                            >
                                <span class="h-1.5 w-1.5 rounded-full bg-current"></span>
                                {{ status.replace('_', ' ') }}
                            </span>
                        </div>

                        <!-- Data Fields -->
                        <div v-if="certificate" class="grid grid-cols-1 md:grid-cols-2 gap-y-4 gap-x-6 text-sm">
                            <div class="space-y-1">
                                <span class="text-xs text-slate-400 dark:text-slate-500 block uppercase tracking-wide font-medium">Certificate Name</span>
                                <span class="font-semibold text-slate-800 dark:text-slate-200">{{ certificate.name }}</span>
                            </div>
                            <div class="space-y-1">
                                <span class="text-xs text-slate-400 dark:text-slate-500 block uppercase tracking-wide font-medium">Key Pair Type / Algorithm</span>
                                <span class="font-semibold text-slate-800 dark:text-slate-200">{{ certificate.algorithm }}</span>
                            </div>
                            <div class="space-y-1 md:col-span-2">
                                <span class="text-xs text-slate-400 dark:text-slate-500 block uppercase tracking-wide font-medium font-mono">Fingerprint (SHA-256)</span>
                                <span class="font-mono text-xs font-semibold break-all bg-slate-50 dark:bg-slate-900/50 p-2 rounded border border-slate-100 dark:border-slate-900 block text-slate-800 dark:text-slate-200">
                                    {{ certificate.fingerprint }}
                                </span>
                            </div>
                            <div class="space-y-1">
                                <span class="text-xs text-slate-400 dark:text-slate-500 block uppercase tracking-wide font-medium">Created Date</span>
                                <span class="font-semibold text-slate-800 dark:text-slate-200">{{ formatDate(certificate.created_at) }}</span>
                            </div>
                            <div class="space-y-1">
                                <span class="text-xs text-slate-400 dark:text-slate-500 block uppercase tracking-wide font-medium">Expiration Date</span>
                                <span class="font-semibold text-slate-800 dark:text-slate-200">{{ formatDate(certificate.expires_at) }}</span>
                            </div>
                            <div class="space-y-1">
                                <span class="text-xs text-slate-400 dark:text-slate-500 block uppercase tracking-wide font-medium">Last Used</span>
                                <span class="font-semibold text-slate-800 dark:text-slate-200">{{ formatDate(certificate.last_used_at) }}</span>
                            </div>
                        </div>

                        <div v-else class="text-center py-10 bg-slate-50/50 dark:bg-slate-900/20 rounded-xl border border-dashed border-slate-200 dark:border-slate-800">
                            <Key class="h-10 w-10 text-slate-400 mx-auto stroke-1" />
                            <h3 class="text-sm font-semibold text-slate-800 dark:text-slate-300 mt-3">No Certificate Generated</h3>
                            <p class="text-xs text-slate-400 max-w-sm mx-auto mt-1 leading-relaxed">
                                Generate an application-wide self-signed certificate to begin automatic handshake validation with local QZ Tray clients.
                            </p>
                        </div>
                    </div>

                    <!-- Certificate Actions Card -->
                    <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm space-y-6">
                        <h2 class="text-base font-semibold text-slate-900 dark:text-slate-100 border-b border-slate-100 dark:border-slate-900 pb-4">
                            Certificate Actions
                        </h2>

                        <div class="flex flex-wrap gap-4">
                            <!-- Generate Button -->
                            <button
                                v-if="!certificate"
                                :disabled="!isOpenSslAvailable"
                                @click="showGenerateModal = true"
                                class="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-500 disabled:opacity-50 text-white rounded-lg text-sm font-semibold shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 transition-all cursor-pointer"
                            >
                                <Key class="h-4 w-4" />
                                <span>Generate Certificate</span>
                            </button>

                            <!-- Regenerate Button -->
                            <button
                                v-if="certificate"
                                @click="showWarningRegenerate = true"
                                class="inline-flex items-center gap-2 px-4 py-2 bg-amber-600 hover:bg-amber-500 text-white rounded-lg text-sm font-semibold shadow-sm focus:outline-none focus:ring-2 focus:ring-amber-500/20 transition-all cursor-pointer"
                            >
                                <RefreshCw class="h-4 w-4" />
                                <span>Regenerate Certificate</span>
                            </button>

                            <!-- Download Public Certificate -->
                            <a
                                v-if="certificate"
                                :href="route('settings.qz-tray.download')"
                                class="inline-flex items-center gap-2 px-4 py-2 bg-slate-100 dark:bg-slate-850 hover:bg-slate-200 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-200 rounded-lg text-sm font-semibold transition-all cursor-pointer"
                            >
                                <Download class="h-4 w-4" />
                                <span>Download Public Cert</span>
                            </a>

                            <!-- Delete Certificate -->
                            <button
                                v-if="certificate"
                                @click="showDeleteModal = true"
                                class="inline-flex items-center gap-2 px-4 py-2 bg-rose-50 dark:bg-rose-950/20 hover:bg-rose-100 dark:hover:bg-rose-950/40 text-rose-600 dark:text-rose-400 rounded-lg text-sm font-semibold border border-rose-200/50 dark:border-rose-900/30 transition-all cursor-pointer"
                            >
                                <Trash2 class="h-4 w-4" />
                                <span>Delete Certificate</span>
                            </button>
                        </div>
                    </div>

                    <!-- Setup Guide Card -->
                    <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm space-y-4">
                        <h2 class="text-base font-semibold text-slate-900 dark:text-slate-100 border-b border-slate-100 dark:border-slate-900 pb-4 flex items-center gap-2">
                            <Info class="h-5 w-5 text-blue-600" />
                            Panduan Setup & Sertifikat QZ Tray (Silent Printing)
                        </h2>
                        
                        <div class="text-xs text-slate-600 dark:text-slate-400 space-y-4 leading-relaxed font-medium">
                            <p>
                                Agar sistem dapat melakukan pencetakan struk secara otomatis tanpa memunculkan jendela dialog konfirmasi keamanan (silent printing), ikuti langkah-langkah setup berikut:
                            </p>
                            
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div class="border border-slate-100 dark:border-slate-850 p-4 rounded-xl bg-slate-50/50 dark:bg-slate-900/20 space-y-2 flex flex-col justify-between">
                                    <div>
                                        <span class="h-6 w-6 rounded-full bg-blue-600/10 text-blue-650 dark:text-blue-400 flex items-center justify-center text-xs font-bold mb-2">1</span>
                                        <h4 class="font-bold text-slate-850 dark:text-slate-200 text-xs">Generate Sertifikat</h4>
                                        <p class="text-[11px] text-slate-505 dark:text-slate-400 leading-normal mt-1">
                                            Klik tombol <strong>"Generate Certificate"</strong> di atas. Sistem akan membuat pasangan kunci privat & publik OpenSSL baru secara otomatis di database backend.
                                        </p>
                                    </div>
                                </div>
                                
                                <div class="border border-slate-100 dark:border-slate-850 p-4 rounded-xl bg-slate-50/50 dark:bg-slate-900/20 space-y-2 flex flex-col justify-between">
                                    <div>
                                        <span class="h-6 w-6 rounded-full bg-blue-600/10 text-blue-650 dark:text-blue-400 flex items-center justify-center text-xs font-bold mb-2">2</span>
                                        <h4 class="font-bold text-slate-850 dark:text-slate-200 text-xs">Unduh Public Cert</h4>
                                        <p class="text-[11px] text-slate-505 dark:text-slate-400 leading-normal mt-1">
                                            Klik tombol <strong>"Download Public Cert"</strong> untuk mengunduh file sertifikat publik <code>digital-certificate.txt</code> aplikasi Anda ke komputer.
                                        </p>
                                    </div>
                                </div>
                                
                                <div class="border border-slate-100 dark:border-slate-850 p-4 rounded-xl bg-slate-50/50 dark:bg-slate-900/20 space-y-2 flex flex-col justify-between">
                                    <div>
                                        <span class="h-6 w-6 rounded-full bg-blue-600/10 text-blue-650 dark:text-blue-400 flex items-center justify-center text-xs font-bold mb-2">3</span>
                                        <h4 class="font-bold text-slate-850 dark:text-slate-200 text-xs">Salin & Trust Certificate</h4>
                                        <p class="text-[11px] text-slate-505 dark:text-slate-400 leading-normal mt-1">
                                            Pindahkan atau salin file <code>digital-certificate.txt</code> tersebut ke dalam folder instalasi QZ Tray di komputer kasir Anda agar terverifikasi otomatis.
                                        </p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800/80 p-4 rounded-xl font-mono text-[11px] text-slate-700 dark:text-slate-350 space-y-2">
                                <div class="font-bold text-slate-850 dark:text-slate-200 uppercase tracking-wider text-[10px]">Lokasi Folder Instalasi QZ Tray:</div>
                                <ul class="list-disc list-inside space-y-1">
                                    <li><strong>Windows:</strong> <code>C:\Program Files\QZ Tray\digital-certificate.txt</code></li>
                                    <li><strong>macOS:</strong> <code>/Applications/QZ Tray.app/Contents/Resources/digital-certificate.txt</code></li>
                                    <li><strong>Linux:</strong> <code>/opt/qz-tray/digital-certificate.txt</code></li>
                                </ul>
                                <div class="text-[10px] text-amber-600 dark:text-amber-400 mt-2 font-sans font-semibold">
                                    *PENTING: Tutup (Close) QZ Tray dari system tray dan buka kembali aplikasinya setelah Anda menaruh file sertifikat agar QZ me-load sertifikat baru.
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Column 3: WebSocket Connection Status & Testing -->
                <div class="space-y-6">
                    <!-- WebSocket Connection Status Card -->
                    <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm space-y-6">
                        <h2 class="text-base font-semibold text-slate-900 dark:text-slate-100 border-b border-slate-100 dark:border-slate-900 pb-4">
                            Connection Testing
                        </h2>

                        <!-- Ws connection indicator -->
                        <div class="flex items-center gap-3">
                            <div 
                                :class="[
                                    'h-3 w-3 rounded-full',
                                    isWsConnected ? 'bg-emerald-500 animate-pulse shadow shadow-emerald-500' : 'bg-rose-500'
                                ]"
                            />
                            <div>
                                <span class="text-sm font-semibold block text-slate-800 dark:text-slate-200">
                                    {{ isWsConnected ? 'Connected to QZ Tray' : 'Disconnected' }}
                                </span>
                                <span class="text-xs text-slate-400 dark:text-slate-500 block">
                                    {{ isWsConnected ? 'Local WebSocket active' : 'Check if QZ Tray app is running locally' }}
                                </span>
                            </div>
                        </div>

                        <!-- Connect Action -->
                        <button
                            @click="toggleQzConnection"
                            :class="[
                                'w-full inline-flex items-center justify-center gap-2 px-4 py-2 text-sm font-semibold rounded-lg shadow-sm transition-all cursor-pointer',
                                isWsConnected 
                                    ? 'bg-slate-100 dark:bg-slate-855 hover:bg-slate-200 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-200' 
                                    : 'bg-blue-600 hover:bg-blue-500 text-white focus:ring-2 focus:ring-blue-500/20'
                            ]"
                        >
                            <Server class="h-4 w-4" />
                            <span>{{ isWsConnected ? 'Disconnect' : 'Connect & Test HANDSHAKE' }}</span>
                        </button>

                        <!-- Log console -->
                        <div v-if="connectionLog.length > 0" class="space-y-2">
                            <span class="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider block">Diagnostics</span>
                            <div class="h-40 overflow-y-auto bg-slate-950 text-[11px] font-mono p-3 rounded-lg border border-slate-900 text-slate-300 leading-normal space-y-1">
                                <div v-for="(log, idx) in connectionLog" :key="idx" class="whitespace-pre-wrap">
                                    {{ log }}
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Printer selection and test print -->
                    <div 
                        v-if="isWsConnected" 
                        class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm space-y-6"
                    >
                        <h2 class="text-base font-semibold text-slate-900 dark:text-slate-100 border-b border-slate-100 dark:border-slate-900 pb-4">
                            Local Printers
                        </h2>

                        <div class="space-y-4">
                            <div class="space-y-2">
                                <label for="printers" class="text-xs font-medium text-slate-500 uppercase block">Available Printers</label>
                                <select 
                                    id="printers" 
                                    v-model="selectedPrinter"
                                    class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-800 bg-transparent text-sm text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all dark:bg-slate-950"
                                >
                                    <option v-for="printer in printersList" :key="printer" :value="printer">{{ printer }}</option>
                                    <option v-if="printersList.length === 0" value="">No Printers Detected</option>
                                </select>
                            </div>

                            <!-- Zoom Scale Setting -->
                            <div class="space-y-2 p-3 bg-slate-50 dark:bg-slate-900/40 rounded-lg border border-slate-200 dark:border-slate-800">
                                <label class="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase block">Zoom Scale Cetak (%)</label>
                                <div class="flex items-center gap-3">
                                    <input
                                        v-model.number="zoomScale"
                                        type="range"
                                        min="40"
                                        max="120"
                                        step="5"
                                        @change="saveZoomScale"
                                        class="flex-1 h-1.5 accent-blue-600 cursor-pointer"
                                    />
                                    <span class="text-sm font-bold text-blue-600 w-12 text-right">{{ zoomScale }}%</span>
                                </div>
                                <p class="text-[10px] text-slate-400 dark:text-slate-500">Default: 100%. Turunkan jika hasil cetak terpotong di sisi kanan. Perubahan disimpan otomatis.</p>
                            </div>

                            <button
                                @click="printTestReceipt"
                                :disabled="!selectedPrinter || isPrinting"
                                class="w-full inline-flex items-center justify-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white rounded-lg text-sm font-semibold shadow-sm focus:outline-none focus:ring-2 focus:ring-emerald-500/20 transition-all cursor-pointer"
                            >
                                <Printer class="h-4 w-4" />
                                <span>{{ isPrinting ? 'Printing Receipt...' : 'Print Test Receipt' }}</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Logs Card -->
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm space-y-4">
                <h2 class="text-base font-semibold text-slate-900 dark:text-slate-100 border-b border-slate-100 dark:border-slate-900 pb-4">
                    Recent Logs
                </h2>

                <div class="overflow-x-auto">
                    <table class="w-full border-collapse text-left text-sm text-slate-500 dark:text-slate-400">
                        <thead class="bg-slate-50/50 dark:bg-slate-900/50 text-xs font-semibold text-slate-700 dark:text-slate-300 uppercase">
                            <tr>
                                <th class="px-4 py-3">Timestamp</th>
                                <th class="px-4 py-3">User</th>
                                <th class="px-4 py-3">IP Address</th>
                                <th class="px-4 py-3">Action</th>
                                <th class="px-4 py-3">Result</th>
                                <th class="px-4 py-3">Details</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-900">
                            <tr v-for="log in recentLogs" :key="log.id" class="hover:bg-slate-50/30 dark:hover:bg-slate-900/20">
                                <td class="px-4 py-3 whitespace-nowrap font-medium text-slate-900 dark:text-slate-100">
                                    {{ formatDate(log.created_at) }}
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap">{{ log.user_name }}</td>
                                <td class="px-4 py-3 whitespace-nowrap font-mono text-xs">{{ log.ip_address }}</td>
                                <td class="px-4 py-3 whitespace-nowrap">{{ log.action }}</td>
                                <td class="px-4 py-3 whitespace-nowrap">
                                    <span 
                                        :class="[
                                            'inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium',
                                            log.result === 'Success' ? 'bg-emerald-50 dark:bg-emerald-950/20 text-emerald-700 dark:text-emerald-400' : 'bg-rose-50 dark:bg-rose-950/20 text-rose-700 dark:text-rose-400'
                                        ]"
                                    >
                                        {{ log.result }}
                                    </span>
                                </td>
                                <td class="px-4 py-3 truncate max-w-xs" :title="log.details || ''">
                                    {{ log.details }}
                                </td>
                            </tr>
                            <tr v-if="recentLogs.length === 0">
                                <td colspan="6" class="px-4 py-8 text-center text-slate-400">
                                    No logged events found.
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- GENERATE CERTIFICATE MODAL -->
        <div v-if="showGenerateModal" class="fixed inset-0 z-50 flex items-center justify-center p-4">
            <div class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm" @click="showGenerateModal = false"></div>
            
            <div class="relative bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl max-w-lg w-full p-6 shadow-2xl space-y-6 overflow-y-auto max-h-[90vh]">
                <div>
                    <h3 class="text-lg font-bold text-slate-900 dark:text-slate-100">Generate QZ Tray Certificate</h3>
                    <p class="text-xs text-slate-400 mt-1">
                        Generate an X509 digital signature certificate mapping with local clients.
                    </p>
                </div>

                <form @submit.prevent="submitGenerate" class="space-y-4">
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div class="space-y-1.5 sm:col-span-2">
                            <label for="name" class="text-xs font-semibold text-slate-500 uppercase">Certificate Name</label>
                            <input 
                                type="text" 
                                id="name" 
                                v-model="certForm.name"
                                class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-800 bg-transparent text-sm text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                                required
                            />
                        </div>
                        <div class="space-y-1.5">
                            <label for="country" class="text-xs font-semibold text-slate-500 uppercase">Country (2 letters)</label>
                            <input 
                                type="text" 
                                id="country" 
                                v-model="certForm.country" 
                                maxlength="2"
                                class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-800 bg-transparent text-sm text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all uppercase"
                                required
                            />
                        </div>
                        <div class="space-y-1.5">
                            <label for="state" class="text-xs font-semibold text-slate-500 uppercase">State/Province</label>
                            <input 
                                type="text" 
                                id="state" 
                                v-model="certForm.state"
                                class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-800 bg-transparent text-sm text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                                required
                            />
                        </div>
                        <div class="space-y-1.5">
                            <label for="locality" class="text-xs font-semibold text-slate-500 uppercase">Locality/City</label>
                            <input 
                                type="text" 
                                id="locality" 
                                v-model="certForm.locality"
                                class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-800 bg-transparent text-sm text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                                required
                            />
                        </div>
                        <div class="space-y-1.5">
                            <label for="organization" class="text-xs font-semibold text-slate-500 uppercase">Organization</label>
                            <input 
                                type="text" 
                                id="organization" 
                                v-model="certForm.organization"
                                class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-800 bg-transparent text-sm text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                                required
                            />
                        </div>
                        <div class="space-y-1.5">
                            <label for="ou" class="text-xs font-semibold text-slate-500 uppercase">Organizational Unit</label>
                            <input 
                                type="text" 
                                id="ou" 
                                v-model="certForm.organizational_unit"
                                class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-800 bg-transparent text-sm text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                                required
                            />
                        </div>
                        <div class="space-y-1.5">
                            <label for="cn" class="text-xs font-semibold text-slate-500 uppercase">Common Name</label>
                            <input 
                                type="text" 
                                id="cn" 
                                v-model="certForm.common_name"
                                class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-800 bg-transparent text-sm text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                                required
                            />
                        </div>
                        <div class="space-y-1.5 sm:col-span-2">
                            <label for="email" class="text-xs font-semibold text-slate-500 uppercase">Email Address</label>
                            <input 
                                type="email" 
                                id="email" 
                                v-model="certForm.email"
                                class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-800 bg-transparent text-sm text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                                required
                            />
                        </div>
                    </div>

                    <div class="flex items-center justify-end gap-3 border-t border-slate-100 dark:border-slate-900 pt-4">
                        <button 
                            type="button" 
                            @click="showGenerateModal = false"
                            class="px-4 py-2 border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-sm font-semibold transition-colors cursor-pointer text-slate-700 dark:text-slate-350"
                        >
                            Cancel
                        </button>
                        <button 
                            type="submit" 
                            :disabled="certForm.processing"
                            class="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm font-semibold shadow-sm transition-colors cursor-pointer disabled:opacity-50"
                        >
                            <span>{{ certForm.processing ? 'Generating...' : 'Generate' }}</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- REGENERATE WARNING MODAL -->
        <div v-if="showWarningRegenerate" class="fixed inset-0 z-50 flex items-center justify-center p-4">
            <div class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm" @click="showWarningRegenerate = false"></div>
            
            <div class="relative bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl max-w-md w-full p-6 shadow-2xl space-y-6">
                <div class="flex items-start gap-4">
                    <div class="h-10 w-10 bg-amber-50 dark:bg-amber-950/30 rounded-lg flex items-center justify-center border border-amber-200/50 dark:border-amber-900/30 flex-shrink-0 text-amber-600 dark:text-amber-400">
                        <AlertTriangle class="h-5 w-5" />
                    </div>
                    <div>
                        <h3 class="text-base font-bold text-slate-900 dark:text-slate-100">Regenerate Signing Certificate?</h3>
                        <p class="text-xs text-slate-500 dark:text-slate-400 mt-2 leading-relaxed">
                            Regenerating the certificate will permanently delete the current keypair.
                        </p>
                        <div class="bg-amber-50/50 dark:bg-amber-950/10 border border-amber-200/40 dark:border-amber-900/25 p-3 rounded-lg text-[11px] text-amber-800 dark:text-amber-400 mt-3 leading-relaxed">
                            <strong>WARNING:</strong> This will invalidate all previous signatures instantly. You will need to download the new public certificate and configure your local QZ Tray clients with it.
                        </div>
                    </div>
                </div>

                <div class="flex items-center justify-end gap-3">
                    <button 
                        @click="showWarningRegenerate = false"
                        class="px-4 py-2 border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-sm font-semibold transition-colors cursor-pointer text-slate-700 dark:text-slate-350"
                    >
                        Cancel
                    </button>
                    <button 
                        @click="showGenerateModal = true; showWarningRegenerate = false"
                        class="px-4 py-2 bg-amber-600 hover:bg-amber-500 text-white rounded-lg text-sm font-semibold transition-colors cursor-pointer shadow-sm"
                    >
                        Proceed to Regenerate
                    </button>
                </div>
            </div>
        </div>

        <!-- DELETE CERTIFICATE MODAL -->
        <div v-if="showDeleteModal" class="fixed inset-0 z-50 flex items-center justify-center p-4">
            <div class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm" @click="showDeleteModal = false"></div>
            
            <div class="relative bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl max-w-md w-full p-6 shadow-2xl space-y-6">
                <div class="flex items-start gap-4">
                    <div class="h-10 w-10 bg-rose-50 dark:bg-rose-950/30 rounded-lg flex items-center justify-center border border-rose-200/50 dark:border-rose-900/30 flex-shrink-0 text-rose-600 dark:text-rose-400">
                        <Trash2 class="h-5 w-5" />
                    </div>
                    <div>
                        <h3 class="text-base font-bold text-slate-900 dark:text-slate-100">Delete Signing Certificate?</h3>
                        <p class="text-xs text-slate-500 dark:text-slate-400 mt-2 leading-relaxed font-medium">
                            Are you absolutely sure you want to delete the QZ Tray certificate?
                        </p>
                        <p class="text-xs text-slate-400 dark:text-slate-500 mt-1 leading-relaxed">
                            This will remove the private key and public certificate record. Silent POS printing handshakes will fail until a new certificate is generated.
                        </p>
                    </div>
                </div>

                <div class="flex items-center justify-end gap-3">
                    <button 
                        @click="showDeleteModal = false"
                        class="px-4 py-2 border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-sm font-semibold transition-colors cursor-pointer text-slate-700 dark:text-slate-350"
                    >
                        Cancel
                    </button>
                    <button 
                        @click="submitDelete"
                        class="px-4 py-2 bg-rose-600 hover:bg-rose-500 text-white rounded-lg text-sm font-semibold transition-colors cursor-pointer shadow-sm"
                    >
                        Yes, Delete Certificate
                    </button>
                </div>
            </div>
        </div>

        <!-- FULL AUDIT LOGS MODAL -->
        <div v-if="showLogsModal" class="fixed inset-0 z-50 flex items-center justify-center p-4">
            <div class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm" @click="showLogsModal = false"></div>
            
            <div class="relative bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl max-w-4xl w-full p-6 shadow-2xl space-y-6 overflow-y-auto max-h-[85vh]">
                <div class="flex items-center justify-between border-b border-slate-100 dark:border-slate-900 pb-3">
                    <h3 class="text-lg font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                        <Database class="h-5 w-5 text-blue-600" />
                        QZ Tray Audit Logs
                    </h3>
                    <button 
                        @click="showLogsModal = false"
                        class="text-xs font-semibold text-slate-400 hover:text-slate-600 dark:hover:text-slate-200"
                    >
                        Close
                    </button>
                </div>

                <div class="overflow-x-auto border border-slate-100 dark:border-slate-900 rounded-lg">
                    <table class="w-full text-left text-sm text-slate-500 dark:text-slate-400">
                        <thead class="bg-slate-50/50 dark:bg-slate-900/50 text-xs font-semibold text-slate-700 dark:text-slate-300 uppercase">
                            <tr>
                                <th class="px-4 py-3">Timestamp</th>
                                <th class="px-4 py-3">User</th>
                                <th class="px-4 py-3">IP Address</th>
                                <th class="px-4 py-3">Action</th>
                                <th class="px-4 py-3">Result</th>
                                <th class="px-4 py-3">Details</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-900">
                            <tr v-for="log in paginatedLogs.data" :key="log.id" class="hover:bg-slate-50/30 dark:hover:bg-slate-900/20">
                                <td class="px-4 py-3 whitespace-nowrap font-medium text-slate-900 dark:text-slate-100">
                                    {{ formatDate(log.created_at) }}
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap">{{ log.user_name || 'System' }}</td>
                                <td class="px-4 py-3 whitespace-nowrap font-mono text-xs">{{ log.ip_address }}</td>
                                <td class="px-4 py-3 whitespace-nowrap">{{ log.action }}</td>
                                <td class="px-4 py-3 whitespace-nowrap">
                                    <span 
                                        :class="[
                                            'inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium',
                                            log.result === 'Success' ? 'bg-emerald-50 dark:bg-emerald-950/20 text-emerald-700 dark:text-emerald-400' : 'bg-rose-50 dark:bg-rose-950/20 text-rose-700 dark:text-rose-400'
                                        ]"
                                    >
                                        {{ log.result }}
                                    </span>
                                </td>
                                <td class="px-4 py-3 truncate max-w-xs" :title="log.details || ''">
                                    {{ log.details }}
                                </td>
                            </tr>
                            <tr v-if="paginatedLogs.data?.length === 0">
                                <td colspan="6" class="px-4 py-8 text-center text-slate-400">
                                    No logs found.
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Simple Modal Pagination -->
                <div class="flex items-center justify-between border-t border-slate-100 dark:border-slate-900 pt-4">
                    <span class="text-xs text-slate-400">
                        Showing {{ paginatedLogs.from || 0 }} to {{ paginatedLogs.to || 0 }} of {{ paginatedLogs.total || 0 }} logs
                    </span>
                    <div class="flex gap-2">
                        <button 
                            :disabled="!paginatedLogs.prev_page_url"
                            @click="router.visit(paginatedLogs.prev_page_url, { only: ['paginatedLogs'], preserveState: true })"
                            class="px-3 py-1 text-xs border border-slate-200 dark:border-slate-800 disabled:opacity-40 rounded cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-900 font-semibold"
                        >
                            Previous
                        </button>
                        <button 
                            :disabled="!paginatedLogs.next_page_url"
                            @click="router.visit(paginatedLogs.next_page_url, { only: ['paginatedLogs'], preserveState: true })"
                            class="px-3 py-1 text-xs border border-slate-200 dark:border-slate-800 disabled:opacity-40 rounded cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-900 font-semibold"
                        >
                            Next
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
