@extends('layouts.admin')

@section('title', 'Finance Settings')

@section('page-title', 'Finance Settings')

@section('breadcrumbs')
    <a href="{{ route('admin.settings.index') }}" class="hover:text-primary">Settings</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">Finance</span>
@endsection

@section('content')
<div class="max-w-7xl mx-auto">
    <!-- Tabs Navigation -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 mb-6">
        <div class="border-b border-gray-200">
            <nav class="flex -mb-px overflow-x-auto bg-gray-50/50">
                <a href="{{ route('admin.settings.finance', ['tab' => 'currency']) }}" class="px-6 py-4 text-sm font-medium border-b-2 whitespace-nowrap {{ $tab === 'currency' ? 'border-primary text-primary bg-white' : 'border-transparent text-gray-700 hover:text-primary hover:border-gray-300 hover:bg-white/50' }} transition-colors">
                    Currency
                </a>
                <a href="{{ route('admin.settings.finance', ['tab' => 'tax']) }}" class="px-6 py-4 text-sm font-medium border-b-2 whitespace-nowrap {{ $tab === 'tax' ? 'border-primary text-primary bg-white' : 'border-transparent text-gray-700 hover:text-primary hover:border-gray-300 hover:bg-white/50' }} transition-colors">
                    Tax Rates & Groups
                </a>
                <a href="{{ route('admin.settings.finance', ['tab' => 'payment-gateway']) }}" class="px-6 py-4 text-sm font-medium border-b-2 whitespace-nowrap {{ $tab === 'payment-gateway' ? 'border-primary text-primary bg-white' : 'border-transparent text-gray-700 hover:text-primary hover:border-gray-300 hover:bg-white/50' }} transition-colors">
                    Payment Gateway
                </a>
            </nav>
        </div>

        <div class="p-6 bg-white">
            @if (session('success'))
                <div class="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg flex items-center gap-2">
                    <span class="material-symbols-outlined text-green-600">check_circle</span>
                    <span class="text-sm text-green-800">{{ session('success') }}</span>
                </div>
            @endif

            @if (session('error'))
                <div class="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2">
                    <span class="material-symbols-outlined text-red-600">error</span>
                    <span class="text-sm text-red-800">{{ session('error') }}</span>
                </div>
            @endif

            @if($tab === 'currency')
                <!-- Currency Tab -->
                <div class="space-y-6">
                    <!-- Page Heading & Actions -->
                    <div class="flex flex-col justify-between gap-6 sm:flex-row sm:items-center">
                        <div class="flex flex-col gap-2">
                            <h1 class="text-3xl font-bold tracking-tight text-gray-900">Currency Settings</h1>
                            <p class="text-gray-700">Manage the currencies available for your invoices and estimates.</p>
                        </div>
                        <button onclick="document.getElementById('add-currency-modal').classList.remove('hidden')" class="flex items-center justify-center gap-2 rounded-lg bg-primary px-5 py-2.5 text-sm font-bold text-white shadow-md shadow-primary/20 transition-all hover:bg-blue-600 hover:shadow-lg focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2">
                            <span class="material-symbols-outlined text-[20px]">add</span>
                            <span>Add Currency</span>
                        </button>
                    </div>
                    <!-- Content Card -->
                    <div class="flex flex-1 flex-col overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                        <!-- Toolbar -->
                        <div class="flex flex-wrap items-center justify-between gap-4 border-b border-gray-200 p-5 bg-white">
                            <div class="relative flex w-full max-w-sm items-center">
                                <div class="absolute left-3 flex items-center justify-center text-gray-500">
                                    <span class="material-symbols-outlined text-[20px]">search</span>
                                </div>
                                <input id="search-currencies" class="h-10 w-full rounded-lg border border-gray-300 bg-white py-2 pl-10 pr-4 text-sm text-gray-900 placeholder-gray-400 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary" placeholder="Search currency name or code..." type="text"/>
                            </div>
                            <div class="flex items-center gap-2">
                                <div class="relative min-w-[120px]">
                                    <select id="filter-currencies-status" class="h-10 w-full rounded-lg border border-gray-300 bg-white py-2 pl-3 pr-10 text-sm text-gray-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary appearance-none cursor-pointer">
                                        <option value="">All Statuses</option>
                                        <option value="active">Active</option>
                                        <option value="inactive">Inactive</option>
                                    </select>
                                    <span class="material-symbols-outlined absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 text-[18px] pointer-events-none">filter_list</span>
                                </div>
                                <button id="export-currencies" class="flex items-center gap-2 rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                                    <span class="material-symbols-outlined text-[18px]">download</span>
                                    <span class="hidden sm:inline">Export</span>
                                </button>
                            </div>
                        </div>
                        <!-- Table Container -->
                        <div class="w-full overflow-x-auto">
                            <table class="w-full min-w-[800px] text-left text-sm">
                                <thead class="bg-gray-50 text-gray-700">
                                    <tr>
                                        <th class="w-64 px-6 py-4 font-semibold text-gray-900">Currency Name</th>
                                        <th class="w-32 px-6 py-4 font-semibold text-gray-900">Symbol</th>
                                        <th class="w-32 px-6 py-4 font-semibold text-gray-900">Code</th>
                                        <th class="w-40 px-6 py-4 font-semibold text-gray-900">Status</th>
                                        <th class="w-40 px-6 py-4 font-semibold text-gray-900">Default</th>
                                        <th class="w-32 px-6 py-4 text-right font-semibold text-gray-900">Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="currencies-table-body" class="divide-y divide-gray-200 bg-white">
                                    <!-- Data will be loaded via AJAX -->
                                </tbody>
                            </table>
                        </div>
                        <!-- Pagination -->
                        <div class="flex items-center justify-between border-t border-gray-200 px-6 py-4 bg-white">
                            <div class="flex items-center gap-2 text-sm text-gray-700">
                                <span>Rows per page:</span>
                                <select id="currencies-per-page" class="border border-gray-300 rounded bg-white px-2 py-1 focus:ring-primary/50 text-gray-900 cursor-pointer">
                                    <option value="10">10</option>
                                    <option value="20">20</option>
                                    <option value="50">50</option>
                                    <option value="100">100</option>
                                </select>
                            </div>
                            <div class="flex items-center gap-4">
                                <span id="currencies-pagination-info" class="text-sm text-gray-700">Loading...</span>
                                <div class="flex items-center gap-2">
                                    <button id="currencies-prev" class="flex h-9 w-9 items-center justify-center rounded-lg border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 hover:text-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors" disabled>
                                        <span class="material-symbols-outlined text-[20px]">chevron_left</span>
                                    </button>
                                    <button id="currencies-next" class="flex h-9 w-9 items-center justify-center rounded-lg border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 hover:text-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                                        <span class="material-symbols-outlined text-[20px]">chevron_right</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            @elseif($tab === 'tax')
                <!-- Tax Rates & Groups Tab -->
                <div class="space-y-6">
                    <!-- Filters & Search -->
                    <div class="flex flex-wrap items-center justify-between gap-4">
                        <div class="flex flex-1 items-center gap-4 max-w-2xl">
                            <div class="relative flex-1 min-w-[240px]">
                                <span class="material-symbols-outlined absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-[20px]">search</span>
                                <input id="search-tax-groups" class="w-full pl-10 pr-4 py-2.5 bg-white border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 text-gray-900 placeholder-gray-400 transition-shadow" placeholder="Search by group name..." type="text"/>
                            </div>
                            <div class="relative min-w-[180px]">
                                <select id="filter-tax-groups-status" class="w-full pl-4 pr-10 py-2.5 bg-white border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 text-gray-900 appearance-none cursor-pointer">
                                    <option value="">All Statuses</option>
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                                <span class="material-symbols-outlined absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 text-[20px] pointer-events-none">filter_list</span>
                            </div>
                        </div>
                        <div class="flex items-center gap-2">
                            <button id="export-tax-groups" class="flex items-center justify-center p-2.5 rounded-lg border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 transition-colors" title="Export CSV">
                                <span class="material-symbols-outlined text-[20px]">download</span>
                            </button>
                            <button onclick="document.getElementById('add-tax-group-modal').classList.remove('hidden')" class="flex items-center gap-2 bg-primary hover:bg-primary/90 text-white px-4 py-2.5 rounded-lg text-sm font-medium transition-all shadow-sm shadow-primary/30">
                                <span class="material-symbols-outlined text-[20px]">add</span>
                                <span>Add Tax Group</span>
                            </button>
                        </div>
                    </div>
                    <!-- Main Card: Tax Group Table -->
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 flex flex-col overflow-hidden">
                        <div class="overflow-x-auto">
                            <table class="w-full text-left border-collapse">
                                <thead>
                                    <tr class="bg-gray-50 border-b border-gray-200">
                                        <th class="py-4 px-6 text-xs font-semibold text-gray-900 uppercase tracking-wider w-[60px]">
                                            <input type="checkbox" id="select-all-tax-groups" class="rounded border-gray-300 text-primary focus:ring-primary/50 cursor-pointer"/>
                                        </th>
                                        <th class="py-4 px-6 text-xs font-semibold text-gray-900 uppercase tracking-wider">Group Name</th>
                                        <th class="py-4 px-6 text-xs font-semibold text-gray-900 uppercase tracking-wider">Components</th>
                                        <th class="py-4 px-6 text-xs font-semibold text-gray-900 uppercase tracking-wider">Total Rate</th>
                                        <th class="py-4 px-6 text-xs font-semibold text-gray-900 uppercase tracking-wider">Created On</th>
                                        <th class="py-4 px-6 text-xs font-semibold text-gray-900 uppercase tracking-wider">Status</th>
                                        <th class="py-4 px-6 text-xs font-semibold text-gray-900 uppercase tracking-wider text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="tax-groups-table-body" class="divide-y divide-gray-200 bg-white">
                                    <!-- Data will be loaded via AJAX -->
                                </tbody>
                            </table>
                        </div>
                        <!-- Pagination -->
                        <div class="bg-white px-6 py-4 border-t border-gray-200 flex items-center justify-between">
                            <div class="flex items-center gap-2 text-sm text-gray-700">
                                <span>Rows per page:</span>
                                <select id="tax-groups-per-page" class="border border-gray-300 rounded bg-white px-2 py-1 focus:ring-primary/50 text-gray-900 cursor-pointer">
                                    <option value="10">10</option>
                                    <option value="20">20</option>
                                    <option value="50">50</option>
                                    <option value="100">100</option>
                                </select>
                            </div>
                            <div class="flex items-center gap-4 text-sm text-gray-700">
                                <span id="tax-groups-pagination-info">Loading...</span>
                                <div class="flex items-center gap-1">
                                    <button id="tax-groups-prev" class="p-1 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-gray-700" disabled>
                                        <span class="material-symbols-outlined text-[20px]">chevron_left</span>
                                    </button>
                                    <button id="tax-groups-next" class="p-1 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-gray-700">
                                        <span class="material-symbols-outlined text-[20px]">chevron_right</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            @elseif($tab === 'payment-gateway')
                <!-- Payment Gateway Tab -->
                <div class="space-y-6">
                    <!-- Page Heading -->
                    <div class="flex flex-col justify-between gap-6 sm:flex-row sm:items-center">
                        <div class="flex flex-col gap-2">
                            <h1 class="text-3xl font-bold tracking-tight text-gray-900">Payment Gateway Settings</h1>
                            <p class="text-gray-700">Configure payment gateways for online payments on invoices and receipts.</p>
                        </div>
                    </div>

                    <!-- Payment Gateways List -->
                    <div class="grid gap-6 md:grid-cols-2">
                        <!-- PayPal Gateway Card -->
                        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="p-6 border-b border-gray-200 bg-gray-50">
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center gap-3">
                                        <div class="flex h-12 w-12 items-center justify-center rounded-lg bg-blue-100">
                                            <span class="text-2xl font-bold text-blue-600">PP</span>
                                        </div>
                                        <div>
                                            <h3 class="text-lg font-semibold text-gray-900">PayPal</h3>
                                            <p class="text-sm text-gray-600">Accept payments via PayPal</p>
                                        </div>
                                    </div>
                                    <label class="relative inline-block w-12 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                                        <input type="checkbox" id="paypal-active" {{ ($paypalGateway->is_active ?? false) ? 'checked' : '' }} onchange="updateGatewayStatus('paypal', this.checked)" class="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300"/>
                                        <span class="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300 {{ ($paypalGateway->is_active ?? false) ? 'bg-primary' : '' }}"></span>
                                    </label>
                                </div>
                            </div>
                            <div class="p-6">
                                <form id="paypal-form" method="POST" action="{{ route('admin.settings.payment-gateways.update', ['gateway' => 'paypal']) }}">
                                    @csrf
                                    @method('PUT')
                                    <div class="space-y-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-900 mb-1">Mode <span class="text-red-500">*</span></label>
                                            <select name="mode" id="paypal-mode" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary">
                                                <option value="sandbox" {{ ($paypalGateway->mode ?? 'sandbox') === 'sandbox' ? 'selected' : '' }}>Sandbox (Testing)</option>
                                                <option value="live" {{ ($paypalGateway->mode ?? 'sandbox') === 'live' ? 'selected' : '' }}>Live (Production)</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-900 mb-1">Client ID <span class="text-red-500">*</span></label>
                                            <input type="text" name="client_id" id="paypal-client-id" value="{{ $paypalGateway->credentials['client_id'] ?? '' }}" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="Enter PayPal Client ID"/>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-900 mb-1">Client Secret <span class="text-red-500">*</span></label>
                                            <input type="password" name="client_secret" id="paypal-client-secret" value="{{ $paypalGateway->credentials['client_secret'] ?? '' }}" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="Enter PayPal Client Secret"/>
                                        </div>
                                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                                            <div class="flex items-start gap-2">
                                                <span class="material-symbols-outlined text-blue-600 text-[20px]">info</span>
                                                <div class="text-sm text-blue-800">
                                                    <p class="font-medium mb-1">How to get PayPal credentials:</p>
                                                    <ol class="list-decimal list-inside space-y-1 text-xs">
                                                        <li>Log in to your PayPal Developer account</li>
                                                        <li>Go to Dashboard → My Apps & Credentials</li>
                                                        <li>Create a new app or use existing one</li>
                                                        <li>Copy the Client ID and Secret</li>
                                                    </ol>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="flex justify-end gap-3 pt-4 border-t border-gray-200">
                                            <button type="button" onclick="testGateway('paypal')" class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">Test Connection</button>
                                            <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-primary hover:bg-primary/90 rounded-lg transition-colors shadow-sm">Save Settings</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Stripe Gateway Card -->
                        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="p-6 border-b border-gray-200 bg-gray-50">
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center gap-3">
                                        <div class="flex h-12 w-12 items-center justify-center rounded-lg bg-purple-100">
                                            <span class="text-2xl font-bold text-purple-600">S</span>
                                        </div>
                                        <div>
                                            <h3 class="text-lg font-semibold text-gray-900">Stripe</h3>
                                            <p class="text-sm text-gray-600">Accept payments via Stripe</p>
                                        </div>
                                    </div>
                                    <label class="relative inline-block w-12 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                                        <input type="checkbox" id="stripe-active" {{ ($stripeGateway->is_active ?? false) ? 'checked' : '' }} onchange="updateGatewayStatus('stripe', this.checked)" class="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300"/>
                                        <span class="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300 {{ ($stripeGateway->is_active ?? false) ? 'bg-primary' : '' }}"></span>
                                    </label>
                                </div>
                            </div>
                            <div class="p-6">
                                <form id="stripe-form" method="POST" action="{{ route('admin.settings.payment-gateways.update', ['gateway' => 'stripe']) }}">
                                    @csrf
                                    @method('PUT')
                                    <div class="space-y-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-900 mb-1">Mode <span class="text-red-500">*</span></label>
                                            <select name="mode" id="stripe-mode" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary">
                                                <option value="sandbox" {{ ($stripeGateway->mode ?? 'sandbox') === 'sandbox' ? 'selected' : '' }}>Test Mode</option>
                                                <option value="live" {{ ($stripeGateway->mode ?? 'sandbox') === 'live' ? 'selected' : '' }}>Live Mode</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-900 mb-1">Publishable Key <span class="text-red-500">*</span></label>
                                            <input type="text" name="publishable_key" id="stripe-publishable-key" value="{{ $stripeGateway->credentials['publishable_key'] ?? '' }}" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="pk_test_..."/>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-900 mb-1">Secret Key <span class="text-red-500">*</span></label>
                                            <input type="password" name="secret_key" id="stripe-secret-key" value="{{ $stripeGateway->credentials['secret_key'] ?? '' }}" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="sk_test_..."/>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-900 mb-1">Webhook Secret (Optional)</label>
                                            <input type="password" name="webhook_secret" id="stripe-webhook-secret" value="{{ $stripeGateway->credentials['webhook_secret'] ?? '' }}" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="whsec_..."/>
                                        </div>
                                        <div class="bg-purple-50 border border-purple-200 rounded-lg p-4">
                                            <div class="flex items-start gap-2">
                                                <span class="material-symbols-outlined text-purple-600 text-[20px]">info</span>
                                                <div class="text-sm text-purple-800">
                                                    <p class="font-medium mb-1">How to get Stripe credentials:</p>
                                                    <ol class="list-decimal list-inside space-y-1 text-xs">
                                                        <li>Log in to your Stripe Dashboard</li>
                                                        <li>Go to Developers → API keys</li>
                                                        <li>Copy the Publishable key and Secret key</li>
                                                        <li>For webhooks, go to Developers → Webhooks</li>
                                                    </ol>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="flex justify-end gap-3 pt-4 border-t border-gray-200">
                                            <button type="button" onclick="testGateway('stripe')" class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">Test Connection</button>
                                            <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-primary hover:bg-primary/90 rounded-lg transition-colors shadow-sm">Save Settings</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            @endif
        </div>
    </div>
