<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Search, Receipt, Store, User, Calendar, Eye, AlertTriangle, RefreshCw, X, Printer, Trash2, FileText, Settings, Check } from 'lucide-vue-next';

interface TransactionItem {
    id: number;
    qty: number;
    variant: string | null;
    price: string | number;
    subtotal: string | number;
    product: {
        id: number;
        name: string;
    };
}

interface TransactionData {
    id: number;
    transaction_number: string;
    outlet_id: number;
    user_id: number;
    total_amount: string | number;
    tax_amount: string | number;
    service_charge_amount: string | number;
    payment_method: string;
    status: 'success' | 'cancelled' | 'pending';
    order_type: 'dine_in' | 'take_away' | 'delivery';
    courier_id: number | null;
    delivery_status: string | null;
    created_at: string;
    outlet: {
        id: number;
        name: string;
    };
    user: {
        id: number;
        name: string;
    };
    courier?: {
        id: number;
        name: string;
    } | null;
    table?: {
        id: number;
        number: string;
    } | null;
    customer?: {
        id: number;
        name: string;
    } | null;
    items: TransactionItem[];
}

interface PaginatedTransactions {
    data: TransactionData[];
    current_page: number;
    last_page: number;
    prev_page_url: string | null;
    next_page_url: string | null;
    total: number;
    links: { url: string | null; label: string; active: boolean }[];
}

interface Outlet {
    id: number;
    name: string;
}

const props = defineProps<{
    transactions: PaginatedTransactions;
    outlets: Outlet[];
    isCashier: boolean;
    filters: {
        search?: string;
        outlet_id?: string;
        date?: string;
    };
}>();

const search = ref(props.filters.search || '');
const outletFilter = ref(props.filters.outlet_id || '');
const dateFilter = ref(props.filters.date || '');

// Debounce filtering
let timeoutId: ReturnType<typeof setTimeout> | null = null;
const applyFilters = () => {
    if (timeoutId) clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
        router.get(
            route('transactions.index'),
            { 
                search: search.value, 
                outlet_id: outletFilter.value, 
                date: dateFilter.value 
            },
            { preserveState: true, replace: true }
        );
    }, 400);
};

watch(search, applyFilters);
watch(outletFilter, applyFilters);
watch(dateFilter, applyFilters);

// Modals
const isDetailModalOpen = ref(false);
const isVoidModalOpen = ref(false);
const isDeleteModalOpen = ref(false);

const selectedTxn = ref<TransactionData | null>(null);
const txnToVoid = ref<TransactionData | null>(null);
const txnToDelete = ref<TransactionData | null>(null);

const deliveryStatus = ref('pending');

const openDetailModal = (txn: TransactionData) => {
    selectedTxn.value = txn;
    deliveryStatus.value = txn.delivery_status || 'pending';
    isDetailModalOpen.value = true;
};

const updateTxnDeliveryStatus = () => {
    if (!selectedTxn.value) return;
    router.post(route('transactions.delivery-status', selectedTxn.value.id), {
        delivery_status: deliveryStatus.value,
    }, {
        preserveScroll: true,
        onSuccess: () => {
            if (selectedTxn.value) {
                selectedTxn.value.delivery_status = deliveryStatus.value;
            }
        }
    });
};

const openVoidModal = (txn: TransactionData) => {
    txnToVoid.value = txn;
    isVoidModalOpen.value = true;
};

const openDeleteModal = (txn: TransactionData) => {
    txnToDelete.value = txn;
    isDeleteModalOpen.value = true;
};

const submitVoid = () => {
    if (!txnToVoid.value) return;
    router.post(route('transactions.void', txnToVoid.value.id), {}, {
        onSuccess: () => {
            isVoidModalOpen.value = false;
            txnToVoid.value = null;
            
            // Update detail modal state if it was open
            if (selectedTxn.value) {
                selectedTxn.value.status = 'cancelled';
            }
        },
    });
};

const submitDelete = () => {
    if (!txnToDelete.value) return;
    router.delete(route('transactions.destroy', txnToDelete.value.id), {
        onSuccess: () => {
            isDeleteModalOpen.value = false;
            txnToDelete.value = null;
        },
    });
};

const isConfirmPaymentModalOpen = ref(false);
const txnToConfirm = ref<TransactionData | null>(null);
const isConfirming = ref(false);
const isKitchenPrintPromptOpen = ref(false);
const kitchenPrintPromptTxnId = ref<number | null>(null);

const openConfirmPaymentModal = (txn: TransactionData) => {
    txnToConfirm.value = txn;
    isConfirmPaymentModalOpen.value = true;
};

