@extends('layouts.admin')

@section('title', 'Supplier')

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

@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">Supplier</h1>
        <div class="flex items-center gap-3">
            <form method="GET" action="{{ route('admin.suppliers.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="openCreateModal()" 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 Supplier</span>
            </button>
        </div>
    </div>

    <!-- Search Bar -->
    <div class="mb-4">
        <form method="GET" action="{{ route('admin.suppliers.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.suppliers.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>

    <!-- Suppliers 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-[250px]">SUPPLIER</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[150px]">PHONE</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 text-right min-w-[150px]">CLOSING BALANCE</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($suppliers as $index => $supplier)
                        <tr class="group hover:bg-gray-50/50 transition-colors">
                            <td class="py-4 px-6 text-sm text-gray-600">{{ ($suppliers->currentPage() - 1) * $suppliers->perPage() + $index + 1 }}</td>
                            <td class="py-4 px-6">
                                <div class="flex items-center gap-3">
                                    <div class="size-10 rounded-full bg-primary flex items-center justify-center text-white font-bold text-sm shrink-0 overflow-hidden">
                                        @if($supplier->image_url)
                                            <img src="{{ $supplier->image_url }}" alt="{{ $supplier->name }}" class="w-full h-full rounded-full object-cover" onerror="this.style.display='none'; this.parentElement.innerHTML='{{ strtoupper(substr($supplier->name ?? 'N', 0, 1)) }}';">
                                        @else
                                            {{ strtoupper(substr($supplier->name ?? 'N', 0, 1)) }}
                                        @endif
                                    </div>
                                    <div class="flex flex-col min-w-0">
                                        <span class="text-sm font-medium text-gray-900 truncate">{{ $supplier->name }}</span>
                                        @if($supplier->email)
                                            <span class="text-xs text-gray-500 truncate">{{ $supplier->email }}</span>
                                        @endif
                                    </div>
                                </div>
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600">
                                {{ $supplier->phone ?? '-' }}
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600 whitespace-nowrap">
                                {{ $supplier->created_at ? $supplier->created_at->format('d-m-Y') : '-' }}
                            </td>
                            <td class="py-4 px-6 text-sm font-medium text-gray-900 text-right">
                                {{ \App\Models\Currency::formatAmount($supplier->closing_balance ?? 0) }}
                            </td>
                            <td class="py-4 px-6">
                                <div class="relative inline-block text-left">
                                    <button type="button" data-admin-fixed-menu-trigger="action-menu-{{ $supplier->id }}" onclick="adminFixedActionMenuToggle(event || window.event, 'action-menu-{{ $supplier->id }}')" class="text-gray-400 hover:text-gray-600 transition-colors p-1" title="More actions">
                                        <span class="material-symbols-outlined text-xl">more_vert</span>
                                    </button>
                                    <div id="action-menu-{{ $supplier->id }}" data-admin-fixed-action-menu class="hidden w-48 overflow-hidden rounded-lg border border-gray-200 bg-white shadow-lg">
                                        <div class="py-1">
                                            <a href="{{ route('admin.suppliers.edit', $supplier) }}" 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({{ $supplier->id }}, @js($supplier->name))" 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="6" class="py-12 px-6 text-center text-gray-500">
                                <span class="material-symbols-outlined text-4xl mb-2 block">local_shipping</span>
                                <p>No suppliers found</p>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

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

<!-- Create Supplier Modal -->
<div id="create-supplier-modal" data-admin-modal class="fixed inset-0 z-50 hidden flex items-center justify-center bg-black/50 backdrop-blur-sm">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
        <!-- Modal Header -->
        <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200 sticky top-0 bg-white rounded-t-xl">
            <h2 class="text-xl font-bold text-gray-900">Create Supplier</h2>
            <button type="button" onclick="closeCreateModal()" class="text-gray-400 hover:text-gray-600 transition-colors">
                <span class="material-symbols-outlined text-2xl">close</span>
            </button>
        </div>

        <!-- Modal Body -->
        <form id="create-supplier-form" class="p-6 space-y-6">
            @csrf
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <!-- Image Upload Section -->
                <div class="md:col-span-1">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Image</label>
                    <div class="space-y-3">
                        <div class="w-32 h-32 rounded-lg bg-gray-100 border-2 border-dashed border-gray-300 flex items-center justify-center overflow-hidden" id="image-preview-container">
                            <span class="material-symbols-outlined text-4xl text-gray-400" id="image-placeholder">image</span>
                            <img id="image-preview" src="" alt="Preview" class="hidden w-full h-full object-cover">
                        </div>
                        <button type="button" onclick="document.getElementById('supplier-image').click()" class="w-full flex items-center justify-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-blue-600 transition-colors">
                            <span class="material-symbols-outlined text-lg">cloud_upload</span>
                            Upload Image
                        </button>
                        <input type="file" id="supplier-image" name="image" accept="image/jpeg,image/png,image/jpg" class="hidden" onchange="previewImage(this)">
                        <p class="text-xs text-gray-500 text-center">JPG or PNG format, not exceeding 5MB.</p>
                    </div>
                </div>

                <!-- Form Fields -->
                <div class="md:col-span-2 space-y-4">
                    <!-- Name -->
                    <div>
                        <label for="supplier-name" class="block text-sm font-medium text-gray-700 mb-2">Name <span class="text-red-500">*</span></label>
                        <input type="text" id="supplier-name" name="name" required 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 Name">
                    </div>

                    <!-- Email -->
                    <div>
                        <label for="supplier-email" class="block text-sm font-medium text-gray-700 mb-2">Email</label>
                        <input type="email" id="supplier-email" name="email" 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 Email Address">
                    </div>

                    <!-- Phone Number -->
                    <div>
                        <label for="supplier-phone" class="block text-sm font-medium text-gray-700 mb-2">Phone Number <span class="text-red-500">*</span></label>
                        <input type="text" id="supplier-phone" name="phone" required 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 Phone Number">
                    </div>

                    <!-- Balance -->
                    <div>
                        <label for="supplier-balance" class="block text-sm font-medium text-gray-700 mb-2">Balance</label>
                        <input type="number" id="supplier-balance" name="balance" value="0" step="0.01" min="0" 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">
                    </div>

                    <!-- Mode -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Mode</label>
                        <div class="flex gap-4">
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input type="radio" name="mode" value="credit" checked class="text-primary focus:ring-primary">
                                <span class="text-sm text-gray-700">Credit</span>
                            </label>
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input type="radio" name="mode" value="debit" class="text-primary focus:ring-primary">
                                <span class="text-sm text-gray-700">Debit</span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal Footer -->
            <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200">
                <button type="button" onclick="closeCreateModal()" 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="delete-supplier-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-2xl w-full max-w-md m-4">
        <div class="p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-2">Delete Supplier</h3>
            <p class="text-sm text-gray-600 mb-6">Are you sure you want to delete supplier <span id="delete-supplier-name" class="font-medium"></span>? This action cannot be undone.</p>
            <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-supplier-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')