</div>

<!-- Add Tax Group Modal -->
<div id="add-tax-group-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-hidden">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity bg-slate-900/50 backdrop-blur-sm" onclick="document.getElementById('add-tax-group-modal').classList.add('hidden')"></div>
        <div class="pointer-events-auto w-full max-w-md bg-white h-full absolute right-0 top-0 shadow-2xl transform transition-transform duration-300 flex flex-col">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between bg-white">
                <h2 class="text-lg font-bold text-gray-900">Add Tax Group</h2>
                <button onclick="document.getElementById('add-tax-group-modal').classList.add('hidden')" class="text-gray-600 hover:text-gray-900 transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form method="POST" action="{{ route('admin.settings.tax-groups.store') }}" class="flex-1 overflow-y-auto p-6 flex flex-col gap-6 bg-white">
                @csrf
                <div class="flex flex-col gap-2">
                    <label class="text-sm font-medium text-gray-900">Group Name <span class="text-red-500">*</span></label>
                    <input name="name" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 focus:ring-primary focus:border-primary px-3 py-2.5" placeholder="e.g. Standard VAT" type="text"/>
                </div>
                <div class="flex flex-col gap-2">
                    <label class="text-sm font-medium text-gray-900">Code <span class="text-red-500">*</span></label>
                    <input name="code" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 focus:ring-primary focus:border-primary px-3 py-2.5 uppercase" placeholder="e.g. VAT-STD" type="text"/>
                </div>
                <div class="flex flex-col gap-2">
                    <label class="text-sm font-medium text-gray-900">Description</label>
                    <textarea name="description" rows="3" class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 focus:ring-primary focus:border-primary px-3 py-2.5" placeholder="Optional description"></textarea>
                </div>
                <div class="p-6 border-t border-gray-200 flex justify-end gap-3 bg-gray-50 -mx-6 -mb-6 sticky bottom-0">
                    <button type="button" onclick="document.getElementById('add-tax-group-modal').classList.add('hidden')" class="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">Cancel</button>
                    <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-primary hover:bg-primary/90 rounded-lg transition-colors shadow-sm">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Tax Group Modal -->
