@extends('layouts.admin')

@section('title', 'Debit Notes (Purchase Returns)')

@section('page-title', 'Debit Notes (Purchase Returns)')

@section('content')
<div class="max-w-[1400px] mx-auto">
    <!-- Header Section -->
    <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">Debit Notes (Purchase Returns)</h1>
        <div class="flex items-center gap-3">
            <form method="GET" action="{{ route('admin.debit-notes.index') }}" class="flex items-center">
                @if(request('search'))
                    <input type="hidden" name="search" value="{{ request('search') }}">
                @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', 10) == 10 ? 'selected' : '' }}>10 / page</option>
                    <option value="15" {{ request('per_page', 10) == 15 ? 'selected' : '' }}>15 / page</option>
                    <option value="25" {{ request('per_page', 10) == 25 ? 'selected' : '' }}>25 / page</option>
                    <option value="50" {{ request('per_page', 10) == 50 ? 'selected' : '' }}>50 / page</option>
                    <option value="100" {{ request('per_page', 10) == 100 ? 'selected' : '' }}>100 / page</option>
                </select>
            </form>
            <a href="{{ route('admin.debit-notes.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 Debit Note</span>
            </a>
        </div>
    </div>

    <!-- Search Bar -->
    <div class="mb-4">
        <form method="GET" action="{{ route('admin.debit-notes.index') }}" class="flex gap-2">
            @if(request('per_page'))
                <input type="hidden" name="per_page" value="{{ request('per_page') }}">
            @endif
            <input type="text" name="search" value="{{ request('search') }}" placeholder="Search..." class="flex-1 max-w-md 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">
            <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors">
                <span class="material-symbols-outlined">search</span>
            </button>
            @if(request('search'))
                <a href="{{ route('admin.debit-notes.index', ['per_page' => request('per_page')]) }}" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </a>
            @endif
        </form>
    </div>

    <!-- Debit Notes Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <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 w-16">#</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[150px]">DEBIT NOTE ID</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[150px]">PURCHASE ID</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[150px]">DEBIT NOTE DATE</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[200px]">SUPPLIER</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 min-w-[120px]">PAYMENT MODE</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[120px]">CREATED ON</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[100px]">STATUS</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right min-w-[100px]">ACTION</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @forelse($debitNotes as $index => $debitNote)
                        <tr class="group hover:bg-gray-50/50 transition-colors">
                            <td class="py-4 px-6 text-sm text-gray-600">{{ ($debitNotes->currentPage() - 1) * $debitNotes->perPage() + $index + 1 }}</td>
                            <td class="py-4 px-6">
                                <span class="text-sm font-medium text-gray-900">{{ $debitNote->debit_note_number }}</span>
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600">
                                @if($debitNote->purchase)
                                    <span class="font-medium">{{ $debitNote->purchase->purchase_number }}</span>
                                @else
                                    <span class="text-gray-400">-</span>
                                @endif
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600 whitespace-nowrap">
                                {{ $debitNote->debit_note_date ? $debitNote->debit_note_date->format('d-m-Y') : '-' }}
                            </td>
                            <td class="py-4 px-6">
                                @if($debitNote->supplier)
                                    <div class="flex items-center gap-2">
                                        <div class="size-8 rounded-full bg-primary flex items-center justify-center text-white font-bold text-xs shrink-0">
                                            @if($debitNote->supplier->image && Storage::disk('public')->exists($debitNote->supplier->image))
                                                <img src="{{ Storage::disk('public')->url($debitNote->supplier->image) }}" alt="{{ $debitNote->supplier->name }}" class="w-full h-full rounded-full object-cover">
                                            @else
                                                {{ strtoupper(substr($debitNote->supplier->name ?? 'N', 0, 1)) }}
                                            @endif
                                        </div>
                                        <span class="text-sm text-gray-900">{{ $debitNote->supplier->name }}</span>
                                    </div>
                                @else
                                    <span class="text-gray-400">-</span>
                                @endif
                            </td>
                            <td class="py-4 px-6 text-sm font-medium text-gray-900 text-right">
                                {{ \App\Models\Currency::formatAmount($debitNote->total, $debitNote->currency ?? null) }}
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600 capitalize">
                                {{ str_replace('_', ' ', $debitNote->payment_method ?? 'cash') }}
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600 whitespace-nowrap">
                                {{ $debitNote->created_at ? $debitNote->created_at->format('d-m-Y') : '-' }}
                            </td>
                            <td class="py-4 px-6">
                                @php
                                    $statusColors = [
                                        'draft' => 'bg-gray-100 text-gray-700',
                                        'pending' => 'bg-yellow-100 text-yellow-700',
                                        'approved' => 'bg-green-100 text-green-700',
                                        'rejected' => 'bg-red-100 text-red-700',
                                        'completed' => 'bg-blue-100 text-blue-700',
                                    ];
                                    $statusColor = $statusColors[$debitNote->status] ?? 'bg-gray-100 text-gray-700';
                                @endphp
                                <span class="px-2 py-1 text-xs font-medium rounded-full {{ $statusColor }}">
                                    {{ ucfirst($debitNote->status) }}
                                </span>
                            </td>
                            <td class="py-4 px-6 text-right">
                                <div class="relative inline-block">
                                    <button type="button" data-admin-fixed-menu-trigger="action-menu-{{ $debitNote->id }}" onclick="adminFixedActionMenuToggle(event || window.event, 'action-menu-{{ $debitNote->id }}')" class="text-gray-400 hover:text-gray-600 transition-colors" title="More actions">
                                        <span class="material-symbols-outlined text-xl">more_vert</span>
                                    </button>
                                    <div id="action-menu-{{ $debitNote->id }}" data-admin-fixed-action-menu class="hidden w-48 bg-white rounded-lg shadow-lg border border-gray-200">
                                        <div class="py-1">
                                            <a href="{{ route('admin.debit-notes.show', $debitNote) }}" 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">visibility</span>
                                                <span>View</span>
                                            </a>
                                            <a href="{{ route('admin.debit-notes.edit', $debitNote) }}" 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>
                                            <div class="border-t border-gray-100 my-1"></div>
                                            <button type="button" onclick="openDeleteModal({{ $debitNote->id }}, {{ json_encode($debitNote->debit_note_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</span>
                                <p>No debit notes found</p>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if($debitNotes->hasPages())
            <div class="px-6 py-4 border-t border-gray-200 flex flex-col sm:flex-row items-center justify-between gap-4">
                <p class="text-sm text-gray-500">
                    Showing <span class="font-medium text-gray-900">{{ $debitNotes->firstItem() }}</span> to <span class="font-medium text-gray-900">{{ $debitNotes->lastItem() }}</span> of <span class="font-medium text-gray-900">{{ $debitNotes->total() }}</span> entries
                </p>
                <div class="flex items-center gap-1">
                    @if($debitNotes->onFirstPage())
                        <button disabled class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                            <
                        </button>
                    @else
                        <a href="{{ $debitNotes->previousPageUrl() }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">
                            <
                        </a>
                    @endif
                    
                    @php
                        $currentPage = $debitNotes->currentPage();
                        $lastPage = $debitNotes->lastPage();
                        $startPage = max(1, $currentPage - 1);
                        $endPage = min($lastPage, $currentPage + 1);
                    @endphp
                    
                    @if($startPage > 1)
                        <a href="{{ $debitNotes->url(1) }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">1</a>
                        @if($startPage > 2)
                            <span class="px-3 py-1 text-sm text-gray-500">...</span>
                        @endif
                    @endif
                    
                    @for($page = $startPage; $page <= $endPage; $page++)
                        <a href="{{ $debitNotes->url($page) }}" class="px-3 py-1 text-sm rounded {{ $page == $currentPage ? 'bg-primary text-white' : 'text-gray-500 hover:bg-gray-50' }}">
                            {{ $page }}
                        </a>
                    @endfor
                    
                    @if($endPage < $lastPage)
                        @if($endPage < $lastPage - 1)
                            <span class="px-3 py-1 text-sm text-gray-500">...</span>
                        @endif
                        <a href="{{ $debitNotes->url($lastPage) }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">{{ $lastPage }}</a>
                    @endif
                    
                    @if($debitNotes->hasMorePages())
                        <a href="{{ $debitNotes->nextPageUrl() }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">
                            >
                        </a>
                    @else
                        <button disabled class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                            >
                        </button>
                    @endif
                </div>
            </div>
        @else
            <div class="px-6 py-4 border-t border-gray-200 flex flex-col sm:flex-row items-center justify-between gap-4">
                <p class="text-sm text-gray-500">
                    Showing <span class="font-medium text-gray-900">0</span> to <span class="font-medium text-gray-900">0</span> of <span class="font-medium text-gray-900">0</span> entries
                </p>
            </div>
        @endif
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="deleteModal" data-admin-modal class="fixed inset-0 bg-black/50 backdrop-blur-sm z-[100] hidden items-center justify-center p-4" role="dialog" aria-modal="true" onclick="if(event.target===this) closeDeleteModal()">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md" onclick="event.stopPropagation()">
        <div class="p-6">
            <div class="flex items-start gap-3 mb-4">
                <div class="flex-shrink-0 flex h-10 w-10 items-center justify-center rounded-full bg-red-100">
                    <span class="material-symbols-outlined text-red-600">warning</span>
                </div>
                <div class="flex-1 min-w-0">
                    <h3 class="text-lg font-semibold text-gray-900">Delete debit note</h3>
                    <p class="text-sm text-gray-600 mt-2">Are you sure you want to delete <span id="delete-debit-note-number" class="font-medium text-gray-900"></span>? This cannot be undone.</p>
                </div>
            </div>
            <div class="flex items-center justify-end gap-3">
                <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>
                <form id="delete-form" method="POST" class="inline">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="px-4 py-2 text-sm text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors">
                        Delete
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Deleted successfully -->
<div id="debitNoteDeleteSuccessModal" class="hidden fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" role="dialog" aria-modal="true" onclick="if(event.target===this) closeDebitNoteDeleteSuccessModal()">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md" onclick="event.stopPropagation()">
        <div class="p-6">
            <div class="flex items-start gap-3">
                <div class="flex-shrink-0 flex h-10 w-10 items-center justify-center rounded-full bg-emerald-100">
                    <span class="material-symbols-outlined text-emerald-600 text-2xl">check_circle</span>
                </div>
                <div class="flex-1">
                    <h3 class="text-lg font-semibold text-gray-900">Deleted successfully</h3>
                    <p class="text-sm text-gray-600 mt-2" id="debit-note-delete-success-message"></p>
                </div>
            </div>
            <div class="flex justify-end mt-6">
                <button type="button" onclick="closeDebitNoteDeleteSuccessModal()" class="px-4 py-2 text-sm font-medium text-white bg-primary rounded-lg hover:bg-blue-600">OK</button>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
const debitNoteDestroyUrl = @json(rtrim(route('admin.debit-notes.index'), '/'));

function openDeleteModal(id, debitNoteNumber) {
    document.getElementById('delete-debit-note-number').textContent = debitNoteNumber || '';
    document.getElementById('delete-form').action = debitNoteDestroyUrl + '/' + id;
    document.getElementById('deleteModal').classList.remove('hidden');
    document.getElementById('deleteModal').classList.add('flex');
}

function closeDeleteModal() {
    document.getElementById('deleteModal').classList.add('hidden');
    document.getElementById('deleteModal').classList.remove('flex');
}

function closeDebitNoteDeleteSuccessModal() {
    const el = document.getElementById('debitNoteDeleteSuccessModal');
    if (el) el.classList.add('hidden');
}

@if(session('debit_note_deleted'))
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('debitNoteDeleteSuccessModal');
    const msg = document.getElementById('debit-note-delete-success-message');
    if (modal && msg) {
        msg.textContent = @json(session('debit_note_deleted'));
        modal.classList.remove('hidden');
    }
});
@endif
</script>
@endpush
@endsection
