@extends('layouts.admin')

@section('title', 'Suppliers Payments')

@section('page-title', 'Suppliers Payments')

@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">Suppliers Payments</h1>
        <div class="flex items-center gap-3">
            <form method="GET" action="{{ route('admin.supplier-payments.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>
            <button type="button" onclick="openPaymentModal()" 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 Payment</span>
            </button>
        </div>
    </div>

    <!-- Search Bar -->
    <div class="mb-4">
        <form method="GET" action="{{ route('admin.supplier-payments.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 by payment number, reference, supplier, or purchase..." 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.supplier-payments.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>

    <!-- Payments 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]">PAYMENT NUMBER</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]">SUPPLIER</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[120px]">PAYMENT DATE</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right min-w-[120px]">PAID AMOUNT</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right min-w-[120px]">DUE AMOUNT</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[150px]">PAYMENT SOURCE</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($payments as $index => $payment)
                        <tr class="group hover:bg-gray-50/50 transition-colors">
                            <td class="py-4 px-6 text-sm text-gray-600">{{ ($payments->currentPage() - 1) * $payments->perPage() + $index + 1 }}</td>
                            <td class="py-4 px-6">
                                <span class="text-sm font-medium text-gray-900">{{ $payment->payment_number }}</span>
                                @if($payment->reference_number)
                                    <span class="text-xs text-gray-500 block">{{ $payment->reference_number }}</span>
                                @endif
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600">
                                @if($payment->purchase)
                                    <span class="font-medium">{{ $payment->purchase->purchase_number }}</span>
                                @else
                                    <span class="text-gray-400">-</span>
                                @endif
                            </td>
                            <td class="py-4 px-6">
                                @if($payment->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($payment->supplier->image && Storage::disk('public')->exists($payment->supplier->image))
                                                <img src="{{ Storage::disk('public')->url($payment->supplier->image) }}" alt="{{ $payment->supplier->name }}" class="w-full h-full rounded-full object-cover">
                                            @else
                                                {{ strtoupper(substr($payment->supplier->name ?? 'N', 0, 1)) }}
                                            @endif
                                        </div>
                                        <span class="text-sm text-gray-900">{{ $payment->supplier->name }}</span>
                                    </div>
                                @else
                                    <span class="text-gray-400">-</span>
                                @endif
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600 whitespace-nowrap">
                                {{ $payment->payment_date ? $payment->payment_date->format('d-m-Y') : '-' }}
                            </td>
                            <td class="py-4 px-6 text-sm font-medium text-gray-900 text-right">
                                {{ \App\Models\Currency::formatAmount($payment->paid_amount, $payment->currency ?? null) }}
                            </td>
                            <td class="py-4 px-6 text-sm font-medium text-right">
                                <span class="{{ $payment->due_amount > 0 ? 'text-red-600' : 'text-green-600' }}">
                                    {{ \App\Models\Currency::formatAmount($payment->due_amount, $payment->currency ?? null) }}
                                </span>
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600">
                                {{ $payment->payment_source ?? '-' }}
                            </td>
                            <td class="py-4 px-6 text-right">
                                <div class="relative inline-block">
                                    <button type="button" data-admin-fixed-menu-trigger="action-menu-{{ $payment->id }}" onclick="adminFixedActionMenuToggle(event || window.event, 'action-menu-{{ $payment->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-{{ $payment->id }}" data-admin-fixed-action-menu class="hidden w-48 bg-white rounded-lg shadow-lg border border-gray-200">
                                        <div class="py-1">
                                            @if($payment->attachment)
                                                <a href="{{ Storage::disk('public')->url($payment->attachment) }}" target="_blank" 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">download</span>
                                                    <span>Download Attachment</span>
                                                </a>
                                                <div class="border-t border-gray-100 my-1"></div>
                                            @endif
                                            <button onclick="openDeleteModal({{ $payment->id }}, '{{ $payment->payment_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="9" class="py-12 px-6 text-center text-gray-500">
                                <span class="material-symbols-outlined text-4xl mb-2 block">receipt</span>
                                <p>No payments found</p>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if($payments->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">{{ $payments->firstItem() }}</span> to <span class="font-medium text-gray-900">{{ $payments->lastItem() }}</span> of <span class="font-medium text-gray-900">{{ $payments->total() }}</span> entries
                </p>
                <div class="flex items-center gap-1">
                    @if($payments->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="{{ $payments->previousPageUrl() }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">
                            <
                        </a>
                    @endif
                    
                    @php
                        $currentPage = $payments->currentPage();
                        $lastPage = $payments->lastPage();
                        $startPage = max(1, $currentPage - 1);
                        $endPage = min($lastPage, $currentPage + 1);
                    @endphp
                    
                    @if($startPage > 1)
                        <a href="{{ $payments->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="{{ $payments->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="{{ $payments->url($lastPage) }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">{{ $lastPage }}</a>
                    @endif
                    
                    @if($payments->hasMorePages())
                        <a href="{{ $payments->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>
        @endif
    </div>
</div>

<!-- Add New Payment Modal -->
<div id="paymentModal" data-admin-modal class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden items-center justify-center p-4 overflow-y-auto">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-3xl max-h-[min(90vh,calc(100vh-2rem))] min-h-0 flex flex-col overflow-hidden my-auto">
        <!-- Modal Header -->
        <div class="flex-shrink-0 flex items-center justify-between p-6 border-b border-gray-200">
            <h2 class="text-xl font-semibold text-gray-900">Add New Payment</h2>
            <button type="button" onclick="closePaymentModal()" class="text-gray-400 hover:text-gray-600 transition-colors">
                <span class="material-symbols-outlined text-2xl">close</span>
            </button>
        </div>

        <!-- Modal Body: scroll fields only; footer stays visible -->
        <form id="payment-form" class="flex flex-col flex-1 min-h-0">
            @csrf
            <div class="flex-1 min-h-0 overflow-y-auto overscroll-contain p-6 space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Purchase ID, Payment Date, and Reference Number - 3 Column Row -->
                <div class="md:col-span-2 grid grid-cols-1 md:grid-cols-3 gap-4">
                    <!-- Purchase ID -->
                    <div>
                        <label for="purchase_id" class="block text-sm font-medium text-gray-700 mb-2">Purchase ID <span class="text-red-500">*</span></label>
                        <div class="relative">
                            <input type="text" id="purchase-search" placeholder="Search or select purchase ID" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" autocomplete="off">
                            <input type="hidden" id="purchase_id" name="purchase_id" required>
                            <div id="purchase-dropdown" class="hidden absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto"></div>
                            <div id="purchase-loading" class="hidden absolute right-3 top-3">
                                <span class="material-symbols-outlined animate-spin text-gray-400">refresh</span>
                            </div>
                        </div>
                        <div id="purchase-details" class="hidden mt-3 p-4 bg-gray-50 rounded-lg border border-gray-200">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-sm font-medium text-gray-900" id="purchase-number"></p>
                                    <p class="text-xs text-gray-500 mt-1" id="purchase-supplier"></p>
                                </div>
                                <button type="button" onclick="clearPurchase()" class="text-gray-400 hover:text-gray-600">
                                    <span class="material-symbols-outlined text-lg">close</span>
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Payment Date -->
                    <div>
                        <label for="payment_date" class="block text-sm font-medium text-gray-700 mb-2">Payment Date <span class="text-red-500">*</span></label>
                        <input type="date" id="payment_date" name="payment_date" required value="{{ date('Y-m-d') }}" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                    </div>

                    <!-- Reference Number -->
                    <div>
                        <label for="reference_number" class="block text-sm font-medium text-gray-700 mb-2" style="font-size: 14px;">Reference Number</label>
                        <input type="text" id="reference_number" name="reference_number" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="Enter reference number">
                    </div>
                </div>

                <!-- Total Amount, Paid Amount, Due Amount - 3 Column Row -->
                <div class="md:col-span-3 grid grid-cols-1 md:grid-cols-3 gap-4">
                    <!-- Total Amount -->
                    <div>
                        <label for="total_amount" class="block text-sm font-medium text-gray-700 mb-2">Total Amount</label>
                        <input type="number" id="total_amount" name="total_amount" readonly value="0" step="0.01" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-gray-100 text-gray-900 cursor-not-allowed">
                    </div>

                    <!-- Paid Amount -->
                    <div>
                        <label for="paid_amount" class="block text-sm font-medium text-gray-700 mb-2">Paid Amount <span class="text-red-500">*</span></label>
                        <input type="number" id="paid_amount" name="paid_amount" required value="0" step="0.01" min="0.01" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                    </div>

                    <!-- Due Amount -->
                    <div>
                        <label for="due_amount" class="block text-sm font-medium text-gray-700 mb-2">Due Amount <span class="text-red-500">*</span></label>
                        <input type="number" id="due_amount" name="due_amount" readonly value="0" step="0.01" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-gray-100 text-gray-900 cursor-not-allowed">
                    </div>
                </div>

                <!-- Payment Source -->
                <div class="md:col-span-2">
                    <label for="payment_source" class="block text-sm font-medium text-gray-700 mb-2">Payment Source <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <input type="text" id="payment_source_search" placeholder="Search or Select Payment Source" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" autocomplete="off">
                        <input type="hidden" id="payment_source" name="payment_source" required>
                        <div id="payment_source_dropdown" class="hidden absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto"></div>
                        <div id="payment_source_loading" class="hidden absolute right-3 top-3">
                            <span class="material-symbols-outlined animate-spin text-gray-400">refresh</span>
                        </div>
                    </div>
                </div>

                <!-- Notes + Attachment — one row, two columns on md+ -->
                <div class="md:col-span-2 grid grid-cols-1 md:grid-cols-2 gap-6 items-stretch">
                    <div class="flex flex-col min-h-0">
                        <label for="notes" class="block text-sm font-medium text-gray-700 mb-2">Notes</label>
                        <textarea id="notes" name="notes" rows="2" class="w-full min-h-[5.5rem] flex-1 px-4 py-3 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow resize-y" placeholder="Enter notes"></textarea>
                    </div>
                    <div class="flex flex-col min-h-0">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Attachment</label>
                        <div class="flex-1 min-h-[5.5rem] flex flex-col items-center justify-center border-2 border-dashed border-gray-300 rounded-lg px-4 py-3 text-center hover:border-primary transition-colors cursor-pointer" onclick="document.getElementById('attachment').click()">
                            <input type="file" id="attachment" name="attachment" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png" class="hidden" onchange="previewAttachment(this)">
                            <span class="material-symbols-outlined text-2xl text-gray-400 mb-1">attach_file</span>
                            <p class="text-sm text-primary font-medium">Browse files</p>
                            <p class="text-xs text-gray-500 mt-0.5">Max size: 5MB</p>
                            <p id="attachment-name" class="text-xs text-gray-600 mt-1.5 line-clamp-2 hidden"></p>
                        </div>
                    </div>
                </div>
            </div>
            </div>

            <!-- Modal Footer -->
            <div class="flex-shrink-0 flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 bg-gray-50/80">
                <button type="button" onclick="closePaymentModal()" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50 transition-colors">
                    Cancel
                </button>
                <button type="submit" class="px-5 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-blue-600 transition-colors flex items-center gap-2">
                    <span class="material-symbols-outlined text-lg">add</span>
                    Create
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="deleteModal" 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-2xl w-full max-w-md m-4">
        <div class="p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-2">Delete Payment</h3>
            <p class="text-sm text-gray-600 mb-6">Are you sure you want to delete payment <span id="delete-payment-number" class="font-medium"></span>? This action cannot be undone.</p>
            <div class="flex items-center justify-end gap-3">
                <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>

@push('scripts')
@php
    $defaultCurrency = \App\Models\Currency::getDefault();
    $currencySymbol = $defaultCurrency ? $defaultCurrency->symbol : '₹';
    $currencyPosition = $defaultCurrency ? $defaultCurrency->symbol_position : 'before';
@endphp
<script>
const currencySymbol = '{{ $currencySymbol }}';
const currencyPosition = '{{ $currencyPosition }}';

function formatCurrency(amount) {
    const formatted = parseFloat(amount || 0).toFixed(2);
    if (currencyPosition === 'before') {
        return currencySymbol + formatted;
    }
    return formatted + ' ' + currencySymbol;
}

let purchaseSearchTimeout;
let paymentSourceSearchTimeout;
let selectedPurchase = null;

// Purchase Search
document.getElementById('purchase-search').addEventListener('input', function(e) {
    clearTimeout(purchaseSearchTimeout);
    const search = e.target.value.trim();
    
    if (search.length < 2) {
        document.getElementById('purchase-dropdown').classList.add('hidden');
        return;
    }

    purchaseSearchTimeout = setTimeout(() => {
        searchPurchases(search);
    }, 300);
});

function searchPurchases(search) {
    const dropdown = document.getElementById('purchase-dropdown');
    const loading = document.getElementById('purchase-loading');
    
    loading.classList.remove('hidden');
    dropdown.classList.remove('hidden');
    dropdown.innerHTML = '<div class="p-4 text-center text-gray-500">Loading...</div>';

    fetch(`{{ route('admin.supplier-payments.api.purchases') }}?search=${encodeURIComponent(search)}`)
        .then(response => response.json())
        .then(data => {
            loading.classList.add('hidden');
            if (data.success && data.purchases.length > 0) {
                dropdown.innerHTML = data.purchases.map(purchase => `
                    <div class="p-3 hover:bg-gray-50 cursor-pointer border-b border-gray-100 last:border-b-0" onclick="selectPurchase(${purchase.id}, '${purchase.purchase_number}', '${purchase.supplier_name}', ${purchase.total}, ${purchase.paid_amount}, ${purchase.due_amount})">
                        <p class="text-sm font-medium text-gray-900">${purchase.purchase_number}</p>
                        <p class="text-xs text-gray-500">${purchase.supplier_name} - ${formatCurrency(purchase.total)}</p>
                        <p class="text-xs text-gray-400 mt-1">Due: ${formatCurrency(purchase.due_amount)}</p>
                    </div>
                `).join('');
            } else {
                dropdown.innerHTML = '<div class="p-4 text-center text-gray-500">No purchases found</div>';
            }
        })
        .catch(error => {
            loading.classList.add('hidden');
            dropdown.innerHTML = '<div class="p-4 text-center text-red-500">Error loading purchases</div>';
        });
}

function selectPurchase(id, number, supplier, total, paid, due) {
    selectedPurchase = { id, number, supplier, total, paid, due };
    document.getElementById('purchase_id').value = id;
    document.getElementById('purchase-search').value = number;
    document.getElementById('purchase-dropdown').classList.add('hidden');
    document.getElementById('purchase-details').classList.remove('hidden');
    document.getElementById('purchase-number').textContent = number;
    document.getElementById('purchase-supplier').textContent = supplier;
    
    // Update amounts
    document.getElementById('total_amount').value = total;
    document.getElementById('due_amount').value = due;
    
    // Update paid amount max
    document.getElementById('paid_amount').max = due;
    document.getElementById('paid_amount').value = due > 0 ? Math.min(due, due) : 0;
    
    calculateDueAmount();
}

function clearPurchase() {
    selectedPurchase = null;
    document.getElementById('purchase_id').value = '';
    document.getElementById('purchase-search').value = '';
    document.getElementById('purchase-details').classList.add('hidden');
    document.getElementById('total_amount').value = 0;
    document.getElementById('paid_amount').value = 0;
    document.getElementById('due_amount').value = 0;
}

// Payment Source Search
document.getElementById('payment_source_search').addEventListener('input', function(e) {
    clearTimeout(paymentSourceSearchTimeout);
    const search = e.target.value.trim();
    
    paymentSourceSearchTimeout = setTimeout(() => {
        searchPaymentSources(search);
    }, 300);
});

function searchPaymentSources(search) {
    const dropdown = document.getElementById('payment_source_dropdown');
    const loading = document.getElementById('payment_source_loading');
    
    loading.classList.remove('hidden');
    dropdown.classList.remove('hidden');
    
    fetch(`{{ route('admin.supplier-payments.api.payment-sources') }}`)
        .then(response => response.json())
        .then(data => {
            loading.classList.add('hidden');
            if (data.success && data.sources.length > 0) {
                const filtered = data.sources.filter(source => 
                    source.toLowerCase().includes(search.toLowerCase())
                );
                
                if (filtered.length > 0) {
                    dropdown.innerHTML = filtered.map(source => `
                        <div class="p-3 hover:bg-gray-50 cursor-pointer border-b border-gray-100 last:border-b-0" onclick="selectPaymentSource('${source}')">
                            <p class="text-sm text-gray-900">${source}</p>
                        </div>
                    `).join('');
                } else {
                    dropdown.innerHTML = '<div class="p-4 text-center text-gray-500">No payment sources found</div>';
                }
            } else {
                dropdown.innerHTML = '<div class="p-4 text-center text-gray-500">No payment sources available</div>';
            }
        })
        .catch(error => {
            loading.classList.add('hidden');
            dropdown.innerHTML = '<div class="p-4 text-center text-red-500">Error loading payment sources</div>';
        });
}

function selectPaymentSource(source) {
    document.getElementById('payment_source').value = source;
    document.getElementById('payment_source_search').value = source;
    document.getElementById('payment_source_dropdown').classList.add('hidden');
}

// Calculate due amount
document.getElementById('paid_amount').addEventListener('input', calculateDueAmount);

function calculateDueAmount() {
    const total = parseFloat(document.getElementById('total_amount').value) || 0;
    const paid = parseFloat(document.getElementById('paid_amount').value) || 0;
    const existingPaid = selectedPurchase ? selectedPurchase.paid : 0;
    const due = Math.max(0, total - (existingPaid + paid));
    document.getElementById('due_amount').value = due.toFixed(2);
}

// Close dropdowns when clicking outside
document.addEventListener('click', function(e) {
    if (!e.target.closest('#purchase-search') && !e.target.closest('#purchase-dropdown')) {
        document.getElementById('purchase-dropdown').classList.add('hidden');
    }
    if (!e.target.closest('#payment_source_search') && !e.target.closest('#payment_source_dropdown')) {
        document.getElementById('payment_source_dropdown').classList.add('hidden');
    }
});

// Modal functions
function openPaymentModal() {
    document.getElementById('paymentModal').classList.remove('hidden');
    document.getElementById('paymentModal').classList.add('flex');
    document.body.style.overflow = 'hidden';
}

function closePaymentModal() {
    document.getElementById('paymentModal').classList.add('hidden');
    document.getElementById('paymentModal').classList.remove('flex');
    document.body.style.overflow = '';
    document.getElementById('payment-form').reset();
    clearPurchase();
    document.getElementById('payment_source').value = '';
    document.getElementById('payment_source_search').value = '';
    document.getElementById('attachment-name').classList.add('hidden');
}

function previewAttachment(input) {
    if (input.files && input.files[0]) {
        const fileName = input.files[0].name;
        document.getElementById('attachment-name').textContent = fileName;
        document.getElementById('attachment-name').classList.remove('hidden');
    }
}

// Form submission
document.getElementById('payment-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="material-symbols-outlined animate-spin text-lg">refresh</span> Creating...';
    
    fetch(`{{ route('admin.supplier-payments.store') }}`, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.reload();
        } else {
            alert(data.message || 'Failed to create payment');
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    })
    .catch(error => {
        alert('An error occurred. Please try again.');
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
});

// Delete modal
function openDeleteModal(id, paymentNumber) {
    document.getElementById('delete-payment-number').textContent = paymentNumber;
    document.getElementById('delete-form').action = `{{ route('admin.supplier-payments.index') }}/${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');
}
</script>
@endpush
@endsection