<div id="edit-tax-group-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-hidden">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity bg-gray-900/50 backdrop-blur-sm" onclick="document.getElementById('edit-tax-group-modal').classList.add('hidden')"></div>
        <div class="pointer-events-auto w-full max-w-md bg-white h-full absolute right-0 top-0 shadow-2xl transform transition-transform duration-300 flex flex-col">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between bg-white">
                <h2 class="text-lg font-bold text-gray-900">Edit Tax Group</h2>
                <button onclick="document.getElementById('edit-tax-group-modal').classList.add('hidden')" class="text-gray-600 hover:text-gray-900 transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="edit-tax-group-form" method="POST" class="flex-1 overflow-y-auto p-6 flex flex-col gap-6 bg-white">
                @csrf
                @method('PUT')
                <div class="flex flex-col gap-2">
                    <label class="text-sm font-medium text-gray-900">Group Name <span class="text-red-500">*</span></label>
                    <input name="name" id="edit-tax-group-name" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 focus:ring-primary focus:border-primary px-3 py-2.5" placeholder="e.g. Standard VAT" type="text"/>
                </div>
                <div class="flex flex-col gap-2">
                    <label class="text-sm font-medium text-gray-900">Code <span class="text-red-500">*</span></label>
                    <input name="code" id="edit-tax-group-code" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 focus:ring-primary focus:border-primary px-3 py-2.5 uppercase" placeholder="e.g. VAT-STD" type="text"/>
                </div>
                <div class="flex flex-col gap-2">
                    <label class="text-sm font-medium text-gray-900">Description</label>
                    <textarea name="description" id="edit-tax-group-description" rows="3" class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 focus:ring-primary focus:border-primary px-3 py-2.5" placeholder="Optional description"></textarea>
                </div>
                <div class="p-6 border-t border-gray-200 flex justify-end gap-3 bg-gray-50 -mx-6 -mb-6 sticky bottom-0">
                    <button type="button" onclick="document.getElementById('edit-tax-group-modal').classList.add('hidden')" class="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">Cancel</button>
                    <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-primary hover:bg-primary/90 rounded-lg transition-colors shadow-sm">Update Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Tax Group Confirmation Modal -->
