@extends('layouts.admin')

@section('title', 'Expenses')

@section('page-title', 'Expenses')

@section('breadcrumbs')
    <span class="text-primary font-medium">Expenses</span>
@endsection

@section('content')
<div class="max-w-[1400px] mx-auto">
    <!-- Header -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <h1 class="text-2xl font-bold text-gray-900 text-gray-900">Expenses</h1>
        <div class="flex items-center gap-3">
            <a href="{{ route('admin.expenses.create') }}" class="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium shadow-lg shadow-primary/30 hover:bg-blue-600 transition-colors">
                <span class="material-symbols-outlined text-lg">add</span>
                <span>New Expense</span>
            </a>
            <form method="GET" action="{{ route('admin.expenses.index') }}" class="inline">
                @if(request('search'))
                    <input type="hidden" name="search" value="{{ request('search') }}">
                @endif
                @if(request('status'))
                    <input type="hidden" name="status" value="{{ request('status') }}">
                @endif
                <select name="per_page" onchange="this.form.submit()" class="px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-primary">
                    <option value="10" {{ request('per_page', 15) == 10 ? 'selected' : '' }}>10 / page</option>
                    <option value="15" {{ request('per_page', 15) == 15 ? 'selected' : '' }}>15 / page</option>
                    <option value="25" {{ request('per_page', 15) == 25 ? 'selected' : '' }}>25 / page</option>
                    <option value="50" {{ request('per_page', 15) == 50 ? 'selected' : '' }}>50 / page</option>
                    <option value="100" {{ request('per_page', 15) == 100 ? 'selected' : '' }}>100 / page</option>
                </select>
            </form>
        </div>
    </div>

    <!-- Search and Filters -->
    <form method="GET" action="{{ route('admin.expenses.index') }}" class="mb-4">
        <div class="flex flex-col sm:flex-row gap-4">
            <div class="flex-1">
                <input type="text" name="search" value="{{ $search ?? '' }}" placeholder="Search by expense number, category, or description..." class="w-full h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary">
            </div>
            <div class="flex gap-2">
                <select name="status" class="h-10 px-3 rounded-lg border border-gray-200 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary">
                    <option value="">All Statuses</option>
                    <option value="draft" {{ request('status') == 'draft' ? 'selected' : '' }}>Draft</option>
                    <option value="approved" {{ request('status') == 'approved' ? 'selected' : '' }}>Approved</option>
                    <option value="paid" {{ request('status') == 'paid' ? 'selected' : '' }}>Paid</option>
                    <option value="rejected" {{ request('status') == 'rejected' ? 'selected' : '' }}>Rejected</option>
                </select>
                <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-blue-600 transition-colors">
                    Filter
                </button>
                @if(request()->hasAny(['search', 'status']))
                    <a href="{{ route('admin.expenses.index') }}" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-50 transition-colors">
                        Clear
                    </a>
                @endif
            </div>
        </div>
    </form>

    <!-- Expenses Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 relative">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">#</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Expense #</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Vendor</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Account</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Category</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Date</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right min-w-[120px]">Amount</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Payment Method</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Status</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @forelse($expenses ?? [] as $expense)
                    <tr class="group hover:bg-gray-50/50 transition-colors">
                        <td class="py-4 px-6 text-sm text-gray-600">{{ $expenses->firstItem() + $loop->index ?? $loop->iteration }}</td>
                        <td class="py-4 px-6">
                            <a href="{{ route('admin.expenses.show', $expense->id) }}" class="text-sm font-medium text-primary hover:underline">
                                {{ $expense->expense_number }}
                            </a>
                        </td>
                        <td class="py-4 px-6">
                            @if($expense->vendor)
                                <div class="flex items-center gap-3">
                                    <div class="size-8 rounded-full bg-primary flex items-center justify-center text-white font-bold text-xs shrink-0">
                                        @if($expense->vendor->image && \Illuminate\Support\Facades\Storage::disk('public')->exists($expense->vendor->image))
                                            <img src="{{ \Illuminate\Support\Facades\Storage::disk('public')->url($expense->vendor->image) }}" alt="{{ $expense->vendor->name }}" class="w-full h-full rounded-full object-cover" onerror="this.style.display='none'; this.parentElement.innerHTML='{{ strtoupper(substr($expense->vendor->name ?? 'N', 0, 1)) }}';">
                                        @else
                                            {{ strtoupper(substr($expense->vendor->name ?? 'N', 0, 1)) }}
                                        @endif
                                    </div>
                                    <span class="text-sm font-medium text-gray-900">{{ $expense->vendor->name }}</span>
                                </div>
                            @else
                                <span class="text-sm text-gray-400">-</span>
                            @endif
                        </td>
                        <td class="py-4 px-6 text-sm text-gray-600">
                            {{ $expense->account ? $expense->account->code . ' - ' . $expense->account->name : '-' }}
                        </td>
                        <td class="py-4 px-6 text-sm text-gray-600">{{ $expense->category ?? '-' }}</td>
                        <td class="py-4 px-6 text-sm text-gray-600">
                            {{ $expense->expense_date ? $expense->expense_date->format('M d, Y') : '-' }}
                        </td>
                        <td class="py-4 px-6 text-sm font-medium text-gray-900 text-right">
                            {{ \App\Models\Currency::formatAmount($expense->amount ?? 0, $expense->currency) }}
                        </td>
                        <td class="py-4 px-6 text-sm text-gray-600">
                            <span class="capitalize">{{ str_replace('_', ' ', $expense->payment_method ?? '-') }}</span>
                        </td>
                        <td class="py-4 px-6">
                            @php
                                $statusColors = [
                                    'draft' => 'bg-gray-100 text-gray-800',
                                    'approved' => 'bg-blue-100 text-blue-800',
                                    'paid' => 'bg-green-100 text-green-800',
                                    'rejected' => 'bg-red-100 text-red-800',
                                ];
                                $statusColor = $statusColors[$expense->status ?? 'draft'] ?? 'bg-gray-100 text-gray-800';
                            @endphp
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $statusColor }}">
                                {{ ucfirst($expense->status ?? 'draft') }}
                            </span>
                        </td>
                        <td class="py-4 px-6 text-right">
                            <div class="relative inline-block">
                                <button onclick="toggleActionMenu({{ $expense->id }}, event)" class="text-gray-400 hover:text-gray-600 transition-colors" title="More actions" data-action-button="{{ $expense->id }}">
                                    <span class="material-symbols-outlined text-xl">more_vert</span>
                                </button>
                                <div id="action-menu-{{ $expense->id }}" class="hidden fixed w-48 bg-white rounded-lg shadow-xl border border-gray-200" style="z-index: 9999; display: none;">
                                    <div class="py-1">
                                        <a href="{{ route('admin.expenses.show', $expense->id) }}" class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors">
                                            <span class="material-symbols-outlined text-base">preview</span>
                                            <span>View</span>
                                        </a>
                                        <a href="{{ route('admin.expenses.edit', $expense->id) }}" class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors">
                                            <span class="material-symbols-outlined text-base">edit</span>
                                            <span>Edit</span>
                                        </a>
                                        <a href="{{ route('admin.expenses.show', $expense->id) }}#expense-status" class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors">
                                            <span class="material-symbols-outlined text-base">toggle_on</span>
                                            <span>Change status</span>
                                        </a>
                                        <div class="border-t border-gray-100 my-1"></div>
                                        <button onclick="openDeleteModal({{ $expense->id }}, '{{ $expense->expense_number }}')" class="w-full flex items-center gap-2 px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors text-left">
                                            <span class="material-symbols-outlined text-base">delete</span>
                                            <span>Delete</span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="10" class="py-12 px-6 text-center text-gray-500">
                            <span class="material-symbols-outlined text-4xl mb-2 block">receipt_long</span>
                            <p>No expenses found</p>
                            @if(request()->hasAny(['search', 'status']))
                                <a href="{{ route('admin.expenses.index') }}" class="mt-2 text-primary hover:underline">Clear filters</a>
                            @else
                                <a href="{{ route('admin.expenses.create') }}" class="mt-2 text-primary hover:underline">Create your first expense</a>
                            @endif
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if(isset($expenses) && method_exists($expenses, 'hasPages') && $expenses->hasPages())
        <div class="px-6 py-4 border-t border-gray-200">
            {{ $expenses->links() }}
        </div>
        @endif
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="delete-expense-modal" data-admin-modal class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden items-center justify-center">
    <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4" onclick="event.stopPropagation()">
        <div class="p-6">
            <div class="flex items-center gap-4 mb-4">
                <div class="flex-shrink-0 w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
                    <span class="material-symbols-outlined text-red-600 text-2xl">warning</span>
                </div>
                <div>
                    <h3 class="text-lg font-bold text-gray-900">Delete Expense</h3>
                    <p class="text-sm text-gray-500">This action cannot be undone</p>
                </div>
            </div>
            <p class="text-sm text-gray-700 mb-6">
                Are you sure you want to delete expense <span id="delete-expense-number" class="font-semibold"></span>? This will permanently remove the expense and all associated data.
            </p>
            <form id="delete-expense-form" method="POST" class="flex items-center justify-end gap-3">
                @csrf
                @method('DELETE')
                <button type="button" onclick="closeDeleteModal()" class="px-4 py-2 text-sm text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                    Cancel
                </button>
                <button type="submit" class="px-4 py-2 text-sm text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors">
                    Delete Expense
                </button>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script>