const submitConfirmPayment = () => {
    if (!txnToConfirm.value) return;
    
    const txnId = txnToConfirm.value.id;
    isConfirming.value = true;
    router.post(route('transactions.confirm-payment', txnId), {}, {
        preserveScroll: true,
        onSuccess: () => {
            isConfirming.value = false;
            isConfirmPaymentModalOpen.value = false;
            if (txnToConfirm.value) {
                txnToConfirm.value.status = 'success';
            }
            if (selectedTxn.value && selectedTxn.value.id === txnToConfirm.value?.id) {
                selectedTxn.value.status = 'success';
            }
            txnToConfirm.value = null;
            
            // Auto-print customer receipt, then prompt for kitchen print
            handlePrint(txnId, 'pos');
            kitchenPrintPromptTxnId.value = txnId;
            isKitchenPrintPromptOpen.value = true;
        },
        onError: () => {
            isConfirming.value = false;
        }
    });
};

const confirmKitchenPrint = () => {
    if (kitchenPrintPromptTxnId.value) {
        handlePrint(kitchenPrintPromptTxnId.value, 'kitchen');
    }
    isKitchenPrintPromptOpen.value = false;
    kitchenPrintPromptTxnId.value = null;
};

const skipKitchenPrint = () => {
    isKitchenPrintPromptOpen.value = false;
    kitchenPrintPromptTxnId.value = null;
};

const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleString('id-ID', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
    });
};

import {
    getPrintSettings,
    savePrintSettings,
    connectQZ,
    getAvailablePrinters,
    printReceipt,
    type PrintSettings,
    isPrinting,
    printStatus
} from '@/lib/printService';

const handlePrint = async (txnId: number, type: 'pos' | 'kitchen') => {
    if (isPrinting.value) return;
    const res = await printReceipt(txnId, type);
    if (res.error) {
        alert(res.error);
    }
};

// Printer Settings States
const isPrinterSettingsOpen = ref(false);
const printSettings = ref<PrintSettings>({
    method: 'browser',
    posPrinter: '',
    kitchenPrinter: '',
    autoPrintPos: false,
    autoPrintKitchen: false,
    zoomScale: 100
});
const availablePrinters = ref<string[]>([]);
const isConnectingQZ = ref(false);
const qzConnectionStatus = ref<'disconnected' | 'connected' | 'error'>('disconnected');

// Load settings on mount
onMounted(() => {
    printSettings.value = getPrintSettings();
    if (printSettings.value.method === 'qz') {
        checkQzConnection();
    }
});

const checkQzConnection = async () => {
    isConnectingQZ.value = true;
    try {
        const connected = await connectQZ();
        if (connected) {
            qzConnectionStatus.value = 'connected';
            availablePrinters.value = await getAvailablePrinters();
        } else {
            qzConnectionStatus.value = 'disconnected';
            availablePrinters.value = [];
        }
    } catch (e) {
        qzConnectionStatus.value = 'error';
        availablePrinters.value = [];
    } finally {
        isConnectingQZ.value = false;
    }
};

const saveSettings = () => {
    savePrintSettings(printSettings.value);
    isPrinterSettingsOpen.value = false;
    alert('Pengaturan printer berhasil disimpan.');
};
</script>