<div id="delete-tax-group-modal" data-admin-modal class="hidden fixed inset-0 z-[100] overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity bg-gray-900/50 backdrop-blur-sm" aria-hidden="true" onclick="document.getElementById('delete-tax-group-modal').classList.add('hidden')"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                        <span class="material-symbols-outlined text-red-600" style="font-size: 24px;">warning</span>
                    </div>
                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left flex-1">
                        <h3 class="text-lg leading-6 font-medium text-gray-900" id="delete-tax-group-title">
                            Delete Tax Group
                        </h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-500">
                                Are you sure you want to delete <strong id="delete-tax-group-name"></strong>? This action cannot be undone.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <form id="delete-tax-group-form" method="POST" class="inline">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
                        Delete
                    </button>
                </form>
                <button type="button" onclick="document.getElementById('delete-tax-group-modal').classList.add('hidden')" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    Cancel
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Add Currency Modal -->
<div id="add-currency-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity bg-slate-900/50 backdrop-blur-sm" onclick="document.getElementById('add-currency-modal').classList.add('hidden')"></div>
        <div class="inline-block align-bottom bg-white rounded-xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <form method="POST" action="/admin/settings/currencies" id="add-currency-form">
                @csrf
                <div class="bg-white p-6">
                    <h3 class="text-lg font-bold text-gray-900 mb-4">Add Currency</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-900 mb-1">Currency Name <span class="text-red-500">*</span></label>
                            <input name="name" required class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="United States Dollar" type="text"/>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-900 mb-1">Symbol <span class="text-red-500">*</span></label>
                            <input name="symbol" required class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="$" type="text"/>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-900 mb-1">Code <span class="text-red-500">*</span></label>
                            <input name="code" required class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary uppercase" placeholder="USD" type="text"/>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-6 py-4 flex items-center justify-end gap-3 border-t border-gray-200">
                    <button type="button" onclick="document.getElementById('add-currency-modal').classList.add('hidden')" class="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">Cancel</button>
                    <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-primary hover:bg-primary/90 rounded-lg transition-colors shadow-sm">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Currency Modal -->
