@extends('layouts.app')
@php($prefix = auth()->user()->role === 'admin' ? 'admin.' : 'user.')
@section('title', 'Brands Management')

@push('styles')
    <style>
        .custom-switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }

        .custom-switch-input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .custom-switch-indicator {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }

        .custom-switch-indicator:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        .custom-switch-input:checked+.custom-switch-indicator {
            background-color: #10b981;
        }

        .custom-switch-input:checked+.custom-switch-indicator:before {
            transform: translateX(26px);
        }
    </style>
@endpush

@section('content')
    <section class="p-4 md:p-6">
        <div class="flex flex-col md:flex-row w-full justify-between items-start md:items-center mb-6">
            <div class="mb-4 md:mb-0">
                <h1 class="text-2xl font-bold text-gray-800 dark:text-gray-100">Brands</h1>
            </div>
            <div class="w-full md:w-auto flex flex-col md:flex-row gap-2">
                <button x-data="" x-on:click.prevent="$dispatch('open-modal', 'add-brand-modal')"
                    class="inline-flex items-center px-4 py-2 bg-gray-800 dark:bg-gray-200 border border-transparent rounded-md font-semibold text-xs text-white dark:text-gray-800 uppercase tracking-widest hover:bg-gray-700 dark:hover:bg-white focus:bg-gray-700 dark:focus:bg-white active:bg-gray-900 dark:active:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition ease-in-out duration-150">
                    <i class="fas fa-plus mr-2"></i>Add new
                </button>

            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden">
            <div class="p-4 overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead>
                        <tr class="bg-gray-50 dark:bg-gray-700/50">
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">#</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Brand Key</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Brand Name</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Action</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                        @forelse ($brands ?? [] as $brand)
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">{{ $loop->iteration }}</td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="flex items-center">
                                        <input readonly type="text"
                                            class="flex-grow px-3 py-2 border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-300 rounded-l-md text-to-clipboard"
                                            value="{{ $brand->brand_key ?? '' }}" id="brand-key-{{ $brand->id }}">
                                        <button
                                            class="my-copy-btn px-3 py-2 bg-gray-100 dark:bg-gray-700 border border-l-0 border-gray-300 dark:border-gray-600 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">
                                            <i class="fas fa-copy text-gray-600 dark:text-gray-300"></i>
                                        </button>
                                        <a href="{{ route($prefix . 'brands.reset-key', $brand->id) }}"
                                            class="px-3 py-2 bg-gray-100 dark:bg-gray-700 border border-l-0 border-gray-300 dark:border-gray-600 rounded-r-md cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors ajaxResetItem"
                                            data-confirm_ms="reset the brand key" title="Reset Brand Key">
                                            <i class="fas fa-recycle text-gray-600 dark:text-gray-300"></i>
                                        </a>
                                        <span id="status-badge-{{ $brand->id }}">
                                            @if ($brand->status)
                                                <small
                                                    class="ml-2 bg-green-100 text-green-800 text-xs font-medium px-2.5 py-0.5 rounded-full dark:bg-green-900 dark:text-green-300">Active</small>
                                            @else
                                                <small
                                                    class="ml-2 bg-red-100 text-red-800 text-xs font-medium px-2.5 py-0.5 rounded-full dark:bg-red-900 dark:text-red-300">Inactive</small>
                                            @endif
                                        </span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{{ $brand->name }}</td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <label class="custom-switch">
                                        <input type="checkbox" name="item_status" data-id="{{ $brand->id }}" data-status="{{ $brand->status }}"
                                            data-action="{{ route($prefix . 'brands.change-status') }}"
                                            class="custom-switch-input ajaxToggleItemStatus" @if($brand->status) checked @endif>
                                        <span class="custom-switch-indicator"></span>
                                    </label>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <x-dropdown align="right" width="48">
                                        <x-slot name="trigger">
                                            <button class="p-2 rounded-full text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-600 dark:hover:text-gray-300">
                                                <i class="fas fa-ellipsis-v"></i>
                                            </button>
                                        </x-slot>
                                        <x-slot name="content">
                                            <button
                                                data-edit-url="{{ route($prefix . 'brands.edit', $brand) }}"
                                                data-update-url="{{ route($prefix . 'brands.update', $brand) }}"
                                                class="edit-brand-btn block w-full px-4 py-2 text-left text-sm leading-5 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-800 transition duration-150 ease-in-out">
                                                <i class="fas fa-edit mr-2"></i>
                                                {{ __('Edit') }}
                                            </button>
                                            <button
                                                data-url="{{ route($prefix . 'brands.destroy', $brand) }}"
                                                class="ajaxDeleteItem block w-full px-4 py-2 text-left text-sm leading-5 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-800 transition duration-150 ease-in-out"
                                                data-confirm_ms="delete this item">
                                                <i class="fas fa-trash mr-2"></i>{{ __('Delete') }}
                                            </button>
                                        </x-slot>
                                    </x-dropdown>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="5" class="px-6 py-4 whitespace-nowrap text-sm text-center text-gray-500 dark:text-gray-400">
                                    No brands found.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </section>

    <!-- Toast Notification -->
    <div id="toast" class="hidden fixed bottom-4 right-4 bg-green-500 text-white px-4 py-2 rounded-md shadow-lg z-50">
        <span id="toast-message"></span>
    </div>

    <!-- Add Brand Modal -->
    <x-modal name="add-brand-modal" focusable>
        <form method="post" action="{{ route($prefix . 'brands.store') }}" class="p-6" id="add-brand-form" enctype="multipart/form-data">
            @csrf

            <h2 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                <i class="fa-solid fa-check-to-slot mr-2"></i>
                {{ __('Add Brand') }}
            </h2>

            <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Brand Name -->
                <div>
                    <x-input-label for="brand_name" value="{{ __('Brand Name') }}" />
                    <x-text-input id="brand_name" name="name" type="text" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('brand_name')" class="mt-2" />
                </div>

                <!-- Mobile Number -->
                <div>
                    <x-input-label for="mobile_number" value="{{ __('Mobile Number') }}" />
                    <x-text-input id="mobile_number" name="mobile_number" type="text" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('mobile_number')" class="mt-2" />
                </div>

                <!-- Domain -->
                <div class="md:col-span-2">
                    <x-input-label for="domain" value="{{ __('Domain (Just domain name)') }}" />
                    <x-text-input id="domain" name="domain" type="text" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('domain')" class="mt-2" />
                </div>

                <!-- WhatsApp Number -->
                <div>
                    <x-input-label for="whatsapp_number" value="{{ __('WhatsApp Number') }}" />
                    <x-text-input id="whatsapp_number" name="whatsapp_number" type="text" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('whatsapp_number')" class="mt-2" />
                </div>

                <!-- Support Mail -->
                <div>
                    <x-input-label for="support_mail" value="{{ __('Support Mail') }}" />
                    <x-text-input id="support_mail" name="support_mail" type="email" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('support_mail')" class="mt-2" />
                </div>

                <!-- Charge Type -->
                <div>
                    <x-input-label for="fees_type" value="{{ __('Charge type') }}" />
                    <select name="fees_type" id="fees_type" class="border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 focus:border-indigo-500 dark:focus:border-indigo-600 focus:ring-indigo-500 dark:focus:ring-indigo-600 rounded-md shadow-sm mt-1 block w-full">
                        <option value="0">Flat</option>
                        <option value="1">Percent</option>
                    </select>
                    <x-input-error :messages="$errors->get('fees_type')" class="mt-2" />
                </div>

                <!-- Charge Amount -->
                <div>
                    <x-input-label for="fees" value="{{ __('Charge amount') }}" />
                    <x-text-input id="fees" name="fees" type="number" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('fees')" class="mt-2" />
                </div>

                <!-- Status -->
                <div class="md:col-span-2">
                    <x-input-label for="status" value="{{ __('Status') }}" />
                    <select name="status" id="status" class="border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 focus:border-indigo-500 dark:focus:border-indigo-600 focus:ring-indigo-500 dark:focus:ring-indigo-600 rounded-md shadow-sm mt-1 block w-full">
                        <option value="1">Active</option>
                        <option value="0">Deactive</option>
                    </select>
                    <x-input-error :messages="$errors->get('status')" class="mt-2" />
                </div>

                <!-- Brand Logo -->
                <div class="md:col-span-2">
                    <x-input-label for="brand_logo" value="{{ __('Add Brand Image') }}" />
                    <input id="brand_logo" type="file" name="brand_logo" class="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100"/>
                    <x-input-error :messages="$errors->get('brand_logo')" class="mt-2" />
                </div>
            </div>

            <div class="mt-6 flex justify-end">
                <x-secondary-button x-on:click="$dispatch('close')">
                    {{ __('Close') }}
                </x-secondary-button>

                <x-primary-button class="ml-3">
                    {{ __('Save') }}
                </x-primary-button>
            </div>
        </form>
    </x-modal>

    <!-- Edit Brand Modal -->
    <x-modal name="edit-brand-modal" focusable>
        <form method="post" action="" class="p-6" id="edit-brand-form" enctype="multipart/form-data">
            @csrf
            @method('PUT')

            <h2 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                <i class="fas fa-edit mr-2"></i>
                {{ __('Edit Brand') }}
            </h2>

            <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Brand Name -->
                <div>
                    <x-input-label for="edit_brand_name" value="{{ __('Brand Name') }}" />
                    <x-text-input id="edit_brand_name" name="name" type="text" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('name')" class="mt-2" />
                </div>

                <!-- Mobile Number -->
                <div>
                    <x-input-label for="edit_mobile_number" value="{{ __('Mobile Number') }}" />
                    <x-text-input id="edit_mobile_number" name="mobile_number" type="text" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('mobile_number')" class="mt-2" />
                </div>

                <!-- Domain -->
                <div class="md:col-span-2">
                    <x-input-label for="edit_domain" value="{{ __('Domain (Just domain name)') }}" />
                    <x-text-input id="edit_domain" name="domain" type="text" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('domain')" class="mt-2" />
                </div>

                <!-- WhatsApp Number -->
                <div>
                    <x-input-label for="edit_whatsapp_number" value="{{ __('WhatsApp Number') }}" />
                    <x-text-input id="edit_whatsapp_number" name="whatsapp_number" type="text" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('whatsapp_number')" class="mt-2" />
                </div>

                <!-- Support Mail -->
                <div>
                    <x-input-label for="edit_support_mail" value="{{ __('Support Mail') }}" />
                    <x-text-input id="edit_support_mail" name="support_mail" type="email" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('support_mail')" class="mt-2" />
                </div>

                <!-- Charge Type -->
                <div>
                    <x-input-label for="edit_fees_type" value="{{ __('Charge type') }}" />
                    <select name="fees_type" id="edit_fees_type" class="border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 focus:border-indigo-500 dark:focus:border-indigo-600 focus:ring-indigo-500 dark:focus:ring-indigo-600 rounded-md shadow-sm mt-1 block w-full">
                        <option value="0">Flat</option>
                        <option value="1">Percent</option>
                    </select>
                    <x-input-error :messages="$errors->get('fees_type')" class="mt-2" />
                </div>

                <!-- Charge Amount -->
                <div>
                    <x-input-label for="edit_fees" value="{{ __('Charge amount') }}" />
                    <x-text-input id="edit_fees" name="fees" type="number" class="mt-1 block w-full" />
                    <x-input-error :messages="$errors->get('fees')" class="mt-2" />
                </div>

                <!-- Status -->
                <div class="md:col-span-2">
                    <x-input-label for="edit_status" value="{{ __('Status') }}" />
                    <select name="status" id="edit_status" class="border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 focus:border-indigo-500 dark:focus:border-indigo-600 focus:ring-indigo-500 dark:focus:ring-indigo-600 rounded-md shadow-sm mt-1 block w-full">
                        <option value="1">Active</option>
                        <option value="0">Inactive</option>
                    </select>
                    <x-input-error :messages="$errors->get('status')" class="mt-2" />
                </div>

                <!-- Brand Logo -->
                <div class="md:col-span-2">
                    <x-input-label for="edit_brand_logo" value="{{ __('Brand Image') }}" />
                    <input id="edit_brand_logo" type="file" name="brand_logo" class="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100"/>
                    <x-input-error :messages="$errors->get('brand_logo')" class="mt-2" />
                    <div id="current-logo" class="mt-2"></div>
                </div>
            </div>

            <div class="mt-6 flex justify-end">
                <x-secondary-button x-on:click="$dispatch('close')">
                    {{ __('Close') }}
                </x-secondary-button>

                <x-primary-button class="ml-3">
                    {{ __('Save Changes') }}
                </x-primary-button>
            </div>
        </form>
    </x-modal>