// Store original parent for each menu to restore later
const menuParents = new Map();

function toggleActionMenu(id, event) {
    event.stopPropagation();
    event.preventDefault();
    
    const button = event.currentTarget;
    const menu = document.getElementById('action-menu-' + id);
    const allMenus = document.querySelectorAll('[id^="action-menu-"]');
    
    // Close all other menus first
    allMenus.forEach(m => {
        if (m.id !== 'action-menu-' + id) {
            closeMenu(m);
        }
    });
    
    // Toggle current menu
    if (menu.classList.contains('hidden') || menu.style.display === 'none') {
        openMenu(menu, button);
    } else {
        closeMenu(menu);
    }
}

function openMenu(menu, button) {
    // Store original parent if not already stored
    if (!menuParents.has(menu.id)) {
        menuParents.set(menu.id, menu.parentElement);
    }
    
    // Get button position relative to viewport
    const buttonRect = button.getBoundingClientRect();
    
    // Calculate if menu should appear above or below button
    const spaceBelow = window.innerHeight - buttonRect.bottom;
    const spaceAbove = buttonRect.top;
    const menuHeight = 130; // Approximate menu height
    
    // Move menu to body to escape overflow clipping (portal-like behavior)
    if (menu.parentElement !== document.body) {
        document.body.appendChild(menu);
    }
    
    // Position menu as fixed to escape overflow clipping
    menu.style.position = 'fixed';
    menu.style.zIndex = '9999';
    menu.style.display = 'block';
    
    if (spaceBelow >= menuHeight || spaceBelow > spaceAbove) {
        // Position below button
        menu.style.top = (buttonRect.bottom + 8) + 'px';
        menu.style.bottom = 'auto';
    } else {
        // Position above button
        menu.style.bottom = (window.innerHeight - buttonRect.top + 8) + 'px';
        menu.style.top = 'auto';
    }
    
    // Align to right edge of button, but ensure it doesn't go off-screen
    const menuWidth = 192; // w-48 = 192px
    const rightPosition = window.innerWidth - buttonRect.right;
    const leftPosition = buttonRect.left;
    
    if (rightPosition + menuWidth > window.innerWidth) {
        // If menu would overflow, align to left edge instead
        menu.style.left = Math.max(8, leftPosition) + 'px';
        menu.style.right = 'auto';
    } else {
        menu.style.right = rightPosition + 'px';
        menu.style.left = 'auto';
    }
    
    menu.classList.remove('hidden');
}