<div id="edit-currency-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity bg-gray-900/50 backdrop-blur-sm" onclick="document.getElementById('edit-currency-modal').classList.add('hidden')"></div>
        <div class="inline-block align-bottom bg-white rounded-xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <form id="edit-currency-form" method="POST" class="bg-white">
                @csrf
                @method('PUT')
                <div class="bg-white p-6">
                    <h3 class="text-lg font-bold text-gray-900 mb-4">Edit Currency</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-900 mb-1">Currency Name <span class="text-red-500">*</span></label>
                            <input name="name" id="edit-currency-name" required class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="United States Dollar" type="text"/>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-900 mb-1">Symbol <span class="text-red-500">*</span></label>
                            <input name="symbol" id="edit-currency-symbol" required class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="$" type="text"/>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-900 mb-1">Code <span class="text-red-500">*</span></label>
                            <input name="code" id="edit-currency-code" required class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary uppercase" placeholder="USD" type="text"/>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-6 py-4 flex items-center justify-end gap-3 border-t border-gray-200">
                    <button type="button" onclick="document.getElementById('edit-currency-modal').classList.add('hidden')" class="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">Cancel</button>
                    <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-primary hover:bg-primary/90 rounded-lg transition-colors shadow-sm">Update Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Currency Confirmation Modal -->
<div id="delete-currency-modal" data-admin-modal class="hidden fixed inset-0 z-[100] overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity bg-gray-900/50 backdrop-blur-sm" aria-hidden="true" onclick="document.getElementById('delete-currency-modal').classList.add('hidden')"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                        <span class="material-symbols-outlined text-red-600" style="font-size: 24px;">warning</span>
                    </div>
                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left flex-1">
                        <h3 class="text-lg leading-6 font-medium text-gray-900" id="delete-currency-title">
                            Delete Currency
                        </h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-500">
                                Are you sure you want to delete <strong id="delete-currency-name"></strong>? This action cannot be undone.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <form id="delete-currency-form" method="POST" class="inline">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
                        Delete
                    </button>
                </form>
                <button type="button" onclick="document.getElementById('delete-currency-modal').classList.add('hidden')" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    Cancel
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Tax Group Modal -->
<div id="edit-tax-group-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-hidden">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity bg-gray-900/50 backdrop-blur-sm" onclick="document.getElementById('edit-tax-group-modal').classList.add('hidden')"></div>
        <div class="pointer-events-auto w-full max-w-md bg-white h-full absolute right-0 top-0 shadow-2xl transform transition-transform duration-300 flex flex-col">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between bg-white">
                <h2 class="text-lg font-bold text-gray-900">Edit Tax Group</h2>
                <button onclick="document.getElementById('edit-tax-group-modal').classList.add('hidden')" class="text-gray-600 hover:text-gray-900 transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="edit-tax-group-form" method="POST" class="flex-1 overflow-y-auto p-6 flex flex-col gap-6 bg-white">
                @csrf
                @method('PUT')
                <div class="flex flex-col gap-2">
                    <label class="text-sm font-medium text-gray-900">Group Name <span class="text-red-500">*</span></label>
                    <input name="name" id="edit-tax-group-name" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 focus:ring-primary focus:border-primary px-3 py-2.5" placeholder="e.g. Standard VAT" type="text"/>
                </div>
                <div class="flex flex-col gap-2">
                    <label class="text-sm font-medium text-gray-900">Code <span class="text-red-500">*</span></label>
                    <input name="code" id="edit-tax-group-code" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 focus:ring-primary focus:border-primary px-3 py-2.5 uppercase" placeholder="e.g. VAT-STD" type="text"/>
                </div>
                <div class="flex flex-col gap-2">
                    <label class="text-sm font-medium text-gray-900">Description</label>
                    <textarea name="description" id="edit-tax-group-description" rows="3" class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 focus:ring-primary focus:border-primary px-3 py-2.5" placeholder="Optional description"></textarea>
                </div>
                <div class="p-6 border-t border-gray-200 flex justify-end gap-3 bg-gray-50 -mx-6 -mb-6 sticky bottom-0">
                    <button type="button" onclick="document.getElementById('edit-tax-group-modal').classList.add('hidden')" class="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">Cancel</button>
                    <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-primary hover:bg-primary/90 rounded-lg transition-colors shadow-sm">Update Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Tax Group Confirmation Modal -->