<script>
function openCreateModal() {
    document.getElementById('create-supplier-modal').classList.remove('hidden');
    document.getElementById('create-supplier-form').reset();
    document.getElementById('image-preview').classList.add('hidden');
    document.getElementById('image-placeholder').classList.remove('hidden');
    document.getElementById('supplier-balance').value = '0';
    document.querySelector('input[name="mode"][value="credit"]').checked = true;
}

function closeCreateModal() {
    document.getElementById('create-supplier-modal').classList.add('hidden');
    document.getElementById('create-supplier-form').reset();
    document.getElementById('image-preview').classList.add('hidden');
    document.getElementById('image-placeholder').classList.remove('hidden');
}

function previewImage(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('image-preview').src = e.target.result;
            document.getElementById('image-preview').classList.remove('hidden');
            document.getElementById('image-placeholder').classList.add('hidden');
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// Handle form submission
document.getElementById('create-supplier-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    // Ensure balance is a number, not empty string
    const balanceValue = formData.get('balance');
    if (balanceValue === '' || balanceValue === null || balanceValue === undefined) {
        formData.set('balance', '0');
    }
    
    // Ensure mode is set (should be set by radio button, but double-check)
    const modeValue = formData.get('mode');
    if (!modeValue || modeValue === '') {
        // Try to get from checked radio button
        const checkedMode = document.querySelector('input[name="mode"]:checked');
        if (checkedMode) {
            formData.set('mode', checkedMode.value);
        } else {
            formData.set('mode', 'credit');
        }
    }
    
    // Debug: Log form data (remove in production)
    console.log('Form Data:', {
        name: formData.get('name'),
        email: formData.get('email'),
        phone: formData.get('phone'),
        balance: formData.get('balance'),
        mode: formData.get('mode'),
        hasImage: formData.get('image') ? 'Yes' : 'No'
    });
    
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="material-symbols-outlined text-lg animate-spin">sync</span> Creating...';
    
    fetch('{{ route("admin.suppliers.store") }}', {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
        }
    })
    .then(async response => {
        let data;
        try {
            data = await response.json();
        } catch (e) {
            console.error('Failed to parse response:', e);
            alert('Error: Invalid response from server');
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
            return;
        }
        
        if (!response.ok) {
            // Handle validation errors (422)
            if (response.status === 422 && data.errors) {
                let errorMessages = [];
                for (const [field, messages] of Object.entries(data.errors)) {
                    const fieldName = field.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
                    errorMessages.push(`${fieldName}: ${Array.isArray(messages) ? messages.join(', ') : messages}`);
                }
                alert('Validation Error:\n\n' + errorMessages.join('\n'));
            } else {
                alert('Error: ' + (data.message || 'Failed to create supplier'));
            }
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
            return;
        }
        
        if (data.success) {
            closeCreateModal();
            location.reload();
        } else {
            alert('Error: ' + (data.message || 'Failed to create supplier'));
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error creating supplier. Please check the console for details.');
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
});

function openDeleteModal(id, name) {
    if (typeof window.adminFixedActionMenuCloseAll === 'function') {
        window.adminFixedActionMenuCloseAll();
    }
    document.getElementById('delete-supplier-name').textContent = name;
    document.getElementById('delete-supplier-form').action = '{{ route("admin.suppliers.index") }}/' + id;
    document.getElementById('delete-supplier-modal').classList.remove('hidden');
    document.getElementById('delete-supplier-modal').classList.add('flex');
}

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

// Handle delete form submission
document.getElementById('delete-supplier-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const form = this;
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="material-symbols-outlined text-sm animate-spin">sync</span> Deleting...';
    
    fetch(form.action, {
        method: 'POST',
        body: new FormData(form),
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
        }
    })
    .then(async response => {
        const data = await response.json();
        
        if (data.success) {
            closeDeleteModal();
            location.reload();
        } else {
            alert('Error deleting supplier: ' + (data.message || 'Unknown error'));
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error deleting supplier');
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
});
</script>
@endpush
@endsection