<template>
    <Head title="Transaction History" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header Section -->
            <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-50">Transaction History</h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Search and view receipt records, audit payments, and void mistaken cash entries.
                    </p>
                </div>
                <button
                    @click="isPrinterSettingsOpen = true"
                    class="self-start sm:self-auto px-4 py-2 border border-slate-200 dark:border-slate-800 rounded-lg text-xs font-semibold hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors cursor-pointer text-slate-700 dark:text-slate-300 flex items-center gap-1.5 animate-pulse"
                >
                    <Settings class="h-4 w-4 text-[#8c5a3c]" />
                    <span>Pengaturan Printer</span>
                </button>
            </div>

            <!-- Filters & Tables Card -->
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-sm overflow-hidden">
                <!-- Filter Toolbar -->
                <div class="p-5 border-b border-slate-200 dark:border-slate-800 flex flex-col md:flex-row items-center gap-4">
                    <!-- Search Input -->
                    <div class="relative flex-1 w-full">
                        <Search class="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
                        <input
                            v-model="search"
                            type="text"
                            placeholder="Search by Transaction Number (TXN-...)"
                            class="w-full pl-9 pr-4 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all text-slate-900 dark:text-slate-100"
                        />
                    </div>
                    
                    <!-- Outlet Filter (only for Admin/Owners) -->
                    <div class="w-full md:w-48" v-if="!isCashier">
                        <select
                            v-model="outletFilter"
                            class="w-full px-3 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 text-slate-900 dark:text-slate-100"
                        >
                            <option value="">All Outlets</option>
                            <option v-for="ot in outlets" :key="ot.id" :value="String(ot.id)">{{ ot.name }}</option>
                        </select>
                    </div>

                    <!-- Date Filter -->
                    <div class="relative w-full md:w-48">
                        <Calendar class="absolute left-3 top-2.5 h-4 w-4 text-slate-400 pointer-events-none" />
                        <input
                            v-model="dateFilter"
                            type="date"
                            class="w-full pl-9 pr-3 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 text-slate-900 dark:text-slate-100"
                        />
                    </div>
                </div>

                <!-- Table Content -->
                <div class="overflow-x-auto">
                    <table class="w-full border-collapse text-left">
                        <thead>
                            <tr class="border-b border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/30">
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">TXN Code</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Date & Time</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Outlet</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Operator</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Amount Paid</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Payment</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Status</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-200 dark:divide-slate-800">
                            <tr v-if="transactions.data.length === 0">
                                <td colspan="8" class="p-8 text-center text-sm text-slate-500 dark:text-slate-400">
                                    No transaction records found.
                                </td>
                            </tr>
                            <tr 
                                v-for="txn in transactions.data" 
                                :key="txn.id"
                                class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-colors"
                            >
                                <td class="p-4 font-mono text-xs font-bold text-slate-900 dark:text-slate-100">
                                    {{ txn.transaction_number }}
                                </td>
                                <td class="p-4 text-xs text-slate-500 dark:text-slate-400">
                                    {{ formatDate(txn.created_at) }}
                                </td>
                                <td class="p-4 text-xs text-slate-700 dark:text-slate-300">
                                    <div class="flex items-center gap-1.5">
                                        <Store class="h-3.5 w-3.5 text-slate-450 flex-shrink-0" />
                                        <span>{{ txn.outlet?.name }}</span>
                                    </div>
                                </td>
                                <td class="p-4 text-xs text-slate-700 dark:text-slate-300">
                                    <div class="flex items-center gap-1.5">
                                        <User class="h-3.5 w-3.5 text-slate-450 flex-shrink-0" />
                                        <span>{{ txn.user?.name || '-' }}</span>
                                    </div>
                                </td>
                                <td class="p-4 text-sm font-bold text-slate-900 dark:text-slate-100">
                                    Rp {{ Number(txn.total_amount).toLocaleString('id-ID') }}
                                </td>
                                <td class="p-4 text-xs uppercase font-semibold text-slate-600 dark:text-slate-400">
                                    {{ txn.payment_method }}
                                </td>
                                <td class="p-4 text-xs">
                                     <span 
                                         :class="[
                                             'inline-flex px-2 py-0.5 rounded-full text-[10px] font-bold uppercase',
                                             txn.status === 'success'
                                                 ? 'bg-emerald-50 dark:bg-emerald-950/30 text-emerald-700 dark:text-emerald-400'
                                                 : (txn.status === 'pending' ? 'bg-amber-50 dark:bg-amber-950/30 text-amber-700 dark:text-amber-400' : 'bg-rose-50 dark:bg-rose-950/30 text-rose-700 dark:text-rose-450')
                                         ]"
                                     >
                                         {{ txn.status === 'success' ? 'Success' : (txn.status === 'pending' ? 'Pending' : 'Voided') }}
                                     </span>
                                 </td>
                                <td class="p-4 text-right">
                                    <div class="flex items-center justify-end gap-1">
                                        <a
                                            :href="route('transactions.print', txn.id)"
                                            @click.prevent="handlePrint(txn.id, 'pos')"
                                            target="_blank"
                                            :class="{ 'opacity-50 pointer-events-none': isPrinting }"
                                            class="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 text-slate-500 dark:text-slate-400 hover:text-slate-800 cursor-pointer flex items-center justify-center"
                                            title="Print POS Receipt"
                                        >
                                            <Printer class="h-4 w-4" />
                                        </a>
                                        <a
                                            :href="route('transactions.kitchen-print', txn.id)"
                                            @click.prevent="handlePrint(txn.id, 'kitchen')"
                                            target="_blank"
                                            :class="{ 'opacity-50 pointer-events-none': isPrinting }"
                                            class="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 text-slate-500 dark:text-slate-400 hover:text-[#8c5a3c] dark:hover:text-[#a17150] cursor-pointer flex items-center justify-center"
                                            title="Print Kitchen Ticket"
                                        >
                                            <FileText class="h-4 w-4" />
                                        </a>
                                        <button
                                            @click="openDetailModal(txn)"
                                            class="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 text-slate-500 dark:text-slate-400 hover:text-slate-800 cursor-pointer"
                                            title="View Invoice Detail"
                                        >
                                            <Eye class="h-4 w-4" />
                                        </button>
                                        <button
                                            v-if="txn.status === 'pending'"
                                            @click="openConfirmPaymentModal(txn)"
                                            class="px-2.5 py-1 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-xs font-bold shadow-sm transition-all cursor-pointer inline-flex items-center gap-1"
                                            title="Konfirmasi Pembayaran Lunas"
                                        >
                                            <Check class="h-3.5 w-3.5" />
                                            <span>Konfirmasi Bayar</span>
                                        </button>
                                        <button
                                            v-if="txn.status === 'success'"
                                            @click="openVoidModal(txn)"
                                            class="p-1.5 rounded-lg hover:bg-rose-50 dark:hover:bg-rose-95/10 text-rose-500 hover:text-rose-600 cursor-pointer"
                                            title="Void Transaction"
                                        >
                                            <RefreshCw class="h-4 w-4" />
                                        </button>
                                        <button
                                            v-if="!isCashier"
                                            @click="openDeleteModal(txn)"
                                            class="p-1.5 rounded-lg hover:bg-red-50 dark:hover:bg-red-95/10 text-red-600 hover:text-red-700 cursor-pointer"
                                            title="Delete Transaction"
                                        >
                                            <Trash2 class="h-4 w-4" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <div v-if="transactions.last_page > 1" class="p-4 border-t border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <p class="text-xs text-slate-500">Showing {{ transactions.data.length }} of {{ transactions.total }} records</p>
                    <div class="flex gap-2">
                        <Link
                            v-if="transactions.prev_page_url"
                            :href="transactions.prev_page_url"
                            class="px-3 py-1.5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-xs font-semibold hover:bg-slate-50 dark:hover:bg-slate-800 transition-all text-slate-700 dark:text-slate-300 cursor-pointer"
                        >
                            Previous
                        </Link>
                        <Link
                            v-if="transactions.next_page_url"
                            :href="transactions.next_page_url"
                            class="px-3 py-1.5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-xs font-semibold hover:bg-slate-50 dark:hover:bg-slate-800 transition-all text-slate-700 dark:text-slate-300 cursor-pointer"
                        >
                            Next
                        </Link>
                    </div>
                </div>
            </div>
        </div>

        <!-- Detail Invoice Modal -->
        <div v-if="isDetailModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm">
            <div class="w-full max-w-md bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200">
                <div class="p-5 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <div class="flex items-center gap-2">
                        <Receipt class="h-5 w-5 text-slate-500" />
                        <h3 class="text-md font-bold text-slate-900 dark:text-slate-50">Invoice Slip</h3>
                    </div>
                    <button @click="isDetailModalOpen = false" class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-500 cursor-pointer">
                        <X class="h-5 w-5" />
                    </button>
                </div>

                <div class="p-6 space-y-6">
                    <div class="text-center space-y-1">
                        <h4 class="text-lg font-extrabold tracking-wider uppercase text-slate-900 dark:text-slate-50">{{ $page.props.settings.site_name }}</h4>
                        <p class="text-xs text-slate-500">{{ selectedTxn?.outlet?.name }}</p>
                        <p class="text-[10px] text-slate-400">{{ selectedTxn ? formatDate(selectedTxn.created_at) : '' }}</p>
                    </div>

                    <div class="border-t border-b border-dashed border-slate-200 dark:border-slate-800 py-3 text-xs space-y-1.5 font-mono">
                        <div class="flex justify-between">
                            <span>Invoice No:</span>
                            <span class="font-bold">{{ selectedTxn?.transaction_number }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Order Type:</span>
                            <span class="font-bold uppercase text-[#8c5a3c]">{{ selectedTxn?.order_type }}</span>
                        </div>
                        <div class="flex justify-between" v-if="selectedTxn?.order_type === 'delivery'">
                            <span>Kurir:</span>
                            <span class="font-bold">{{ selectedTxn?.courier?.name || 'Belum Ditugaskan' }}</span>
                        </div>
                        <div class="flex justify-between" v-if="selectedTxn?.order_type === 'delivery'">
                            <span>Status Delivery:</span>
                            <span class="font-bold uppercase text-orange-500">{{ selectedTxn?.delivery_status }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Cashier:</span>
                            <span>{{ selectedTxn?.user?.name || '-' }}</span>
                        </div>
                        <div class="flex justify-between uppercase">
                            <span>Payment Mode:</span>
                            <span>{{ selectedTxn?.payment_method }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Status:</span>
                            <span class="font-bold uppercase" :class="selectedTxn?.status === 'success' ? 'text-emerald-600' : 'text-rose-500'">
                                {{ selectedTxn?.status }}
                            </span>
                        </div>
                    </div>

                    <!-- Delivery Status Update Controls -->
                    <div v-if="selectedTxn?.order_type === 'delivery' && selectedTxn?.status === 'success'" class="p-3 border border-[#8c5a3c]/20 bg-[#8c5a3c]/5 rounded-xl space-y-2">
                        <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-wider">Update Status Pengiriman</label>
                        <div class="flex gap-2">
                            <select
                                v-model="deliveryStatus"
                                class="flex-1 h-8 px-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-white dark:bg-slate-900 text-xs font-semibold focus:outline-none focus:ring-1 focus:ring-[#8c5a3c]"
                            >
                                <option value="pending">Pending</option>
                                <option value="preparing">Preparing</option>
                                <option value="delivering">Delivering</option>
                                <option value="delivered">Delivered</option>
                                <option value="failed">Failed</option>
                            </select>
                            <button
                                @click="updateTxnDeliveryStatus"
                                class="h-8 px-3 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-lg cursor-pointer transition-colors"
                            >
                                Update
                            </button>
                        </div>
                    </div>

                    <!-- Items -->
                    <div class="space-y-3 font-mono text-xs max-h-40 overflow-y-auto pr-1">
                        <div v-for="item in selectedTxn?.items" :key="item.id" class="flex justify-between items-start">
                            <div>
                                <p class="font-bold">{{ item.product?.name }}</p>
                                <span v-if="item.variant" class="text-[10px] text-slate-400 uppercase">[{{ item.variant }}]</span>
                            </div>
                            <span class="text-right flex-shrink-0 ml-4">{{ item.qty }} x Rp{{ Number(item.price).toLocaleString('id-ID') }}</span>
                        </div>
                    </div>

                    <!-- Pricing Summary -->
                    <div class="border-t border-dashed border-slate-200 dark:border-slate-800 pt-3 space-y-1.5 font-mono text-xs">
                        <div class="flex justify-between">
                            <span>Subtotal</span>
                            <span>Rp {{ (Number(selectedTxn?.total_amount) - Number(selectedTxn?.tax_amount) - Number(selectedTxn?.service_charge_amount)).toLocaleString('id-ID') }}</span>
                        </div>
                        <div class="flex justify-between" v-if="Number(selectedTxn?.service_charge_amount) > 0">
                            <span>Service Charge</span>
                            <span>Rp {{ Number(selectedTxn?.service_charge_amount).toLocaleString('id-ID') }}</span>
                        </div>
                        <div class="flex justify-between" v-if="Number(selectedTxn?.tax_amount) > 0">
                            <span>Tax</span>
                            <span>Rp {{ Number(selectedTxn?.tax_amount).toLocaleString('id-ID') }}</span>
                        </div>
                        <div class="flex justify-between text-sm font-bold pt-1.5 border-t border-slate-200 dark:border-slate-800">
                            <span>Grand Total</span>
                            <span>Rp {{ Number(selectedTxn?.total_amount).toLocaleString('id-ID') }}</span>
                        </div>
                    </div>
                </div>

                <div class="p-5 border-t border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900/30 flex flex-col gap-3">
                    <div class="flex gap-2">
                        <a
                            v-if="selectedTxn"
                            :href="route('transactions.print', selectedTxn.id)"
                            @click.prevent="handlePrint(selectedTxn.id, 'pos')"
                            target="_blank"
                            :class="{ 'opacity-50 pointer-events-none': isPrinting }"
                            class="flex-1 py-2 bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-300 rounded-lg text-xs font-semibold shadow-sm text-center flex items-center justify-center gap-1.5 cursor-pointer"
                        >
                            <Printer class="h-3.5 w-3.5" />
                            Print Struk
                        </a>
                        <a
                            v-if="selectedTxn"
                            :href="route('transactions.kitchen-print', selectedTxn.id)"
                            @click.prevent="handlePrint(selectedTxn.id, 'kitchen')"
                            target="_blank"
                            :class="{ 'opacity-50 pointer-events-none': isPrinting }"
                            class="flex-1 py-2 border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900 text-[#8c5a3c] dark:text-[#a17150] rounded-lg text-xs font-semibold shadow-sm text-center flex items-center justify-center gap-1.5 cursor-pointer transition-colors"
                        >
                            <FileText class="h-3.5 w-3.5" />
                            Tiket Dapur
                        </a>
                    </div>
                    
                    <div class="flex gap-2">
                        <button
                            v-if="selectedTxn?.status === 'pending'"
                            @click="openConfirmPaymentModal(selectedTxn); isDetailModalOpen = false;"
                            class="flex-1 py-2 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-xs font-bold shadow-sm focus:outline-none transition-all flex items-center justify-center gap-1 cursor-pointer"
                        >
                            <Check class="h-3.5 w-3.5" />
                            Konfirmasi Lunas
                        </button>
                        <button
                            v-if="selectedTxn?.status === 'success'"
                            @click="openVoidModal(selectedTxn)"
                            class="flex-1 py-2 bg-rose-600 hover:bg-rose-500 text-white rounded-lg text-xs font-semibold shadow-sm focus:outline-none transition-all flex items-center justify-center gap-1 cursor-pointer"
                        >
                            <RefreshCw class="h-3.5 w-3.5 animate-spin-reverse" />
                            Void Order
                        </button>
                        <button
                            @click="isDetailModalOpen = false"
                            class="flex-1 py-2 border border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-xs font-semibold transition-all cursor-pointer text-center"
                        >
                            Close
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Void Confirmation Modal -->
        <div v-if="isVoidModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm">
            <div class="w-full max-w-md bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl p-6 animate-in zoom-in-95 duration-200 space-y-6">
                <div class="flex items-center gap-3 text-rose-600 dark:text-rose-450">
                    <AlertTriangle class="h-6 w-6 flex-shrink-0" />
                    <h3 class="text-lg font-bold">Void Transaction?</h3>
                </div>

                <p class="text-sm text-slate-500 dark:text-slate-400">
                    Are you sure you want to void transaction <span class="font-bold text-slate-900 dark:text-slate-100">"{{ txnToVoid?.transaction_number }}"</span>? This will cancel the order, mark it as Void, and **instantly restore all deducted stock levels (BOM ingredients / manual retail products)** in the outlet inventory. This action is irreversible.
                </p>

                <div class="flex items-center justify-end gap-3">
                    <button
                        @click="isVoidModalOpen = false"
                        class="px-4 py-2 border border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-sm font-semibold transition-all cursor-pointer"
                    >
                        Cancel
                    </button>
                    <button
                        @click="submitVoid"
                        class="px-4 py-2 bg-rose-600 hover:bg-rose-500 text-white rounded-lg text-sm font-semibold transition-all cursor-pointer"
                    >
                        Confirm Void
                    </button>
                </div>
            </div>
        </div>
        <!-- Delete Confirmation Modal -->
        <div v-if="isDeleteModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm">
            <div class="w-full max-w-md bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl p-6 animate-in zoom-in-95 duration-200 space-y-6">
                <div class="flex items-center gap-3 text-rose-600 dark:text-rose-450">
                    <AlertTriangle class="h-6 w-6 flex-shrink-0" />
                    <h3 class="text-lg font-bold">Hapus Transaksi Permanen?</h3>
                </div>

                <p class="text-sm text-slate-500 dark:text-slate-400 font-sans">
                    Apakah Anda yakin ingin menghapus transaksi <span class="font-bold text-slate-900 dark:text-slate-100">"{{ txnToDelete?.transaction_number }}"</span> secara permanen dari database?
                    <br><br>
                    <span v-if="txnToDelete?.status !== 'cancelled'" class="text-rose-500 font-bold block">
                        ⚠️ PENTING: Karena status transaksi ini masih aktif (SUKSES), stok bahan baku (BOM) / produk retail yang terpotong akan DIKEMBALIKAN (REVERT) secara otomatis ke dalam inventori!
                    </span>
                    <span v-else class="text-slate-500 block">
                        Catatan: Karena transaksi ini sudah di-void (dibatalkan), stok telah dikembalikan sebelumnya dan tidak akan disesuaikan lagi.
                    </span>
                </p>

                <div class="flex items-center justify-end gap-3 font-sans">
                    <button
                        @click="isDeleteModalOpen = false"
                        class="px-4 py-2 border border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-sm font-semibold transition-all cursor-pointer"
                    >
                        Batal
                    </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-all cursor-pointer"
                    >
                        Hapus Transaksi
                    </button>
                </div>
            </div>
        </div>

        <!-- Printer Settings Modal -->
        <div v-if="isPrinterSettingsOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/65 backdrop-blur-sm animate-in fade-in duration-150">
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-md overflow-hidden flex flex-col transform transition-all">
                <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <h3 class="text-sm font-extrabold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                        <Settings class="h-4 w-4 text-[#8c5a3c]" />
                        <span>Pengaturan Printer POS</span>
                    </h3>
                    <button @click="isPrinterSettingsOpen = false" class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-400 cursor-pointer">
                        <X class="h-4 w-4" />
                    </button>
                </div>

                <div class="p-6 space-y-4 max-h-[70vh] overflow-y-auto font-sans">
                    <!-- Metode Cetak Selection -->
                    <div class="space-y-1.5">
                        <label class="block text-xs font-bold text-slate-650 dark:text-slate-350">Metode Pencetakan</label>
                        <select
                            v-model="printSettings.method"
                            class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                        >
                            <option value="browser">Browser Print (Buka Tab Baru)</option>
                            <option value="qz">QZ Tray (Cetak Otomatis / Silent)</option>
                        </select>
                    </div>

                    <!-- QZ Tray Connection Status -->
                    <div v-if="printSettings.method === 'qz'" class="p-3 bg-slate-50 dark:bg-slate-900/30 border border-slate-200 dark:border-slate-800 rounded-xl space-y-3">
                        <div class="flex items-center justify-between">
                            <span class="text-[10px] font-bold uppercase tracking-wider text-slate-400">Status QZ Tray</span>
                            <span 
                                :class="[
                                    'inline-flex px-2 py-0.5 rounded-full text-[9px] font-bold uppercase',
                                    qzConnectionStatus === 'connected' ? 'bg-emerald-50 dark:bg-emerald-95/30 text-emerald-700' : 'bg-rose-50 dark:bg-rose-95/30 text-rose-700'
                                ]"
                            >
                                {{ qzConnectionStatus === 'connected' ? 'Terhubung' : 'Terputus' }}
                            </span>
                        </div>

                        <button
                            type="button"
                            @click="checkQzConnection"
                            :disabled="isConnectingQZ"
                            class="w-full py-1.5 border border-slate-200 dark:border-slate-800 hover:bg-slate-100 dark:hover:bg-slate-900 text-slate-700 dark:text-slate-300 text-xs font-bold rounded-lg transition-colors cursor-pointer flex items-center justify-center gap-1.5 disabled:opacity-50"
                        >
                            <RefreshCw class="h-3 w-3" :class="{'animate-spin': isConnectingQZ}" />
                            <span>Hubungkan Ulang / Cek Koneksi</span>
                        </button>
                    </div>

                    <!-- Printer Choices -->
                    <div v-if="printSettings.method === 'qz'" class="space-y-3">
                        <!-- POS Printer Selection -->
                        <div class="space-y-1.5">
                            <label class="block text-xs font-bold text-slate-650 dark:text-slate-350">Printer Kasir (Struk)</label>
                            <select
                                v-if="availablePrinters.length > 0"
                                v-model="printSettings.posPrinter"
                                class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                            >
                                <option value="">-- Pilih Printer Kasir --</option>
                                <option v-for="printer in availablePrinters" :key="printer" :value="printer">{{ printer }}</option>
                            </select>
                            <input
                                v-else
                                v-model="printSettings.posPrinter"
                                type="text"
                                placeholder="Masukkan nama printer (e.g. POS-58)"
                                class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                            />
                        </div>

                        <!-- Kitchen Printer Selection -->
                        <div class="space-y-1.5">
                            <label class="block text-xs font-bold text-slate-650 dark:text-slate-350">Printer Dapur (Tiket)</label>
                            <select
                                v-if="availablePrinters.length > 0"
                                v-model="printSettings.kitchenPrinter"
                                class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                            >
                                <option value="">-- Pilih Printer Dapur --</option>
                                <option v-for="printer in availablePrinters" :key="printer" :value="printer">{{ printer }}</option>
                            </select>
                            <input
                                v-else
                                v-model="printSettings.kitchenPrinter"
                                type="text"
                                placeholder="Masukkan nama printer (e.g. Kitchen-Printer)"
                                class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                            />
                        </div>

                        <!-- Zoom Scale -->
                        <div class="pt-1 space-y-1.5">
                            <label class="block text-xs font-bold text-slate-650 dark:text-slate-350">
                                Zoom Scale Cetak (%)
                            </label>
                            <div class="flex items-center gap-3">
                                <input
                                    v-model.number="printSettings.zoomScale"
                                    type="range"
                                    min="40"
                                    max="120"
                                    step="5"
                                    class="flex-1 h-1.5 accent-[#8c5a3c] cursor-pointer"
                                />
                                <span class="text-xs font-bold text-[#8c5a3c] w-10 text-right">{{ printSettings.zoomScale }}%</span>
                            </div>
                            <p class="text-[10px] text-slate-400 dark:text-slate-500">Default: 100%. Turunkan jika hasil cetak terpotong di sisi kanan.</p>
                        </div>
                    </div>
                </div>

                <div class="px-6 py-4 border-t border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900/30 flex items-center justify-end gap-3">
                    <button
                        type="button"
                        @click="isPrinterSettingsOpen = false"
                        class="px-4 py-2 border border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-300 text-xs font-bold rounded-xl hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors cursor-pointer"
                    >
                        Batal
                    </button>
                    <button
                        type="button"
                        @click="saveSettings"
                        class="px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer"
                    >
                        Simpan Pengaturan
                    </button>
                </div>
            </div>
        </div>

        <!-- Confirm Payment Shadcn UI Modal -->
        <div v-if="isConfirmPaymentModalOpen && txnToConfirm" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/70 backdrop-blur-sm animate-in fade-in duration-200">
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-3xl shadow-2xl w-full max-w-md overflow-hidden flex flex-col transform transition-all animate-in zoom-in-95 duration-200">
                <!-- Header -->
                <div class="px-6 py-5 border-b border-slate-100 dark:border-slate-800 flex items-start justify-between bg-slate-50/50 dark:bg-slate-900/30">
                    <div class="flex items-center gap-3">
                        <div class="h-10 w-10 bg-emerald-500/10 rounded-2xl flex items-center justify-center text-emerald-600 shrink-0">
                            <CheckCircle2 class="h-5 w-5" />
                        </div>
                        <div>
                            <h3 class="text-sm font-black text-slate-900 dark:text-slate-100 uppercase tracking-wider">
                                Konfirmasi Pembayaran
                            </h3>
                            <p class="text-xs text-slate-400 font-medium mt-0.5">
                                Mengubah status transaksi menjadi LUNAS
                            </p>
                        </div>
                    </div>
                    <button 
                        @click="isConfirmPaymentModalOpen = false; txnToConfirm = null;" 
                        class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-800 rounded-xl text-slate-400 cursor-pointer transition-colors"
                    >
                        <X class="h-4 w-4" />
                    </button>
                </div>

                <!-- Body -->
                <div class="p-6 space-y-4">
                    <div class="bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-2 text-xs">
                        <div class="flex justify-between">
                            <span class="text-slate-400">No. Transaksi:</span>
                            <span class="font-mono font-bold text-slate-900 dark:text-slate-100">{{ txnToConfirm.transaction_number }}</span>
                        </div>
                        <div class="flex justify-between" v-if="txnToConfirm.table">
                            <span class="text-slate-400">Nomor Meja:</span>
                            <span class="font-bold text-[#8c5a3c]">Meja {{ txnToConfirm.table.number }}</span>
                        </div>
                        <div class="flex justify-between" v-if="txnToConfirm.customer">
                            <span class="text-slate-400">Pemesan:</span>
                            <span class="font-bold text-slate-900 dark:text-slate-100">{{ txnToConfirm.customer.name }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-slate-400">Metode Bayar:</span>
                            <span class="font-bold uppercase text-amber-700 dark:text-amber-400">{{ txnToConfirm.payment_method }}</span>
                        </div>
                    </div>

                    <div class="flex justify-between items-center bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-900/50 rounded-2xl p-4">
                        <div>
                            <span class="text-[10px] font-black text-emerald-700 dark:text-emerald-400 uppercase tracking-wider block">Total Tagihan</span>
                            <span class="text-xs text-slate-500">Status transaksi akan menjadi LUNAS</span>
                        </div>
                        <span class="text-lg font-black text-emerald-700 dark:text-emerald-300 font-mono">
                            Rp {{ Number(txnToConfirm.total_amount).toLocaleString('id-ID') }}
                        </span>
                    </div>
                </div>

                <!-- Footer Actions -->
                <div class="px-6 py-4 border-t border-slate-100 dark:border-slate-800 flex items-center justify-end gap-3 bg-slate-50/50 dark:bg-slate-900/10">
                    <button
                        type="button"
                        @click="isConfirmPaymentModalOpen = false; txnToConfirm = null;"
                        class="px-4 py-2.5 border border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800 text-xs font-bold rounded-xl transition-all cursor-pointer"
                    >
                        Batal
                    </button>
                    <button
                        type="button"
                        @click="submitConfirmPayment"
                        :disabled="isConfirming"
                        class="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-xs font-extrabold rounded-xl transition-all shadow-md shadow-emerald-600/20 flex items-center gap-2 cursor-pointer active:scale-95"
                    >
                        <Check class="h-4 w-4" />
                        <span>{{ isConfirming ? 'Memproses...' : 'Konfirmasi & Lunaskan' }}</span>
                    </button>
                </div>
            </div>
        </div>

        <!-- Silent Printing Loading Overlay -->
        <Transition
            enter-active-class="transition ease-out duration-300"
            enter-from-class="opacity-0 scale-95"
            enter-to-class="opacity-100 scale-100"
            leave-active-class="transition ease-in duration-200"
            leave-from-class="opacity-100 scale-100"
            leave-to-class="opacity-0 scale-95"
        >
            <div 
                v-if="isPrinting" 
                class="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-slate-950/65 backdrop-blur-md"
            >
                <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl p-6 w-full max-w-sm text-center space-y-4 transform transition-all">
                    <!-- Rotating Premium Spinner -->
                    <div class="relative w-16 h-16 mx-auto flex items-center justify-center">
                        <div class="absolute inset-0 rounded-full border-4 border-slate-100 dark:border-slate-900"></div>
                        <div class="absolute inset-0 rounded-full border-4 border-t-[#8c5a3c] dark:border-t-[#8c5a3c] animate-spin"></div>
                        <Printer class="h-6 w-6 text-[#8c5a3c]" />
                    </div>
                    
                    <div class="space-y-1">
                        <h3 class="text-sm font-bold text-slate-900 dark:text-slate-100">
                            Sedang Mencetak Struk
                        </h3>
                        <p class="text-xs text-slate-500 dark:text-slate-400 animate-pulse font-medium">
                            {{ printStatus || 'Menghubungkan ke printer...' }}
                        </p>
                    </div>
                </div>
            </div>
        </Transition>

        <!-- Kitchen Print Prompt Modal -->
        <Teleport to="body">
            <div v-if="isKitchenPrintPromptOpen" class="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm animate-in fade-in duration-200">
                <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-xs p-6 space-y-5 animate-in zoom-in-95 duration-200 text-center">
                    <!-- Icon -->
                    <div class="flex flex-col items-center gap-3">
                        <div class="h-14 w-14 rounded-2xl bg-orange-50 dark:bg-orange-950/20 flex items-center justify-center text-orange-500">
                            <Printer class="h-7 w-7" />
                        </div>
                        <div>
                            <h3 class="text-sm font-extrabold text-slate-900 dark:text-slate-100">Cetak Struk Dapur?</h3>
                            <p class="text-xs text-slate-500 dark:text-slate-400 mt-1">Struk pelanggan telah dicetak. Apakah Anda juga ingin mencetak tiket dapur untuk pesanan ini?</p>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="flex gap-2.5">
                        <button
                            type="button"
                            @click="skipKitchenPrint"
                            class="flex-1 py-2.5 border border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900 text-xs font-bold rounded-xl transition-all cursor-pointer"
                        >
                            Tidak, Lewati
                        </button>
                        <button
                            type="button"
                            @click="confirmKitchenPrint"
                            class="flex-1 py-2.5 bg-orange-500 hover:bg-orange-400 text-white text-xs font-extrabold rounded-xl transition-all shadow-md shadow-orange-500/20 flex items-center justify-center gap-1.5 cursor-pointer active:scale-95"
                        >
                            <Printer class="h-3.5 w-3.5" />
                            <span>Ya, Cetak Dapur</span>
                        </button>
                    </div>
                </div>
            </div>
        </Teleport>
</AdminLayout>
</template>
