@extends('layouts.app')
@php($prefix = auth()->user()->role === 'admin' ? 'admin.' : 'user.')
@section('content')
@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

<!-- 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>

<div class="container mx-auto px-4 sm:px-8">
    <div class="py-8">
        {{-- Success message on invoice creation --}}
        @if (request()->has('created') && request()->get('created') == 'true')
        <div id="invoice-created-success"
            class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-4 rounded-md shadow-md" role="alert">
            <div class="flex">
                <div class="py-1"><i class="fas fa-check-circle fa-2x text-green-500 mr-3"></i></div>
                <div>
                    <p class="font-bold">Success!</p>
                    <p class="text-sm">The new invoice has been created successfully.</p>
                </div>
            </div>
        </div>
        @endif
        <div>
            <h2 class="text-2xl font-semibold leading-tight text-gray-800 dark:text-white">Invoices</h2>
        </div>
        <div class="flex justify-end mb-4">
            <a href="{{ route($prefix . 'invoices.create') }}"
                class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-black  dark:hover:bg-black">
                <i class="fas fa-plus -ml-1 mr-2"></i>
                Create New Invoice
            </a>
        </div>

        <form action="{{ route($prefix . 'invoices.index') }}" method="GET" class="my-2 flex sm:flex-row flex-col">
            <div class="flex flex-row mb-1 sm:mb-0">
                {{-- Future filter options can go here --}}
            </div>
            <div class="block relative">
                <span class="h-full absolute inset-y-0 left-0 flex items-center pl-2">
                    <svg viewBox="0 0 24 24" class="h-4 w-4 fill-current text-gray-500">
                        <path
                            d="M10 4a6 6 0 100 12 6 6 0 000-12zm-8 6a8 8 0 1114.32 4.906l5.387 5.387a1 1 0 01-1.414 1.414l-5.387-5.387A8 8 0 012 10z">
                        </path>
                    </svg>
                </span>
                <input placeholder="Search by Invoice # or Customer" name="search" value="{{ request('search') }}"
                    class="appearance-none rounded-r rounded-l sm:rounded-l-none border border-gray-400 border-b block pl-8 pr-6 py-2 w-full bg-white text-sm placeholder-gray-400 text-gray-700 focus:bg-white focus:placeholder-gray-600 focus:text-gray-700 focus:outline-none" />
            </div>
            <button type="submit" class="ml-2 px-4 py-2 bg-black text-white rounded-md text-sm">Search</button>
        </form>

        <div class="-mx-4 sm:-mx-8 px-4 sm:px-8 py-4">
            <div class="inline-block min-w-full shadow rounded-lg overflow-x-auto">
                <table class="min-w-full leading-normal bg-white dark:bg-gray-800">
                    <thead>
                        <tr>
                            <th
                                class="px-5 py-3 border-b-2 border-gray-200 dark:border-gray-700 text-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider">
                                Invoice ID
                            </th>
                            <th
                                class="px-5 py-3 border-b-2 border-gray-200 dark:border-gray-700 text-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider">
                                Customer
                            </th>
                            <th
                                class="px-5 py-3 border-b-2 border-gray-200 dark:border-gray-700 text-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider">
                                Date
                            </th>
                            <th
                                class="px-5 py-3 border-b-2 border-gray-200 dark:border-gray-700 text-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider">
                                Amount
                            </th>
                            <th
                                class="px-5 py-3 border-b-2 border-gray-200 dark:border-gray-700 text-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider">
                                Status
                            </th>
                            <th
                                class="px-5 py-3 border-b-2 border-gray-200 dark:border-gray-700 text-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider">
                                Action
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse ($invoices as $invoice)
                        <tr>
                            <td class="px-5 py-5 border-b border-gray-200 dark:border-gray-700 text-sm">
                                <div class="flex items-center">
                                    <div class="flex-grow pr-2">
                                        <p class="text-gray-900 dark:text-white whitespace-no-wrap font-semibold">{{ $invoice->invoice_number }}</p>
                                        {{-- This hidden p tag holds the URL for the copy button. Passing the full object is cleaner. --}}
                                        <p class="hidden" id="invoice-url-{{ $invoice->id }}">{{ route('invoice.public.show', $invoice) }}</p>
                                        <p class="text-gray-600 dark:text-gray-400 whitespace-no-wrap text-xs">
                                            {{ $invoice->brand->name }}
                                        </p>
                                    </div>
                                    <button class="flex-shrink-0 p-2 rounded-full text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-700 copy-btn" data-clipboard-target="#invoice-url-{{ $invoice->id }}" title="Copy Public Invoice URL">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                            </td>
                            <td class="px-5 py-5 border-b border-gray-200 dark:border-gray-700 text-sm">
                                <p class="text-gray-900 dark:text-white whitespace-no-wrap">
                                    {{ $invoice->customer_name }}
                                </p>
                                <p class="text-gray-600 dark:text-gray-400 whitespace-no-wrap">
                                    {{ $invoice->customer_email }}</p>
                            </td>
                            <td class="px-5 py-5 border-b border-gray-200 dark:border-gray-700 text-sm">
                                <p class="text-gray-900 dark:text-white whitespace-no-wrap">
                                    {{ $invoice->created_at->format('d M, Y') }}</p>
                                <p class="text-gray-600 dark:text-gray-400 whitespace-no-wrap">Due:
                                    {{ $invoice->due_date->format('d M, Y') }}</p>
                            </td>
                            <td class="px-5 py-5 border-b border-gray-200 dark:border-gray-700 text-sm">
                                <div class="flex items-center">
                                    <p class="text-gray-900 dark:text-white whitespace-no-wrap">
                                        {{ number_format($invoice->amount, 2) }} BDT
                                    </p>
                                    <span class="ml-2 px-2 inline-flex text-xs leading-5 font-semibold rounded-full
                                        @if($invoice->payment_status == 'paid') bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300 @endif
                                        @if($invoice->payment_status == 'pending') bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300 @endif
                                        @if($invoice->payment_status == 'unpaid') bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300 @endif">
                                        {{ ucfirst($invoice->payment_status) }}
                                    </span>
                                </div>
                            </td>
                            <td class="px-5 py-5 border-b border-gray-200 dark:border-gray-700 text-sm">
                                <label class="custom-switch">
                                    <input type="checkbox"
                                           class="custom-switch-input ajaxToggleItemStatus"
                                           data-id="{{ $invoice->id }}"
                                           data-action="{{ route($prefix . 'invoices.toggleStatus') }}"
                                           @checked($invoice->status)>
                                    <span class="custom-switch-indicator"></span>
                                </label>
                            </td>
                            <td class="px-5 py-5 border-b border-gray-200 dark:border-gray-700 text-sm text-right">
                                <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">
                                        <a href="{{ route($prefix . 'invoices.show', $invoice->id) }}" class="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-eye mr-2"></i> View
                                        </a>
                                        <a href="{{ route($prefix . 'invoices.edit', $invoice->id) }}" class="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
                                        </a>
                                        <form action="{{ route($prefix . 'invoices.destroy', $invoice->id) }}" method="POST" onsubmit="return confirm('Are you sure you want to delete this invoice?');">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="block w-full px-4 py-2 text-left text-sm leading-5 text-red-600 dark:text-red-400 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-trash mr-2"></i> Delete
                                            </button>
                                        </form>
                                    </x-slot>
                                </x-dropdown>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="6" class="px-5 py-5 border-b border-gray-200 dark:border-gray-700 text-center text-sm">
                                <p class="text-gray-500 dark:text-gray-400">No invoices found matching your search.</p>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.copy-btn').forEach(button => {
        button.addEventListener('click', function() {
            const targetSelector = this.getAttribute('data-clipboard-target');
            const elementToCopy = document.querySelector(targetSelector);
            const urlToCopy = elementToCopy.innerText;

            navigator.clipboard.writeText(urlToCopy).then(() => {
                showToast('Payment URL copied successfully!');
            }).catch(err => {
                console.error('Failed to copy: ', err);
                showToast('Failed to copy URL.', 'error');
            });
        });
    });
});
document.addEventListener('DOMContentLoaded', function() {
    // 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);
    }

    // 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;
            this.disabled = true;
            const originalCheckedState = !this.checked;

            fetch(action, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                            .getAttribute('content'),
                        '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 successfully`);
                        const statusBadge = document.getElementById(`status-badge-${id}`);
                        if (statusBadge) {
                            statusBadge.innerHTML = 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>` :
                                `<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');
                    this.checked = originalCheckedState; // Revert switch on error
                })
                .finally(() => {
                    this.disabled = false;
                });
        });
    });
});
</script>
@endpush