<div id="delete-tax-group-modal" data-admin-modal class="hidden fixed inset-0 z-[100] overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity bg-gray-900/50 backdrop-blur-sm" aria-hidden="true" onclick="document.getElementById('delete-tax-group-modal').classList.add('hidden')"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                        <span class="material-symbols-outlined text-red-600" style="font-size: 24px;">warning</span>
                    </div>
                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left flex-1">
                        <h3 class="text-lg leading-6 font-medium text-gray-900" id="delete-tax-group-title">
                            Delete Tax Group
                        </h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-500">
                                Are you sure you want to delete <strong id="delete-tax-group-name"></strong>? This action cannot be undone.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <form id="delete-tax-group-form" method="POST" class="inline">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
                        Delete
                    </button>
                </form>
                <button type="button" onclick="document.getElementById('delete-tax-group-modal').classList.add('hidden')" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    Cancel
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let currentTaxGroupsPage = 1;
let taxGroupsPerPage = 10;
let taxGroupsSearch = '';
let taxGroupsStatus = '';

// Load tax groups data
function loadTaxGroups() {
    const params = new URLSearchParams({
        page: currentTaxGroupsPage,
        per_page: taxGroupsPerPage,
        search: taxGroupsSearch,
        status: taxGroupsStatus,
    });
    
    fetch(`{{ route('admin.settings.tax-groups.api') }}?${params}`)
        .then(response => response.json())
        .then(data => {
            renderTaxGroupsTable(data.data);
            updateTaxGroupsPagination(data);
        })
        .catch(error => {
            console.error('Error loading tax groups:', error);
            document.getElementById('tax-groups-table-body').innerHTML = '<tr><td colspan="7" class="py-8 px-4 text-center text-gray-600">Error loading data</td></tr>';
        });
}

