@extends('layouts.admin-simple')

@section('title', 'Suppliers')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item active">Suppliers</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">Suppliers</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Manage supplier information and performance</p>
        </div>
        @can('warehouse.suppliers.create')
        <div class="page-actions-right d-flex align-items-center">
            <button type="button" onclick="showImportModal()" class="btn btn-sm btn-success mr-2" title="Import suppliers from Excel file">
                <i class="material-icons mr-1" style="font-size: 16px;">upload_file</i>
                Import
            </button>

            <button type="button" onclick="exportSuppliers()" class="btn btn-sm btn-info mr-2" title="Export suppliers to Excel file">
                <i class="material-icons mr-1" style="font-size: 16px;">file_download</i>
                Export
            </button>

            <button type="button" onclick="showAddSupplierModal()" class="btn btn-sm btn-primary" title="Add new supplier to the system">
                <i class="material-icons mr-1" style="font-size: 16px;">add</i>
                Add Supplier
            </button>
        </div>
        @endcan
    </div>
@endsection

@section('content')
    <!-- Statistics Cards -->
    <div class="row mb-4 warehouse-stats-row">
        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Total Suppliers"
                :value="$statistics['total_suppliers'] ?? 0"
                icon="business"
                color="primary"
                subtitle="All registered suppliers"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Active Suppliers"
                :value="$statistics['active_suppliers'] ?? 0"
                icon="check_circle"
                color="success"
                subtitle="Currently active suppliers"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Average Rating"
                :value="number_format($statistics['average_rating'] ?? 0, 1)"
                icon="star"
                color="warning"
                subtitle="Overall supplier rating"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Top Rated Suppliers"
                :value="$statistics['top_rated_suppliers'] ?? 0"
                icon="trending_up"
                color="info"
                subtitle="5-star rated suppliers"
            />
        </div>
    </div>

    <!-- Filters Panel -->
    <div class="card mb-4 warehouse-filters-panel">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="material-icons align-middle mr-2">filter_list</i>
                Filters
            </h5>
        </div>
        <div class="card-body">
            <form id="filterForm" class="warehouse-filter-form" method="GET" action="{{ route('warehouse.suppliers.index') }}">
                <div class="row">
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Search</label>
                        <input type="text" name="search" value="{{ request('search') }}" class="form-control" 
                               placeholder="Name, code, email, contact">
                    </div>

                    <div class="col-md-2 mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control warehouse-select2">
                            <option value="">All Statuses</option>
                            <option value="active" {{ request('status') == 'active' ? 'selected' : '' }}>Active</option>
                            <option value="inactive" {{ request('status') == 'inactive' ? 'selected' : '' }}>Inactive</option>
                            <option value="suspended" {{ request('status') == 'suspended' ? 'selected' : '' }}>Suspended</option>
                        </select>
                    </div>

                    <div class="col-md-2 mb-3">
                        <label class="form-label">Country</label>
                        <select name="country" class="form-control warehouse-select2">
                            <option value="">All Countries</option>
                            @foreach($filterOptions['countries'] ?? [] as $country)
                                <option value="{{ $country }}" {{ request('country') == $country ? 'selected' : '' }}>{{ $country }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="col-md-2 mb-3">
                        <label class="form-label">City</label>
                        <select name="city" class="form-control warehouse-select2">
                            <option value="">All Cities</option>
                            @foreach($filterOptions['cities'] ?? [] as $city)
                                <option value="{{ $city }}" {{ request('city') == $city ? 'selected' : '' }}>{{ $city }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="col-md-2 mb-3">
                        <label class="form-label">Min Rating</label>
                        <input type="number" name="rating_min" value="{{ request('rating_min') }}" 
                               class="form-control" placeholder="0" min="0" max="5" step="0.1">
                    </div>

                    <div class="col-md-1 mb-3">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-primary btn-block">
                            <i class="material-icons" style="font-size: 18px; vertical-align: middle;">search</i>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Export Buttons -->

    <!-- Suppliers Table -->
    <div class="card">
        <div class="card-header warehouse-report-header">
            <h5 class="mb-0 warehouse-report-title">
                <i class="material-icons align-middle mr-2">business</i>
                Suppliers List ({{ $suppliers->total() }} total suppliers)
            </h5>
        </div>
        <div class="card-body p-0">
            <div class="warehouse-table-container">
                <!-- Loading Overlay -->
                <div class="warehouse-loading-overlay" id="tableLoadingOverlay">
                    <div class="warehouse-loading-content">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <div class="mt-2">Loading supplier data...</div>
                        </div>
                    </div>
                </div>

                <!-- Table -->
                <div class="warehouse-table-wrapper">
                    <table class="table table-hover mb-0 warehouse-table">
                        <thead class="thead-light">
                            <tr>
                                <th style="min-width: 200px;">Supplier</th>
                                <th style="min-width: 150px;">Contact</th>
                                <th style="min-width: 150px;">Location</th>
                                <th style="min-width: 100px;" class="text-center">Status</th>
                                <th style="min-width: 100px;" class="text-center">Rating</th>
                                <th style="min-width: 120px;">Payment Terms</th>
                                <th style="min-width: 100px;">Created</th>
                                <th style="min-width: 80px;" class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($suppliers as $supplier)
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="supplier-avatar mr-3">
                                                <i class="material-icons text-primary" style="font-size: 24px;">business</i>
                                            </div>
                                            <div>
                                                <div class="font-weight-medium">{{ $supplier->name }}</div>
                                                @if($supplier->supplier_code)
                                                    <small class="text-muted">Code: {{ $supplier->supplier_code }}</small>
                                                @endif
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div>
                                            @if($supplier->contact_person)
                                                <div class="font-weight-medium">{{ $supplier->contact_person }}</div>
                                            @endif
                                            @if($supplier->email)
                                                <small class="text-muted">{{ $supplier->email }}</small><br>
                                            @endif
                                            @if($supplier->phone)
                                                <small class="text-muted">{{ $supplier->phone }}</small>
                                            @endif
                                        </div>
                                    </td>
                                    <td>
                                        <div>
                                            @if($supplier->city)
                                                <div>{{ $supplier->city }}</div>
                                            @endif
                                            @if($supplier->country)
                                                <small class="text-muted">{{ $supplier->country }}</small>
                                            @endif
                                        </div>
                                    </td>
                                    <td class="warehouse-cell-status">
                                        @php
                                            $statusColors = [
                                                'active' => 'success',
                                                'inactive' => 'secondary',
                                                'suspended' => 'danger'
                                            ];
                                            $statusColor = $statusColors[$supplier->status] ?? 'secondary';
                                        @endphp
                                        <span class="badge warehouse-badge warehouse-status-{{ $statusColor }}">
                                            {{ ucfirst($supplier->status) }}
                                        </span>
                                    </td>
                                    <td class="text-center">
                                        @if($supplier->rating)
                                            <div class="d-flex align-items-center justify-content-center">
                                                <span class="mr-1">{{ number_format($supplier->rating, 1) }}</span>
                                                <i class="material-icons text-warning" style="font-size: 16px;">star</i>
                                            </div>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td>
                                        <span class="badge warehouse-badge warehouse-status-info">
                                            {{ $supplier->payment_terms ?: 'Standard' }}
                                        </span>
                                    </td>
                                    <td class="warehouse-cell-date">
                                        {{ $supplier->created_at->format('d M Y') }}
                                    </td>
                                    <td class="text-center">
                                        <div class="btn-group" role="group">
                                            <a href="{{ route('warehouse.suppliers.show', $supplier->id) }}" 
                                               class="btn btn-sm btn-outline-primary warehouse-action-btn" title="View Details">
                                                <i class="material-icons">visibility</i>
                                            </a>
                                            @can('warehouse.suppliers.edit')
                                            <button type="button" onclick="showEditSupplierModal({{ $supplier->id }})" 
                                                    class="btn btn-sm btn-outline-secondary warehouse-action-btn" title="Edit Supplier">
                                                <i class="material-icons">edit</i>
                                            </button>
                                            @endcan
                                            @can('warehouse.suppliers.delete')
                                            <button type="button" onclick="confirmDelete({{ $supplier->id }}, '{{ $supplier->name }}')" 
                                                    class="btn btn-sm btn-outline-danger warehouse-action-btn" title="Delete Supplier">
                                                <i class="material-icons">delete</i>
                                            </button>
                                            @endcan
                                        </div>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="8" class="warehouse-empty-state">
                                        <i class="material-icons">business</i>
                                        <h5>No Suppliers Found</h5>
                                        <p class="text-muted">No suppliers match your current filters.</p>
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        @if($suppliers->hasPages())
            <div class="card-footer">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        Showing {{ $suppliers->firstItem() }} to {{ $suppliers->lastItem() }} 
                        of {{ $suppliers->total() }} suppliers
                    </div>
                    <div>
                        <nav class="warehouse-pagination">
                            {{ $suppliers->links('pagination::bootstrap-4') }}
                        </nav>
                    </div>
                </div>
            </div>
        @endif
    </div>
@endsection

@section('modals')
    <!-- Add Supplier Modal -->
    <div class="modal fade" id="addSupplierModal" tabindex="-1" role="dialog" aria-labelledby="addSupplierModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addSupplierModalLabel">
                        <i class="material-icons mr-2">business</i>
                        Add New Supplier
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="addSupplierForm" method="POST" action="{{ route('warehouse.suppliers.store') }}">
                    @csrf
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Supplier Name <span class="text-danger">*</span></label>
                                <input type="text" name="name" class="form-control" required placeholder="Enter supplier name">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Supplier Code</label>
                                <input type="text" name="supplier_code" class="form-control" placeholder="Enter supplier code">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Contact Person</label>
                                <input type="text" name="contact_person" class="form-control" placeholder="Enter contact person">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Email</label>
                                <input type="email" name="email" class="form-control" placeholder="Enter email address">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Phone</label>
                                <input type="text" name="phone" class="form-control" placeholder="Enter phone number">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Mobile</label>
                                <input type="text" name="mobile" class="form-control" placeholder="Enter mobile number">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Address</label>
                                <textarea name="address" class="form-control" rows="2" placeholder="Enter address"></textarea>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">City</label>
                                <input type="text" name="city" class="form-control" placeholder="Enter city">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Country</label>
                                <input type="text" name="country" class="form-control" placeholder="Enter country">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Status <span class="text-danger">*</span></label>
                                <select name="status" class="form-control" required>
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                    <option value="suspended">Suspended</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Payment Terms</label>
                                <select name="payment_terms" class="form-control">
                                    <option value="">Select Payment Terms</option>
                                    <option value="Net 15">Net 15</option>
                                    <option value="Net 30" selected>Net 30</option>
                                    <option value="Net 45">Net 45</option>
                                    <option value="Net 60">Net 60</option>
                                    <option value="Cash on Delivery">Cash on Delivery</option>
                                    <option value="Advance Payment">Advance Payment</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Rating</label>
                                <select name="rating" class="form-control">
                                    <option value="">Select Rating</option>
                                    <option value="1">1 Star</option>
                                    <option value="2">2 Stars</option>
                                    <option value="3">3 Stars</option>
                                    <option value="4">4 Stars</option>
                                    <option value="5">5 Stars</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Notes</label>
                                <textarea name="notes" class="form-control" rows="3" placeholder="Enter any notes about the supplier"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="material-icons mr-1" style="font-size: 16px;">cancel</i>
                            Cancel
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                            Add Supplier
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Import Modal -->
    <div class="modal fade" id="importModal" tabindex="-1" role="dialog" aria-labelledby="importModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="importModalLabel">
                        <i class="material-icons mr-2">upload_file</i>
                        Import Suppliers
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="importForm" method="POST" action="{{ route('warehouse.suppliers.import') }}" enctype="multipart/form-data">
                        @csrf
                        <div class="mb-3">
                            <label class="form-label">Select Excel File</label>
                            <input type="file" name="file" class="form-control" accept=".xlsx,.xls,.csv" required>
                            <small class="form-text text-muted">Supported formats: Excel (.xlsx, .xls) and CSV (.csv)</small>
                        </div>
                        <div class="mb-3">
                            <a href="{{ route('warehouse.suppliers.template') }}" class="btn btn-sm btn-outline-info">
                                <i class="material-icons mr-1" style="font-size: 16px;">download</i>
                                Download Template
                            </a>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="material-icons mr-1" style="font-size: 16px;">cancel</i>
                        Cancel
                    </button>
                    <button type="submit" form="importForm" class="btn btn-success">
                        <i class="material-icons mr-1" style="font-size: 16px;">upload</i>
                        Import Suppliers
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Supplier Modal -->
    <div class="modal fade" id="editSupplierModal" tabindex="-1" role="dialog" aria-labelledby="editSupplierModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editSupplierModalLabel">
                        <i class="material-icons mr-2">edit</i>
                        Edit Supplier
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="editSupplierForm" method="POST">
                    @csrf
                    @method('PUT')
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Supplier Name <span class="text-danger">*</span></label>
                                <input type="text" name="name" id="edit_name" class="form-control" required placeholder="Enter supplier name">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Supplier Code</label>
                                <input type="text" name="supplier_code" id="edit_supplier_code" class="form-control" placeholder="Enter supplier code">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Contact Person</label>
                                <input type="text" name="contact_person" id="edit_contact_person" class="form-control" placeholder="Enter contact person">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Email</label>
                                <input type="email" name="email" id="edit_email" class="form-control" placeholder="Enter email address">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Phone</label>
                                <input type="text" name="phone" id="edit_phone" class="form-control" placeholder="Enter phone number">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Mobile</label>
                                <input type="text" name="mobile" id="edit_mobile" class="form-control" placeholder="Enter mobile number">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Address</label>
                                <textarea name="address" id="edit_address" class="form-control" rows="2" placeholder="Enter address"></textarea>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">City</label>
                                <input type="text" name="city" id="edit_city" class="form-control" placeholder="Enter city">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Country</label>
                                <input type="text" name="country" id="edit_country" class="form-control" placeholder="Enter country">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Status <span class="text-danger">*</span></label>
                                <select name="status" id="edit_status" class="form-control" required>
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                    <option value="suspended">Suspended</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Payment Terms</label>
                                <select name="payment_terms" id="edit_payment_terms" class="form-control">
                                    <option value="">Select Payment Terms</option>
                                    <option value="Net 15">Net 15</option>
                                    <option value="Net 30">Net 30</option>
                                    <option value="Net 45">Net 45</option>
                                    <option value="Net 60">Net 60</option>
                                    <option value="Cash on Delivery">Cash on Delivery</option>
                                    <option value="Advance Payment">Advance Payment</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Rating</label>
                                <select name="rating" id="edit_rating" class="form-control">
                                    <option value="">Select Rating</option>
                                    <option value="1">1 Star</option>
                                    <option value="2">2 Stars</option>
                                    <option value="3">3 Stars</option>
                                    <option value="4">4 Stars</option>
                                    <option value="5">5 Stars</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Notes</label>
                                <textarea name="notes" id="edit_notes" class="form-control" rows="3" placeholder="Enter any notes about the supplier"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="material-icons mr-1" style="font-size: 16px;">cancel</i>
                            Cancel
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                            Update Supplier
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('styles')
    <link href="{{ asset('admin-assets/css/warehouse-reports.css') }}" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet" />
    <style>
        .supplier-avatar {
            width: 40px;
            height: 40px;
            background: #f8f9fa;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px solid #e9ecef;
        }

        /* SweetAlert2 custom button styling */
        .swal2-actions {
            gap: 12px !important;
        }

        .swal2-actions .btn {
            min-height: 38px !important;
            height: 38px !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        .swal2-actions .btn:focus,
        .swal2-actions .btn:focus-visible {
            outline: none !important;
            box-shadow: none !important;
        }

        .swal2-actions .btn:active {
            transform: scale(0.98);
        }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="{{ asset('admin-assets/js/warehouse-reports.js') }}"></script>
    <script>
        // Debug function to check if modal is working
        function showAddSupplierModal() {
            console.log('🔧 Attempting to show Add Supplier modal...');
            
            // Check if jQuery is available
            if (typeof $ === 'undefined') {
                console.error('❌ jQuery is not loaded!');
                alert('Error: jQuery is not available. Please refresh the page.');
                return;
            }
            
            // Check if modal exists
            const modal = $('#addSupplierModal');
            if (modal.length === 0) {
                console.error('❌ Modal #addSupplierModal not found in DOM!');
                alert('Error: Add Supplier modal not found. Please refresh the page.');
                return;
            }
            
            console.log('✅ Modal found, showing...');
            modal.modal('show');
        }

        function showImportModal() {
            console.log('🔧 Attempting to show Import modal...');
            
            // Check if jQuery is available
            if (typeof $ === 'undefined') {
                console.error('❌ jQuery is not loaded!');
                alert('Error: jQuery is not available. Please refresh the page.');
                return;
            }
            
            // Check if modal exists
            const modal = $('#importModal');
            if (modal.length === 0) {
                console.error('❌ Modal #importModal not found in DOM!');
                alert('Error: Import modal not found. Please refresh the page.');
                return;
            }
            
            console.log('✅ Import modal found, showing...');
            modal.modal('show');
        }

        function exportSuppliers() {
            const params = new URLSearchParams(window.location.search);
            params.append('export', 'excel');
            const exportUrl = '{{ route('warehouse.suppliers.export') }}?' + params.toString();
            
            const link = document.createElement('a');
            link.href = exportUrl;
            link.download = '';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }


        function showEditSupplierModal(supplierId) {
            console.log('🔧 Opening edit modal for supplier ID:', supplierId);
            
            // Make AJAX request to get supplier data
            fetch(`{{ url('warehouse/suppliers') }}/${supplierId}/edit`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const supplier = data.data;
                    
                    // Populate form fields
                    document.getElementById('edit_name').value = supplier.name || '';
                    document.getElementById('edit_supplier_code').value = supplier.supplier_code || '';
                    document.getElementById('edit_contact_person').value = supplier.contact_person || '';
                    document.getElementById('edit_email').value = supplier.email || '';
                    document.getElementById('edit_phone').value = supplier.phone || '';
                    document.getElementById('edit_mobile').value = supplier.mobile || '';
                    document.getElementById('edit_address').value = supplier.address || '';
                    document.getElementById('edit_city').value = supplier.city || '';
                    document.getElementById('edit_country').value = supplier.country || '';
                    document.getElementById('edit_status').value = supplier.status || 'active';
                    // Set payment terms dropdown
                    const paymentTermsSelect = document.getElementById('edit_payment_terms');
                    paymentTermsSelect.value = supplier.payment_terms || '';
                    
                    // Set rating dropdown  
                    const ratingSelect = document.getElementById('edit_rating');
                    ratingSelect.value = supplier.rating || '';
                    document.getElementById('edit_notes').value = supplier.notes || '';
                    
                    // Set form action
                    document.getElementById('editSupplierForm').action = `{{ url('warehouse/suppliers') }}/${supplier.id}`;
                    
                    // Show modal
                    $('#editSupplierModal').modal('show');
                    console.log('✅ Edit modal opened successfully');
                } else {
                    alert('Error loading supplier data: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error loading supplier data. Please try again.');
            });
        }

        function confirmDelete(supplierId, supplierName) {
            Swal.fire({
                title: 'Delete Supplier?',
                html: `Are you sure you want to delete <strong>"${supplierName}"</strong>?<br><small class="text-muted">This action cannot be undone.</small>`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: '<i class="material-icons" style="font-size: 16px; vertical-align: middle;">delete</i> Yes, Delete',
                cancelButtonText: '<i class="material-icons" style="font-size: 16px; vertical-align: middle;">cancel</i> Cancel',
                reverseButtons: true,
                focusCancel: true,
                customClass: {
                    confirmButton: 'btn btn-danger px-4',
                    cancelButton: 'btn btn-secondary px-4'
                },
                buttonsStyling: false
            }).then((result) => {
                if (result.isConfirmed) {
                    // Show loading state
                    Swal.fire({
                        title: 'Deleting...',
                        text: 'Please wait while we delete the supplier.',
                        icon: 'info',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });

                    // Create a form to submit the DELETE request
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = `{{ url('warehouse/suppliers') }}/${supplierId}`;

                    // Add CSRF token
                    const csrfToken = document.createElement('input');
                    csrfToken.type = 'hidden';
                    csrfToken.name = '_token';
                    csrfToken.value = '{{ csrf_token() }}';
                    form.appendChild(csrfToken);

                    // Add method override for DELETE
                    const methodInput = document.createElement('input');
                    methodInput.type = 'hidden';
                    methodInput.name = '_method';
                    methodInput.value = 'DELETE';
                    form.appendChild(methodInput);

                    // Submit the form
                    document.body.appendChild(form);
                    form.submit();
                }
            });
        }

        // Ensure everything is ready when document loads
        $(document).ready(function() {
            console.log('📄 Suppliers page: Document ready');
            console.log('✅ jQuery version:', $.fn.jquery);
            console.log('✅ Add Supplier modal exists:', $('#addSupplierModal').length > 0);
            console.log('✅ Import modal exists:', $('#importModal').length > 0);
            console.log('✅ Edit Supplier modal exists:', $('#editSupplierModal').length > 0);
            
            // Check for success message in URL parameters
            const urlParams = new URLSearchParams(window.location.search);
            const successMessage = urlParams.get('success');
            if (successMessage) {
                // Create and show success alert
                const alertHtml = `
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        ${decodeURIComponent(successMessage)}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                `;
                $('.container-fluid.page__container').prepend(alertHtml);
                
                // Clean up URL by removing the success parameter
                urlParams.delete('success');
                const newUrl = window.location.pathname + (urlParams.toString() ? '?' + urlParams.toString() : '');
                window.history.replaceState({}, document.title, newUrl);
            }
            
            // Test modal functionality on page load (optional)
            $('#addSupplierModal').on('show.bs.modal', function() {
                console.log('📋 Add Supplier modal is showing...');
            });
            
            $('#addSupplierModal').on('shown.bs.modal', function() {
                console.log('✅ Add Supplier modal shown successfully');
            });
            
            // Handle edit supplier form submission
            $('#editSupplierForm').on('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const supplierId = this.action.split('/').pop();
                
                console.log('🔧 Submitting edit supplier form for ID:', supplierId);
                
                fetch(this.action, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        $('#editSupplierModal').modal('hide');
                        
                        // Create a success flash message and reload to show it
                        const url = new URL(window.location);
                        url.searchParams.set('success', encodeURIComponent(data.message || 'Supplier updated successfully'));
                        window.location.href = url.toString();
                    } else {
                        alert('Error updating supplier: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error updating supplier. Please try again.');
                });
            });
        });
    </script>
@endpush