@endsection

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // --- Invoice Modal Functionality ---
            const invoiceModal = document.getElementById('invoiceModal');
            const closeInvoiceModalBtn = document.getElementById('closeInvoiceModalBtn');
            const cancelInvoiceBtn = document.getElementById('cancelInvoiceBtn');
            const invoiceForm = document.getElementById('invoiceForm');
            const openInvoiceModalBtn = document.getElementById('openInvoiceModalBtn'); // Moved inside

            if (openInvoiceModalBtn) {
                const openModal = () => {
                    invoiceForm.reset();
                    invoiceModal.style.display = 'flex';
                    document.body.style.overflow = 'hidden';
                };

                const closeModal = () => {
                    invoiceModal.style.display = 'none';
                    document.body.style.overflow = 'auto';
                };

                openInvoiceModalBtn.addEventListener('click', openModal);
                closeInvoiceModalBtn.addEventListener('click', closeModal);
                cancelInvoiceBtn.addEventListener('click', closeModal);

                invoiceModal.addEventListener('click', (event) => {
                    if (event.target === invoiceModal) {
                        closeModal();
                    }
                });

                document.addEventListener('keydown', (event) => {
                    if (event.key === 'Escape' && invoiceModal.style.display === 'flex') {
                        closeModal();
                    }
                });

                invoiceForm.addEventListener('submit', function(event) {
                    event.preventDefault();
                    const formData = new FormData(invoiceForm);
                    const saveBtn = document.getElementById('saveInvoiceBtn');
                    const saveBtnText = document.getElementById('saveInvoiceBtnText');
                    const originalBtnText = saveBtnText.innerText;

                    saveBtn.disabled = true;
                    saveBtnText.innerText = 'Saving...';

                    fetch(invoiceForm.action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value,
                            'Accept': 'application/json',
                        }
                    })
                    .then(response => response.json().then(data => ({ok: response.ok, data})))
                    .then(({ok, data}) => {
                        if (ok) {
                            showToast(data.message || 'Invoice created successfully!', 'success');
                            closeModal();
                        } else {
                            throw new Error(data.message || 'Failed to create invoice.');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showToast(error.message, 'error');
                    })
                    .finally(() => {
                        saveBtn.disabled = false;
                        saveBtnText.innerText = originalBtnText;
                    });
                });
            }

            // Edit brand modal functionality
            document.querySelectorAll('.edit-brand-btn').forEach(button => {
                button.addEventListener('click', function() {
                    const editUrl = this.dataset.editUrl;
                    const updateUrl = this.dataset.updateUrl;

                    // Show loading state
                    const originalText = this.innerHTML;
                    this.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Loading...';
                    this.disabled = true;

                    fetch(editUrl, {
                        method: 'GET',
                        headers: {
                            'Accept': 'application/json',
                        }
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then(data => {
                            const form = document.getElementById('edit-brand-form');
                            form.action = updateUrl;

                            // Populate form fields
                            document.getElementById('edit_brand_name').value = data.name || '';
                            document.getElementById('edit_mobile_number').value = data.mobile_number || '';
                            document.getElementById('edit_domain').value = data.domain || '';
                            document.getElementById('edit_whatsapp_number').value = data.whatsapp_number || '';
                            document.getElementById('edit_support_mail').value = data.support_mail || '';
                            document.getElementById('edit_fees_type').value = data.fees_type || '0';
                            document.getElementById('edit_fees').value = data.fees || '';
                            document.getElementById('edit_status').value = data.status || '1';

                            // Handle brand logo display
                            const currentLogoDiv = document.getElementById('current-logo');
                            if (data.brand_logo) {
                                currentLogoDiv.innerHTML = `
                                    <p class="text-sm text-gray-600 dark:text-gray-400">Current Logo:</p>
                                    <img src="${data.brand_logo}" alt="Current Logo" class="mt-1 h-16 w-16 object-cover rounded">
                                `;
                            } else {
                                currentLogoDiv.innerHTML = '<p class="text-sm text-gray-600 dark:text-gray-400">No logo uploaded</p>';
                            }

                            // Open modal using Alpine.js
                            window.dispatchEvent(new CustomEvent('open-modal', { detail: 'edit-brand-modal' }));
                        })
                        .catch(error => {
                            console.error('Error fetching brand data:', error);
                            showToast('Could not load brand data.', 'error');
                        })
                        .finally(() => {
                            // Restore button state
                            this.innerHTML = originalText;
                            this.disabled = false;
                        });
                });
            });

            // Handle Add Brand form submission with AJAX
            const addBrandForm = document.getElementById('add-brand-form');
            if (addBrandForm) {
                addBrandForm.addEventListener('submit', function(e) {
                    e.preventDefault();

                    const formData = new FormData(this);
                    const action = this.action;

                    fetch(action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value,
                            'Accept': 'application/json',
                        }
                    })
                    .then(response => {
                        if (!response.ok) {
                            return response.json().then(err => { throw err; });
                        }
                        if (response.headers.get('Content-Type')?.includes('application/json')) {
                            return response.json();
                        }
                        return { message: 'Brand added successfully!' };
                    })
                    .then(data => {
                        showToast(data.message || 'Brand added successfully!');
                        // Close modal
                        window.dispatchEvent(new CustomEvent('close-modal', {
                            detail: { name: 'add-brand-modal' }
                        }));
                        // Reload the page to show the new brand
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        if (error.message) {
                            showToast(error.message, 'error');
                        }
                        if (error.errors) {
                            // Clear previous errors
                            document.querySelectorAll('.input-error-message').forEach(el => el.remove());

                            // Display new validation errors
                            for (const field in error.errors) {
                                const input = document.querySelector(`[name="${field}"]`);
                                if (input) {
                                    const errorHtml = `<div class="text-sm text-red-600 dark:text-red-400 mt-2 input-error-message">${error.errors[field][0]}</div>`;
                                    input.insertAdjacentHTML('afterend', errorHtml);
                                }
                            }
                        }
                    });
                });
            }

            // Handle Edit Brand form submission with AJAX
            const editBrandForm = document.getElementById('edit-brand-form');
            if (editBrandForm) {
                editBrandForm.addEventListener('submit', function(e) {
                    e.preventDefault();

                    const formData = new FormData(this);
                    const action = this.action;

                    fetch(action, {
                        method: 'POST', // Form method spoofing handles PUT
                        body: formData,
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value,
                            'Accept': 'application/json',
                        }
                    })
                    .then(response => {
                        if (!response.ok) {
                            return response.json().then(err => { throw err; });
                        }
                        return response.json();
                    })
                    .then(data => {
                        showToast(data.message || 'Brand updated successfully!');
                        // Close modal
                        window.dispatchEvent(new CustomEvent('close-modal', {
                            detail: { name: 'edit-brand-modal' }
                        }));
                        setTimeout(() => window.location.reload(), 1000);
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        if (error.message) showToast(error.message, 'error');
                        if (error.errors) {
                            document.querySelectorAll('#edit-brand-form .input-error-message').forEach(el => el.remove());
                            for (const field in error.errors) {
                                const input = document.querySelector(`#edit-brand-form [name="${field}"]`);
                                if (input) {
                                    const errorHtml = `<div class="text-sm text-red-600 dark:text-red-400 mt-2 input-error-message">${error.errors[field][0]}</div>`;
                                    input.insertAdjacentHTML('afterend', errorHtml);
                                }
                            }
                        }
                    });
                });
            }

            // Toast notification function
            function showToast(message, type = 'success') {
                const toast = document.getElementById('toast');
                const toastMessage = document.getElementById('toast-message');

                toastMessage.textContent = message;
                toast.classList.remove('bg-green-500', 'bg-red-500', 'hidden');
                toast.classList.add(type === 'success' ? 'bg-green-500' : 'bg-red-500');

                setTimeout(() => {
                    toast.classList.add('hidden');
                }, 3000);
            }

            // Copy button functionality
            document.querySelectorAll('.my-copy-btn').forEach(button => {
                button.addEventListener('click', function() {
                    const input = this.parentElement.querySelector('.text-to-clipboard');
                    navigator.clipboard.writeText(input.value).then(() => {
                        showToast('Brand Key Copied Successfully');
                    }).catch(err => {
                        console.error('Failed to copy: ', err);
                        showToast('Failed to copy key.');
                    });
                });
            });

            // Toggle switch functionality
            document.querySelectorAll('.ajaxToggleItemStatus').forEach(toggle => {
                toggle.addEventListener('change', function() {
                    const id = this.dataset.id;
                    const status = this.checked ? 1 : 0;
                    const action = this.dataset.action;

                    // Disable the toggle to prevent multiple clicks
                    this.disabled = true;
                    const originalCheckedState = !this.checked;

                    fetch(action, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value,
                            'Accept': 'application/json',
                        },
                        body: JSON.stringify({ id: id, status: status })
                    })
                    .then(response => response.json().then(data => ({ok: response.ok, data})))
                    .then(({ok, data}) => {
                        if (ok) {
                            showToast(data.message || `Status updated to ${status ? 'Active' : 'Inactive'}`);
                            const statusBadge = document.getElementById(`status-badge-${id}`);
                            if (statusBadge) {
                                if (status) {
                                    statusBadge.innerHTML = `<small class="ml-2 bg-green-100 text-green-800 text-xs font-medium px-2.5 py-0.5 rounded-full dark:bg-green-900 dark:text-green-300">Active</small>`;
                                } else {
                                    statusBadge.innerHTML = `<small class="ml-2 bg-red-100 text-red-800 text-xs font-medium px-2.5 py-0.5 rounded-full dark:bg-red-900 dark:text-red-300">Inactive</small>`;
                                }
                            }
                        } else {
                            throw new Error(data.message || 'Failed to update status.');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showToast(error.message, 'error');
                        // Revert the switch on error
                        this.checked = originalCheckedState;
                    })
                    .finally(() => {
                        this.disabled = false; // Re-enable the toggle
                    });
                });
            });

            // AJAX functionality for resetting an item
            document.querySelectorAll('.ajaxResetItem').forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const confirmMessage = this.dataset.confirm_ms || 'reset this item';
                    const url = this.href;

                    if (confirm(`Are you sure you want to ${confirmMessage}?`)) {
                        fetch(url, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                                'Accept': 'application/json',
                            }
                        })
                        .then(response => response.json().then(data => ({ok: response.ok, data})))
                        .then(({ok, data}) => {
                            if (ok) {
                                showToast(data.message || 'Item reset successfully.');
                                document.getElementById(`brand-key-${data.brand_id}`).value = data.brand_key;
                            } else {
                                throw new Error(data.message || 'Failed to reset item.');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            showToast(error.message, 'error');
                        });
                    }
                });
            });

            // AJAX functionality for deleting an item
            document.querySelectorAll('.ajaxDeleteItem').forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const confirmMessage = this.dataset.confirm_ms || 'delete this item';
                    const url = this.dataset.url;
                    const row = this.closest('tr');

                    if (confirm(`Are you sure you want to ${confirmMessage}?`)) {
                        fetch(url, {
                            method: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value,
                                'Accept': 'application/json',
                            }
                        })
                        .then(response => response.json().then(data => ({ok: response.ok, data})))
                        .then(({ok, data}) => {
                            if (ok) {
                                showToast(data.message || 'Item deleted successfully.');
                                if (row) {
                                    row.remove();
                                }
                            } else {
                                throw new Error(data.message || 'Failed to delete item.');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            showToast(error.message, 'error');
                        });
                    }
                });
            });
        });
    </script>
@endpush