// Render tax groups table
function renderTaxGroupsTable(groups) {
    const tbody = document.getElementById('tax-groups-table-body');
    
    if (groups.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="py-8 px-4 text-center text-gray-600">No tax groups found</td></tr>';
        return;
    }
    
    tbody.innerHTML = groups.map(group => {
        const components = group.components.length > 0 
            ? group.components.map(c => `<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-700">${c}</span>`).join('')
            : '<span class="text-xs text-gray-500">No components</span>';
        
        return `
            <tr class="hover:bg-gray-50 transition-colors group">
                <td class="py-4 px-6">
                    <input type="checkbox" class="rounded border-gray-300 text-primary focus:ring-primary/50 cursor-pointer" value="${group.id}"/>
                </td>
                <td class="py-4 px-6">
                    <p class="text-sm font-medium text-gray-900">${group.name}</p>
                    <p class="text-xs text-gray-600">${group.description || ''}</p>
                </td>
                <td class="py-4 px-6">
                    <div class="flex flex-wrap gap-1">${components}</div>
                </td>
                <td class="py-4 px-6">
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold bg-blue-50 text-blue-700">${group.total_rate}%</span>
                </td>
                <td class="py-4 px-6">
                    <p class="text-sm text-gray-700">${group.created_at}</p>
                </td>
                <td class="py-4 px-6">
                    <label class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                        <input type="checkbox" ${group.is_active ? 'checked' : ''} onchange="updateTaxGroupStatus(${group.id}, this.checked)" class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300"/>
                        <span class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300 ${group.is_active ? 'bg-primary' : ''}"></span>
                    </label>
                </td>
                <td class="py-4 px-6 text-right">
                    <div class="flex items-center justify-end gap-2 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity">
                        <button onclick="openEditTaxGroupModal(${group.id}, '${group.name.replace(/'/g, "\\'")}', '${group.code}', '${(group.description || '').replace(/'/g, "\\'")}')" class="p-1.5 text-gray-600 hover:text-primary hover:bg-blue-50 rounded-md transition-colors" title="Edit">
                            <span class="material-symbols-outlined text-[18px]">edit</span>
                        </button>
                        <button onclick="openDeleteTaxGroupModal(${group.id}, '${group.name.replace(/'/g, "\\'")}')" class="p-1.5 text-gray-600 hover:text-red-500 hover:bg-red-50 rounded-md transition-colors" title="Delete">
                            <span class="material-symbols-outlined text-[18px]">delete</span>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    }).join('');
}

// Update pagination
function updateTaxGroupsPagination(data) {
    currentTaxGroupsPage = data.current_page;
    
    const from = data.from || 0;
    const to = data.to || 0;
    const total = data.total || 0;
    
    document.getElementById('tax-groups-pagination-info').textContent = 
        `Showing ${from} to ${to} of ${total} tax groups`;
    
    const prevBtn = document.getElementById('tax-groups-prev');
    const nextBtn = document.getElementById('tax-groups-next');
    
    if (prevBtn) {
        prevBtn.disabled = data.current_page === 1;
    }
    if (nextBtn) {
        nextBtn.disabled = data.current_page >= data.last_page;
    }
}

// Search handler
document.getElementById('search-tax-groups')?.addEventListener('input', function(e) {
    taxGroupsSearch = e.target.value;
    currentTaxGroupsPage = 1;
    loadTaxGroups();
});

// Filter handler
document.getElementById('filter-tax-groups-status')?.addEventListener('change', function(e) {
    taxGroupsStatus = e.target.value;
    currentTaxGroupsPage = 1;
    loadTaxGroups();
});

// Per page handler
document.getElementById('tax-groups-per-page')?.addEventListener('change', function(e) {
    taxGroupsPerPage = parseInt(e.target.value);
    currentTaxGroupsPage = 1;
    loadTaxGroups();
});

// Pagination handlers
document.getElementById('tax-groups-prev')?.addEventListener('click', function() {
    if (currentTaxGroupsPage > 1) {
        currentTaxGroupsPage--;
        loadTaxGroups();
    }
});

document.getElementById('tax-groups-next')?.addEventListener('click', function() {
    const nextBtn = document.getElementById('tax-groups-next');
    if (!nextBtn.disabled) {
        currentTaxGroupsPage++;
        loadTaxGroups();
    }
});

// Export handler
document.getElementById('export-tax-groups')?.addEventListener('click', function() {
    const params = new URLSearchParams({
        search: taxGroupsSearch,
        status: taxGroupsStatus,
    });
    window.location.href = `{{ route('admin.settings.tax-groups.export') }}?${params}`;
});

// Edit modal
function openEditTaxGroupModal(id, name, code, description) {
    document.getElementById('edit-tax-group-name').value = name;
    document.getElementById('edit-tax-group-code').value = code;
    document.getElementById('edit-tax-group-description').value = description || '';
    document.getElementById('edit-tax-group-form').action = `/admin/settings/tax-groups/${id}`;
    document.getElementById('edit-tax-group-modal').classList.remove('hidden');
}

// Delete modal
function openDeleteTaxGroupModal(id, name) {
    document.getElementById('delete-tax-group-name').textContent = name || 'this tax group';
    document.getElementById('delete-tax-group-form').action = `/admin/settings/tax-groups/${id}`;
    document.getElementById('delete-tax-group-modal').classList.remove('hidden');
}

// Update tax group status via AJAX
function updateTaxGroupStatus(id, isActive) {
    const formData = new FormData();
    formData.append('_token', '{{ csrf_token() }}');
    formData.append('_method', 'PATCH');
    if (isActive) {
        formData.append('is_active', '1');
    }
    
    fetch(`/admin/settings/tax-groups/${id}/status`, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
        }
    })
    .then(response => {
        if (response.ok) {
            loadTaxGroups(); // Reload data to reflect changes
        } else {
            alert('Failed to update status');
            loadTaxGroups(); // Reload to revert UI
        }
    })
    .catch(error => {
        console.error('Error updating status:', error);
        alert('Failed to update status');
        loadTaxGroups(); // Reload to revert UI
    });
}

// Initialize on page load if tax tab is active
@if($tab === 'tax')
document.addEventListener('DOMContentLoaded', function() {
    loadTaxGroups();
});
@endif

// ========== CURRENCY MANAGEMENT ==========
let currentCurrenciesPage = 1;
let currenciesPerPage = 10;
let currenciesSearch = '';
let currenciesStatus = '';

// Load currencies data
function loadCurrencies() {
    const params = new URLSearchParams({
        page: currentCurrenciesPage,
        per_page: currenciesPerPage,
        search: currenciesSearch,
        status: currenciesStatus,
    });
    
    fetch(`{{ route('admin.settings.currencies.api') }}?${params}`)
        .then(response => response.json())
        .then(data => {
            renderCurrenciesTable(data.data);
            updateCurrenciesPagination(data);
        })
        .catch(error => {
            console.error('Error loading currencies:', error);
            document.getElementById('currencies-table-body').innerHTML = '<tr><td colspan="6" class="py-8 px-4 text-center text-gray-600">Error loading data</td></tr>';
        });
}

// Render currencies table
function renderCurrenciesTable(currencies) {
    const tbody = document.getElementById('currencies-table-body');
    
    if (currencies.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="py-8 px-4 text-center text-gray-600">No currencies found</td></tr>';
        return;
    }
    
    tbody.innerHTML = currencies.map(currency => {
        return `
            <tr class="group hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4">
                    <div class="flex items-center gap-3">
                        <div class="flex h-8 w-8 items-center justify-center rounded-full bg-green-100 text-xs font-bold text-green-700">
                            ${currency.symbol}
                        </div>
                        <div class="flex flex-col">
                            <span class="font-medium text-gray-900">${currency.name}</span>
                        </div>
                    </div>
                </td>
                <td class="px-6 py-4 text-gray-900 font-medium">${currency.symbol}</td>
                <td class="px-6 py-4">
                    <span class="inline-flex items-center rounded-md bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700">${currency.code}</span>
                </td>
                <td class="px-6 py-4">
                    <label class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                        <input type="checkbox" ${currency.is_active ? 'checked' : ''} onchange="updateCurrencyStatus(${currency.id}, this.checked)" class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300"/>
                        <span class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300 ${currency.is_active ? 'bg-primary' : ''}"></span>
                    </label>
                </td>
                <td class="px-6 py-4">
                    ${currency.is_default 
                        ? '<span class="inline-flex items-center rounded-full bg-primary px-2.5 py-1 text-xs font-semibold text-white shadow-sm">Default</span>'
                        : `<button onclick="setDefaultCurrency(${currency.id})" class="text-sm font-medium text-gray-700 hover:text-primary hover:underline">Set as Default</button>`
                    }
                </td>
                <td class="px-6 py-4 text-right">
                    <div class="flex items-center justify-end gap-2">
                        <button onclick="openEditCurrencyModal(${currency.id}, '${currency.name.replace(/'/g, "\\'")}', '${currency.code}', '${currency.symbol.replace(/'/g, "\\'")}')" class="flex h-8 w-8 items-center justify-center rounded-lg text-gray-600 hover:bg-primary/10 hover:text-primary transition-colors" title="Edit">
                            <span class="material-symbols-outlined text-[18px]">edit</span>
                        </button>
                        ${currency.is_default 
                            ? '<button class="flex h-8 w-8 cursor-not-allowed items-center justify-center rounded-lg text-gray-300" disabled title="Cannot delete default currency"><span class="material-symbols-outlined text-[18px]">delete</span></button>'
                            : `<button onclick="openDeleteCurrencyModal(${currency.id}, '${currency.name.replace(/'/g, "\\'")}')" class="flex h-8 w-8 items-center justify-center rounded-lg text-gray-600 hover:bg-red-50 hover:text-red-500 transition-colors" title="Delete"><span class="material-symbols-outlined text-[18px]">delete</span></button>`
                        }
                    </div>
                </td>
            </tr>
        `;
    }).join('');
}

// Update pagination
function updateCurrenciesPagination(data) {
    currentCurrenciesPage = data.current_page;
    
    const from = data.from || 0;
    const to = data.to || 0;
    const total = data.total || 0;
    
    document.getElementById('currencies-pagination-info').textContent = 
        `Showing ${from} to ${to} of ${total} currencies`;
    
    const prevBtn = document.getElementById('currencies-prev');
    const nextBtn = document.getElementById('currencies-next');
    
    if (prevBtn) {
        prevBtn.disabled = data.current_page === 1;
    }
    if (nextBtn) {
        nextBtn.disabled = data.current_page >= data.last_page;
    }
}

// Search handler
document.getElementById('search-currencies')?.addEventListener('input', function(e) {
    currenciesSearch = e.target.value;
    currentCurrenciesPage = 1;
    loadCurrencies();
});

// Filter handler
document.getElementById('filter-currencies-status')?.addEventListener('change', function(e) {
    currenciesStatus = e.target.value;
    currentCurrenciesPage = 1;
    loadCurrencies();
});

// Per page handler
document.getElementById('currencies-per-page')?.addEventListener('change', function(e) {
    currenciesPerPage = parseInt(e.target.value);
    currentCurrenciesPage = 1;
    loadCurrencies();
});

// Pagination handlers
document.getElementById('currencies-prev')?.addEventListener('click', function() {
    if (currentCurrenciesPage > 1) {
        currentCurrenciesPage--;
        loadCurrencies();
    }
});

document.getElementById('currencies-next')?.addEventListener('click', function() {
    const nextBtn = document.getElementById('currencies-next');
    if (!nextBtn.disabled) {
        currentCurrenciesPage++;
        loadCurrencies();
    }
});

// Export handler
document.getElementById('export-currencies')?.addEventListener('click', function() {
    const params = new URLSearchParams({
        search: currenciesSearch,
        status: currenciesStatus,
    });
    window.location.href = `{{ route('admin.settings.currencies.export') }}?${params}`;
});

// Update currency status via AJAX
function updateCurrencyStatus(id, isActive) {
    const formData = new FormData();
    formData.append('_token', '{{ csrf_token() }}');
    formData.append('_method', 'PATCH');
    if (isActive) {
        formData.append('is_active', '1');
    }
    
    fetch(`/admin/settings/currencies/${id}/status`, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
        }
    })
    .then(response => {
        if (response.ok) {
            loadCurrencies(); // Reload data to reflect changes
        } else {
            alert('Failed to update status');
            loadCurrencies(); // Reload to revert UI
        }
    })
    .catch(error => {
        console.error('Error updating status:', error);
        alert('Failed to update status');
        loadCurrencies(); // Reload to revert UI
    });
}

// Set default currency
function setDefaultCurrency(id) {
    const formData = new FormData();
    formData.append('_token', '{{ csrf_token() }}');
    
    fetch(`/admin/settings/currencies/${id}/set-default`, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            loadCurrencies(); // Reload data to reflect changes
        } else {
            alert(data.message || 'Failed to set default currency');
        }
    })
    .catch(error => {
        console.error('Error setting default currency:', error);
        alert('Failed to set default currency');
    });
}

// Edit modal
function openEditCurrencyModal(id, name, code, symbol) {
    document.getElementById('edit-currency-name').value = name;
    document.getElementById('edit-currency-code').value = code;
    document.getElementById('edit-currency-symbol').value = symbol;
    document.getElementById('edit-currency-form').action = `/admin/settings/currencies/${id}`;
    document.getElementById('edit-currency-modal').classList.remove('hidden');
}

// Delete modal
function openDeleteCurrencyModal(id, name) {
    document.getElementById('delete-currency-name').textContent = name || 'this currency';
    document.getElementById('delete-currency-form').action = `/admin/settings/currencies/${id}`;
    document.getElementById('delete-currency-modal').classList.remove('hidden');
}

// Initialize on page load if currency tab is active
@if($tab === 'currency')
document.addEventListener('DOMContentLoaded', function() {
    loadCurrencies();
});
@endif

// ========== PAYMENT GATEWAY MANAGEMENT ==========
// Update gateway status
function updateGatewayStatus(gateway, isActive) {
    const formData = new FormData();
    formData.append('_token', '{{ csrf_token() }}');
    formData.append('_method', 'PATCH');
    formData.append('is_active', isActive ? '1' : '0');
    
    fetch(`/admin/settings/payment-gateways/${gateway}/status`, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Show success message
            const message = document.createElement('div');
            message.className = 'fixed top-4 right-4 bg-green-50 border border-green-200 rounded-lg p-4 flex items-center gap-2 z-50';
            message.innerHTML = `
                <span class="material-symbols-outlined text-green-600">check_circle</span>
                <span class="text-sm text-green-800">${data.message}</span>
            `;
            document.body.appendChild(message);
            setTimeout(() => message.remove(), 3000);
        } else {
            alert(data.message || 'Failed to update gateway status');
        }
    })
    .catch(error => {
        console.error('Error updating gateway status:', error);
        alert('Failed to update gateway status');
    });
}

// Test gateway connection
function testGateway(gateway) {
    const formData = new FormData();
    formData.append('_token', '{{ csrf_token() }}');
    
    fetch(`/admin/settings/payment-gateways/${gateway}/test`, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
        }
    })
    .then(response => response.json())
    .then(data => {
        const message = document.createElement('div');
        message.className = `fixed top-4 right-4 border rounded-lg p-4 flex items-center gap-2 z-50 ${data.success ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'}`;
        message.innerHTML = `
            <span class="material-symbols-outlined ${data.success ? 'text-green-600' : 'text-red-600'}">${data.success ? 'check_circle' : 'error'}</span>
            <span class="text-sm ${data.success ? 'text-green-800' : 'text-red-800'}">${data.message}</span>
        `;
        document.body.appendChild(message);
        setTimeout(() => message.remove(), 5000);
    })
    .catch(error => {
        console.error('Error testing gateway:', error);
        alert('Failed to test gateway connection');
    });
}
</script>

<style>
    .toggle-checkbox:checked {
        right: 0;
        border-color: #137fec;
    }
    .toggle-checkbox:checked + .toggle-label {
        background-color: #137fec;
    }
</style>

@endsection