function closeMenu(menu) {
    menu.classList.add('hidden');
    menu.style.display = 'none';
    
    // Restore menu to original parent if stored
    const originalParent = menuParents.get(menu.id);
    if (originalParent && menu.parentElement === document.body) {
        originalParent.appendChild(menu);
    }
    
    // Reset positioning styles
    menu.style.position = '';
    menu.style.top = '';
    menu.style.right = '';
    menu.style.left = '';
    menu.style.bottom = '';
    menu.style.zIndex = '';
}

// Close menus when clicking outside
document.addEventListener('click', function(e) {
    // Check if click is outside any menu or action button
    const clickedMenu = e.target.closest('[id^="action-menu-"]');
    const clickedButton = e.target.closest('button[data-action-button]') || e.target.closest('button[onclick*="toggleActionMenu"]');
    
    if (!clickedMenu && !clickedButton) {
        document.querySelectorAll('[id^="action-menu-"]').forEach(menu => {
            closeMenu(menu);
        });
    }
});

// Close menus on scroll
window.addEventListener('scroll', function() {
    document.querySelectorAll('[id^="action-menu-"]:not(.hidden)').forEach(menu => {
        if (menu.style.display !== 'none') {
            closeMenu(menu);
        }
    });
}, true);

function openDeleteModal(id, expenseNumber) {
    document.getElementById('delete-expense-number').textContent = expenseNumber;
    document.getElementById('delete-expense-form').action = '{{ route("admin.expenses.index") }}/' + id;
    document.getElementById('delete-expense-modal').classList.remove('hidden');
    document.getElementById('delete-expense-modal').classList.add('flex');
}

function closeDeleteModal() {
    document.getElementById('delete-expense-modal').classList.add('hidden');
    document.getElementById('delete-expense-modal').classList.remove('flex');
}

// Close modal when clicking outside
document.getElementById('delete-expense-modal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeDeleteModal();
    }
});
</script>
@endpush
@endsection




